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
27 #include <arpa/inet.h>
34 #include <linux/loop.h>
36 #include <netinet/in.h>
43 #include <sys/mount.h>
44 #include <sys/param.h>
45 #include <sys/prctl.h>
46 #include <sys/sendfile.h>
47 #include <sys/socket.h>
49 #include <sys/syscall.h>
50 #include <sys/sysmacros.h>
51 #include <sys/types.h>
52 #include <sys/utsname.h>
63 #include "confile_utils.h"
68 #include "lxcseccomp.h"
70 #include "memory_utils.h"
71 #include "namespace.h"
74 #include "raw_syscalls.h"
78 #include "storage/overlay.h"
79 #include "syscall_wrappers.h"
84 #include <sys/mkdev.h>
88 #include <sys/statvfs.h>
94 #include <../include/openpty.h>
98 #include <sys/capability.h>
101 #if HAVE_SYS_PERSONALITY_H
102 #include <sys/personality.h>
106 #include "include/strlcat.h"
110 #include <../include/lxcmntent.h>
115 #if !defined(HAVE_PRLIMIT) && defined(HAVE_PRLIMIT64)
116 #include <../include/prlimit.h>
119 lxc_log_define(conf
, lxc
);
121 /* The lxc_conf of the container currently being worked on in an API call.
122 * This is used in the error calls.
125 thread_local
struct lxc_conf
*current_config
;
127 struct lxc_conf
*current_config
;
130 char *lxchook_names
[NUM_LXC_HOOKS
] = {
159 static struct mount_opt mount_opt
[] = {
160 { "async", 1, MS_SYNCHRONOUS
},
161 { "atime", 1, MS_NOATIME
},
162 { "bind", 0, MS_BIND
},
163 { "defaults", 0, 0 },
164 { "dev", 1, MS_NODEV
},
165 { "diratime", 1, MS_NODIRATIME
},
166 { "dirsync", 0, MS_DIRSYNC
},
167 { "exec", 1, MS_NOEXEC
},
168 { "lazytime", 0, MS_LAZYTIME
},
169 { "mand", 0, MS_MANDLOCK
},
170 { "noatime", 0, MS_NOATIME
},
171 { "nodev", 0, MS_NODEV
},
172 { "nodiratime", 0, MS_NODIRATIME
},
173 { "noexec", 0, MS_NOEXEC
},
174 { "nomand", 1, MS_MANDLOCK
},
175 { "norelatime", 1, MS_RELATIME
},
176 { "nostrictatime", 1, MS_STRICTATIME
},
177 { "nosuid", 0, MS_NOSUID
},
178 { "rbind", 0, MS_BIND
|MS_REC
},
179 { "relatime", 0, MS_RELATIME
},
180 { "remount", 0, MS_REMOUNT
},
181 { "ro", 0, MS_RDONLY
},
182 { "rw", 1, MS_RDONLY
},
183 { "strictatime", 0, MS_STRICTATIME
},
184 { "suid", 1, MS_NOSUID
},
185 { "sync", 0, MS_SYNCHRONOUS
},
189 static struct mount_opt propagation_opt
[] = {
190 { "private", 0, MS_PRIVATE
},
191 { "shared", 0, MS_SHARED
},
192 { "slave", 0, MS_SLAVE
},
193 { "unbindable", 0, MS_UNBINDABLE
},
194 { "rprivate", 0, MS_PRIVATE
|MS_REC
},
195 { "rshared", 0, MS_SHARED
|MS_REC
},
196 { "rslave", 0, MS_SLAVE
|MS_REC
},
197 { "runbindable", 0, MS_UNBINDABLE
|MS_REC
},
201 static struct caps_opt caps_opt
[] = {
203 { "chown", CAP_CHOWN
},
204 { "dac_override", CAP_DAC_OVERRIDE
},
205 { "dac_read_search", CAP_DAC_READ_SEARCH
},
206 { "fowner", CAP_FOWNER
},
207 { "fsetid", CAP_FSETID
},
208 { "kill", CAP_KILL
},
209 { "setgid", CAP_SETGID
},
210 { "setuid", CAP_SETUID
},
211 { "setpcap", CAP_SETPCAP
},
212 { "linux_immutable", CAP_LINUX_IMMUTABLE
},
213 { "net_bind_service", CAP_NET_BIND_SERVICE
},
214 { "net_broadcast", CAP_NET_BROADCAST
},
215 { "net_admin", CAP_NET_ADMIN
},
216 { "net_raw", CAP_NET_RAW
},
217 { "ipc_lock", CAP_IPC_LOCK
},
218 { "ipc_owner", CAP_IPC_OWNER
},
219 { "sys_module", CAP_SYS_MODULE
},
220 { "sys_rawio", CAP_SYS_RAWIO
},
221 { "sys_chroot", CAP_SYS_CHROOT
},
222 { "sys_ptrace", CAP_SYS_PTRACE
},
223 { "sys_pacct", CAP_SYS_PACCT
},
224 { "sys_admin", CAP_SYS_ADMIN
},
225 { "sys_boot", CAP_SYS_BOOT
},
226 { "sys_nice", CAP_SYS_NICE
},
227 { "sys_resource", CAP_SYS_RESOURCE
},
228 { "sys_time", CAP_SYS_TIME
},
229 { "sys_tty_config", CAP_SYS_TTY_CONFIG
},
230 { "mknod", CAP_MKNOD
},
231 { "lease", CAP_LEASE
},
232 #ifdef CAP_AUDIT_READ
233 { "audit_read", CAP_AUDIT_READ
},
235 #ifdef CAP_AUDIT_WRITE
236 { "audit_write", CAP_AUDIT_WRITE
},
238 #ifdef CAP_AUDIT_CONTROL
239 { "audit_control", CAP_AUDIT_CONTROL
},
241 { "setfcap", CAP_SETFCAP
},
242 { "mac_override", CAP_MAC_OVERRIDE
},
243 { "mac_admin", CAP_MAC_ADMIN
},
245 { "syslog", CAP_SYSLOG
},
247 #ifdef CAP_WAKE_ALARM
248 { "wake_alarm", CAP_WAKE_ALARM
},
250 #ifdef CAP_BLOCK_SUSPEND
251 { "block_suspend", CAP_BLOCK_SUSPEND
},
256 static struct limit_opt limit_opt
[] = {
261 { "core", RLIMIT_CORE
},
264 { "cpu", RLIMIT_CPU
},
267 { "data", RLIMIT_DATA
},
270 { "fsize", RLIMIT_FSIZE
},
273 { "locks", RLIMIT_LOCKS
},
275 #ifdef RLIMIT_MEMLOCK
276 { "memlock", RLIMIT_MEMLOCK
},
278 #ifdef RLIMIT_MSGQUEUE
279 { "msgqueue", RLIMIT_MSGQUEUE
},
282 { "nice", RLIMIT_NICE
},
285 { "nofile", RLIMIT_NOFILE
},
288 { "nproc", RLIMIT_NPROC
},
291 { "rss", RLIMIT_RSS
},
294 { "rtprio", RLIMIT_RTPRIO
},
297 { "rttime", RLIMIT_RTTIME
},
299 #ifdef RLIMIT_SIGPENDING
300 { "sigpending", RLIMIT_SIGPENDING
},
303 { "stack", RLIMIT_STACK
},
307 static int run_buffer(char *buffer
)
309 __do_free
char *output
= NULL
;
311 struct lxc_popen_FILE
*f
;
313 f
= lxc_popen(buffer
);
315 SYSERROR("Failed to popen() %s", buffer
);
319 output
= malloc(LXC_LOG_BUFFER_SIZE
);
321 ERROR("Failed to allocate memory for %s", buffer
);
326 while (fgets(output
, LXC_LOG_BUFFER_SIZE
, f
->f
))
327 DEBUG("Script %s with output: %s", buffer
, output
);
331 SYSERROR("Script exited with error");
333 } else if (WIFEXITED(ret
) && WEXITSTATUS(ret
) != 0) {
334 ERROR("Script exited with status %d", WEXITSTATUS(ret
));
336 } else if (WIFSIGNALED(ret
)) {
337 ERROR("Script terminated by signal %d", WTERMSIG(ret
));
344 int run_script_argv(const char *name
, unsigned int hook_version
,
345 const char *section
, const char *script
,
346 const char *hookname
, char **argv
)
348 __do_free
char *buffer
= NULL
;
352 if (hook_version
== 0)
353 INFO("Executing script \"%s\" for container \"%s\", config "
354 "section \"%s\"", script
, name
, section
);
356 INFO("Executing script \"%s\" for container \"%s\"", script
, name
);
358 for (i
= 0; argv
&& argv
[i
]; i
++)
359 size
+= strlen(argv
[i
]) + 1;
361 size
+= STRLITERALLEN("exec");
363 size
+= strlen(script
);
369 if (hook_version
== 0) {
370 size
+= strlen(hookname
);
373 size
+= strlen(name
);
376 size
+= strlen(section
);
383 buffer
= malloc(size
);
387 if (hook_version
== 0)
388 buf_pos
= snprintf(buffer
, size
, "exec %s %s %s %s", script
, name
, section
, hookname
);
390 buf_pos
= snprintf(buffer
, size
, "exec %s", script
);
391 if (buf_pos
< 0 || (size_t)buf_pos
>= size
) {
392 ERROR("Failed to create command line for script \"%s\"", script
);
396 if (hook_version
== 1) {
397 ret
= setenv("LXC_HOOK_TYPE", hookname
, 1);
399 SYSERROR("Failed to set environment variable: "
400 "LXC_HOOK_TYPE=%s", hookname
);
403 TRACE("Set environment variable: LXC_HOOK_TYPE=%s", hookname
);
405 ret
= setenv("LXC_HOOK_SECTION", section
, 1);
407 SYSERROR("Failed to set environment variable: "
408 "LXC_HOOK_SECTION=%s", section
);
411 TRACE("Set environment variable: LXC_HOOK_SECTION=%s", section
);
413 if (strcmp(section
, "net") == 0) {
416 if (!argv
|| !argv
[0])
419 ret
= setenv("LXC_NET_TYPE", argv
[0], 1);
421 SYSERROR("Failed to set environment variable: "
422 "LXC_NET_TYPE=%s", argv
[0]);
425 TRACE("Set environment variable: LXC_NET_TYPE=%s", argv
[0]);
427 parent
= argv
[1] ? argv
[1] : "";
429 if (strcmp(argv
[0], "macvlan") == 0) {
430 ret
= setenv("LXC_NET_PARENT", parent
, 1);
432 SYSERROR("Failed to set environment "
433 "variable: LXC_NET_PARENT=%s", parent
);
436 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
437 } else if (strcmp(argv
[0], "phys") == 0) {
438 ret
= setenv("LXC_NET_PARENT", parent
, 1);
440 SYSERROR("Failed to set environment "
441 "variable: LXC_NET_PARENT=%s", parent
);
444 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
445 } else if (strcmp(argv
[0], "veth") == 0) {
446 char *peer
= argv
[2] ? argv
[2] : "";
448 ret
= setenv("LXC_NET_PEER", peer
, 1);
450 SYSERROR("Failed to set environment "
451 "variable: LXC_NET_PEER=%s", peer
);
454 TRACE("Set environment variable: LXC_NET_PEER=%s", peer
);
456 ret
= setenv("LXC_NET_PARENT", parent
, 1);
458 SYSERROR("Failed to set environment "
459 "variable: LXC_NET_PARENT=%s", parent
);
462 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
467 for (i
= 0; argv
&& argv
[i
]; i
++) {
468 size_t len
= size
- buf_pos
;
470 ret
= snprintf(buffer
+ buf_pos
, len
, " %s", argv
[i
]);
471 if (ret
< 0 || (size_t)ret
>= len
) {
472 ERROR("Failed to create command line for script \"%s\"", script
);
478 return run_buffer(buffer
);
481 int run_script(const char *name
, const char *section
, const char *script
, ...)
483 __do_free
char *buffer
= NULL
;
489 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
490 script
, name
, section
);
492 va_start(ap
, script
);
493 while ((p
= va_arg(ap
, char *)))
494 size
+= strlen(p
) + 1;
497 size
+= STRLITERALLEN("exec");
498 size
+= strlen(script
);
499 size
+= strlen(name
);
500 size
+= strlen(section
);
506 buffer
= must_realloc(NULL
, size
);
507 ret
= snprintf(buffer
, size
, "exec %s %s %s", script
, name
, section
);
508 if (ret
< 0 || ret
>= size
)
511 va_start(ap
, script
);
512 while ((p
= va_arg(ap
, char *))) {
513 int len
= size
- ret
;
515 rc
= snprintf(buffer
+ ret
, len
, " %s", p
);
516 if (rc
< 0 || rc
>= len
) {
524 return run_buffer(buffer
);
528 * if rootfs is a directory, then open ${rootfs}/.lxc-keep for writing for
529 * the duration of the container run, to prevent the container from marking
530 * the underlying fs readonly on shutdown. unlink the file immediately so
531 * no name pollution is happens.
532 * don't unlink on NFS to avoid random named stale handles.
533 * return -1 on error.
534 * return -2 if nothing needed to be pinned.
535 * return an open fd (>=0) if we pinned it.
537 int pin_rootfs(const char *rootfs
)
539 __do_free
char *absrootfs
= NULL
;
541 char absrootfspin
[PATH_MAX
];
545 if (rootfs
== NULL
|| strlen(rootfs
) == 0)
548 absrootfs
= realpath(rootfs
, NULL
);
552 ret
= stat(absrootfs
, &s
);
556 if (!S_ISDIR(s
.st_mode
))
559 ret
= snprintf(absrootfspin
, PATH_MAX
, "%s/.lxc-keep", absrootfs
);
560 if (ret
< 0 || ret
>= PATH_MAX
)
563 fd
= open(absrootfspin
, O_CREAT
| O_RDWR
, S_IWUSR
| S_IRUSR
);
567 ret
= fstatfs (fd
, &sfs
);
571 if (sfs
.f_type
== NFS_SUPER_MAGIC
) {
572 DEBUG("Rootfs on NFS, not unlinking pin file \"%s\"", absrootfspin
);
576 (void)unlink(absrootfspin
);
581 /* If we are asking to remount something, make sure that any NOEXEC etc are
584 unsigned long add_required_remount_flags(const char *s
, const char *d
,
590 unsigned long required_flags
= 0;
598 ret
= statvfs(s
, &sb
);
602 if (flags
& MS_REMOUNT
) {
603 if (sb
.f_flag
& MS_NOSUID
)
604 required_flags
|= MS_NOSUID
;
605 if (sb
.f_flag
& MS_NODEV
)
606 required_flags
|= MS_NODEV
;
607 if (sb
.f_flag
& MS_RDONLY
)
608 required_flags
|= MS_RDONLY
;
609 if (sb
.f_flag
& MS_NOEXEC
)
610 required_flags
|= MS_NOEXEC
;
613 if (sb
.f_flag
& MS_NOATIME
)
614 required_flags
|= MS_NOATIME
;
615 if (sb
.f_flag
& MS_NODIRATIME
)
616 required_flags
|= MS_NODIRATIME
;
617 if (sb
.f_flag
& MS_LAZYTIME
)
618 required_flags
|= MS_LAZYTIME
;
619 if (sb
.f_flag
& MS_RELATIME
)
620 required_flags
|= MS_RELATIME
;
621 if (sb
.f_flag
& MS_STRICTATIME
)
622 required_flags
|= MS_STRICTATIME
;
624 return flags
| required_flags
;
630 static int add_shmount_to_list(struct lxc_conf
*conf
)
632 char new_mount
[PATH_MAX
];
633 /* Offset for the leading '/' since the path_cont
634 * is absolute inside the container.
636 int offset
= 1, ret
= -1;
638 ret
= snprintf(new_mount
, sizeof(new_mount
),
639 "%s %s none bind,create=dir 0 0", conf
->shmount
.path_host
,
640 conf
->shmount
.path_cont
+ offset
);
641 if (ret
< 0 || (size_t)ret
>= sizeof(new_mount
))
644 return add_elem_to_mount_list(new_mount
, conf
);
647 static int lxc_mount_auto_mounts(struct lxc_conf
*conf
, int flags
, struct lxc_handler
*handler
)
654 const char *destination
;
658 } default_mounts
[] = {
659 /* Read-only bind-mounting... In older kernels, doing that
660 * required to do one MS_BIND mount and then
661 * MS_REMOUNT|MS_RDONLY the same one. According to mount(2)
662 * manpage, MS_BIND honors MS_RDONLY from kernel 2.6.26
663 * onwards. However, this apparently does not work on kernel
664 * 3.8. Unfortunately, on that very same kernel, doing the same
665 * trick as above doesn't seem to work either, there one needs
666 * to ALSO specify MS_BIND for the remount, otherwise the
667 * entire fs is remounted read-only or the mount fails because
668 * it's busy... MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for
669 * kernels as low as 2.6.32...
671 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
672 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
673 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys/net", "%r/proc/tty", NULL
, MS_BIND
, NULL
},
674 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys", "%r/proc/sys", NULL
, MS_BIND
, NULL
},
675 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
676 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/tty", "%r/proc/sys/net", NULL
, MS_MOVE
, NULL
},
677 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL
, MS_BIND
, NULL
},
678 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sysrq-trigger", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
679 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_RW
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
680 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RW
, "sysfs", "%r/sys", "sysfs", 0, NULL
},
681 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RO
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
, NULL
},
682 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys", "sysfs", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
683 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/sys", "%r/sys", NULL
, MS_BIND
, NULL
},
684 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, NULL
, "%r/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
685 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys/devices/virtual/net", "sysfs", 0, NULL
},
686 { 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
},
687 { 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
},
688 { 0, 0, NULL
, NULL
, NULL
, 0, NULL
}
691 for (i
= 0; default_mounts
[i
].match_mask
; i
++) {
693 unsigned long mflags
;
694 char *destination
= NULL
;
696 if ((flags
& default_mounts
[i
].match_mask
) != default_mounts
[i
].match_flag
)
699 if (default_mounts
[i
].source
) {
700 /* will act like strdup if %r is not present */
701 source
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].source
);
706 if (!default_mounts
[i
].destination
) {
707 ERROR("BUG: auto mounts destination %d was NULL", i
);
712 /* will act like strdup if %r is not present */
713 destination
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].destination
);
721 mflags
= add_required_remount_flags(source
, destination
,
722 default_mounts
[i
].flags
);
723 r
= safe_mount(source
, destination
, default_mounts
[i
].fstype
,
724 mflags
, default_mounts
[i
].options
,
725 conf
->rootfs
.path
? conf
->rootfs
.mount
: NULL
);
727 if (r
< 0 && errno
== ENOENT
) {
728 INFO("Mount source or target for \"%s\" on \"%s\" does "
729 "not exist. Skipping", source
, destination
);
732 SYSERROR("Failed to mount \"%s\" on \"%s\" with flags %lu", source
, destination
, mflags
);
743 if (flags
& LXC_AUTO_CGROUP_MASK
) {
746 cg_flags
= flags
& (LXC_AUTO_CGROUP_MASK
& ~LXC_AUTO_CGROUP_FORCE
);
747 /* If the type of cgroup mount was not specified, it depends on
748 * the container's capabilities as to what makes sense: if we
749 * have CAP_SYS_ADMIN, the read-only part can be remounted
750 * read-write anyway, so we may as well default to read-write;
751 * then the admin will not be given a false sense of security.
752 * (And if they really want mixed r/o r/w, then they can
753 * explicitly specify :mixed.) OTOH, if the container lacks
754 * CAP_SYS_ADMIN, do only default to :mixed, because then the
755 * container can't remount it read-write.
757 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
|| cg_flags
== LXC_AUTO_CGROUP_FULL_NOSPEC
) {
758 int has_sys_admin
= 0;
760 if (!lxc_list_empty(&conf
->keepcaps
))
761 has_sys_admin
= in_caplist(CAP_SYS_ADMIN
, &conf
->keepcaps
);
763 has_sys_admin
= !in_caplist(CAP_SYS_ADMIN
, &conf
->caps
);
765 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
766 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_RW
: LXC_AUTO_CGROUP_MIXED
;
768 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_FULL_RW
: LXC_AUTO_CGROUP_FULL_MIXED
;
771 if (flags
& LXC_AUTO_CGROUP_FORCE
)
772 cg_flags
|= LXC_AUTO_CGROUP_FORCE
;
774 if (!handler
->cgroup_ops
->mount(handler
->cgroup_ops
,
776 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
778 SYSERROR("Failed to mount \"/sys/fs/cgroup\"");
783 if (flags
& LXC_AUTO_SHMOUNTS_MASK
) {
784 int ret
= add_shmount_to_list(conf
);
786 ERROR("Failed to add shmount entry to container config");
794 static int setup_utsname(struct utsname
*utsname
)
801 ret
= sethostname(utsname
->nodename
, strlen(utsname
->nodename
));
803 SYSERROR("Failed to set the hostname to \"%s\"", utsname
->nodename
);
807 INFO("Set hostname to \"%s\"", utsname
->nodename
);
812 struct dev_symlinks
{
817 static const struct dev_symlinks dev_symlinks
[] = {
818 { "/proc/self/fd", "fd" },
819 { "/proc/self/fd/0", "stdin" },
820 { "/proc/self/fd/1", "stdout" },
821 { "/proc/self/fd/2", "stderr" },
824 static int lxc_setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
830 for (i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
831 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
833 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s",
834 rootfs
->path
? rootfs
->mount
: "", d
->name
);
835 if (ret
< 0 || ret
>= PATH_MAX
)
838 /* Stat the path first. If we don't get an error accept it as
839 * is and don't try to create it
841 ret
= stat(path
, &s
);
845 ret
= symlink(d
->oldpath
, path
);
846 if (ret
&& errno
!= EEXIST
) {
847 if (errno
== EROFS
) {
848 WARN("Failed to create \"%s\". Read-only filesystem", path
);
850 SYSERROR("Failed to create \"%s\"", path
);
859 /* Build a space-separate list of ptys to pass to systemd. */
860 static bool append_ttyname(char **pp
, char *name
)
866 *pp
= malloc(strlen(name
) + strlen("container_ttys=") + 1);
870 sprintf(*pp
, "container_ttys=%s", name
);
874 size
= strlen(*pp
) + strlen(name
) + 2;
875 p
= realloc(*pp
, size
);
880 (void)strlcat(p
, " ", size
);
881 (void)strlcat(p
, name
, size
);
886 static int lxc_setup_ttys(struct lxc_conf
*conf
)
889 const struct lxc_tty_info
*ttys
= &conf
->ttys
;
890 char *ttydir
= ttys
->dir
;
891 char path
[PATH_MAX
], lxcpath
[PATH_MAX
];
893 if (!conf
->rootfs
.path
)
896 for (i
= 0; i
< ttys
->max
; i
++) {
897 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
899 ret
= snprintf(path
, sizeof(path
), "/dev/tty%d", i
+ 1);
900 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
904 /* create dev/lxc/tty%d" */
905 ret
= snprintf(lxcpath
, sizeof(lxcpath
),
906 "/dev/%s/tty%d", ttydir
, i
+ 1);
907 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
910 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
911 if (ret
< 0 && errno
!= EEXIST
) {
912 SYSERROR("Failed to create \"%s\"", lxcpath
);
917 if (ret
< 0 && errno
!= ENOENT
) {
918 SYSERROR("Failed to unlink \"%s\"", path
);
922 ret
= mount(tty
->name
, lxcpath
, "none", MS_BIND
, 0);
924 SYSWARN("Failed to bind mount \"%s\" onto \"%s\"",
928 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
,
931 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/tty%d",
933 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
936 ret
= symlink(lxcpath
, path
);
938 SYSERROR("Failed to create symlink \"%s\" -> \"%s\"",
943 /* If we populated /dev, then we need to create
946 ret
= mknod(path
, S_IFREG
| 0000, 0);
947 if (ret
< 0) /* this isn't fatal, continue */
948 SYSERROR("Failed to create \"%s\"", path
);
950 ret
= mount(tty
->name
, path
, "none", MS_BIND
, 0);
952 SYSERROR("Failed to mount '%s'->'%s'", tty
->name
, path
);
956 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, path
);
959 if (!append_ttyname(&conf
->ttys
.tty_names
, tty
->name
)) {
960 ERROR("Error setting up container_ttys string");
965 INFO("Finished setting up %zu /dev/tty<N> device(s)", ttys
->max
);
969 int lxc_allocate_ttys(struct lxc_conf
*conf
)
973 struct lxc_tty_info
*ttys
= &conf
->ttys
;
975 /* no tty in the configuration */
979 ttys
->tty
= malloc(sizeof(*ttys
->tty
) * ttys
->max
);
983 for (i
= 0; i
< ttys
->max
; i
++) {
984 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
986 tty
->master
= -EBADF
;
988 ret
= openpty(&tty
->master
, &tty
->slave
, NULL
, NULL
, NULL
);
990 SYSERROR("Failed to create tty %zu", i
);
992 lxc_delete_tty(ttys
);
996 ret
= ttyname_r(tty
->slave
, tty
->name
, sizeof(tty
->name
));
998 SYSERROR("Failed to retrieve name of tty %zu slave", i
);
1000 lxc_delete_tty(ttys
);
1004 DEBUG("Created tty \"%s\" with master fd %d and slave fd %d",
1005 tty
->name
, tty
->master
, tty
->slave
);
1007 /* Prevent leaking the file descriptors to the container */
1008 ret
= fd_cloexec(tty
->master
, true);
1010 SYSWARN("Failed to set FD_CLOEXEC flag on master fd %d of "
1011 "tty device \"%s\"", tty
->master
, tty
->name
);
1013 ret
= fd_cloexec(tty
->slave
, true);
1015 SYSWARN("Failed to set FD_CLOEXEC flag on slave fd %d of "
1016 "tty device \"%s\"", tty
->slave
, tty
->name
);
1021 INFO("Finished creating %zu tty devices", ttys
->max
);
1025 void lxc_delete_tty(struct lxc_tty_info
*ttys
)
1032 for (i
= 0; i
< ttys
->max
; i
++) {
1033 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1035 if (tty
->master
>= 0) {
1037 tty
->master
= -EBADF
;
1040 if (tty
->slave
>= 0) {
1042 tty
->slave
= -EBADF
;
1050 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
1054 struct lxc_conf
*conf
= handler
->conf
;
1055 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1056 int sock
= handler
->data_sock
[0];
1061 for (i
= 0; i
< ttys
->max
; i
++) {
1063 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1065 ttyfds
[0] = tty
->master
;
1066 ttyfds
[1] = tty
->slave
;
1068 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, 2, NULL
, 0);
1072 TRACE("Sent tty \"%s\" with master fd %d and slave fd %d to "
1073 "parent", tty
->name
, tty
->master
, tty
->slave
);
1077 SYSERROR("Failed to send %zu ttys to parent", ttys
->max
);
1079 TRACE("Sent %zu ttys to parent", ttys
->max
);
1084 static int lxc_create_ttys(struct lxc_handler
*handler
)
1087 struct lxc_conf
*conf
= handler
->conf
;
1089 ret
= lxc_allocate_ttys(conf
);
1091 ERROR("Failed to allocate ttys");
1095 ret
= lxc_send_ttys_to_parent(handler
);
1097 ERROR("Failed to send ttys to parent");
1101 if (!conf
->is_execute
) {
1102 ret
= lxc_setup_ttys(conf
);
1104 ERROR("Failed to setup ttys");
1109 if (conf
->ttys
.tty_names
) {
1110 ret
= setenv("container_ttys", conf
->ttys
.tty_names
, 1);
1112 SYSERROR("Failed to set \"container_ttys=%s\"", conf
->ttys
.tty_names
);
1118 lxc_delete_tty(&conf
->ttys
);
1123 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1124 * error, log it but don't fail yet.
1126 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
,
1127 const char *lxcpath
)
1129 __do_free
char *path
= NULL
;
1134 INFO("Preparing \"/dev\"");
1136 /* $(rootfs->mount) + "/dev/pts" + '\0' */
1137 clen
= (rootfs
->path
? strlen(rootfs
->mount
) : 0) + 9;
1138 path
= must_realloc(NULL
, clen
);
1140 ret
= snprintf(path
, clen
, "%s/dev", rootfs
->path
? rootfs
->mount
: "");
1141 if (ret
< 0 || (size_t)ret
>= clen
)
1144 cur_mask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1145 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1146 if (ret
< 0 && errno
!= EEXIST
) {
1147 SYSERROR("Failed to create \"/dev\" directory");
1152 ret
= safe_mount("none", path
, "tmpfs", 0, "size=500000,mode=755",
1153 rootfs
->path
? rootfs
->mount
: NULL
);
1155 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1158 TRACE("Mounted tmpfs on \"%s\"", path
);
1160 ret
= snprintf(path
, clen
, "%s/dev/pts", rootfs
->path
? rootfs
->mount
: "");
1161 if (ret
< 0 || (size_t)ret
>= clen
) {
1166 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1167 * If not, then create it and exit if that fails...
1169 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1170 if (ret
< 0 && errno
!= EEXIST
) {
1171 SYSERROR("Failed to create directory \"%s\"", path
);
1179 (void)umask(cur_mask
);
1181 INFO("Prepared \"/dev\"");
1185 struct lxc_device_node
{
1192 static const struct lxc_device_node lxc_devices
[] = {
1193 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1194 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1195 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1196 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1197 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1198 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1205 LXC_DEVNODE_PARTIAL
,
1209 static int lxc_fill_autodev(const struct lxc_rootfs
*rootfs
)
1212 char path
[PATH_MAX
];
1214 int use_mknod
= LXC_DEVNODE_MKNOD
;
1216 ret
= snprintf(path
, PATH_MAX
, "%s/dev",
1217 rootfs
->path
? rootfs
->mount
: "");
1218 if (ret
< 0 || ret
>= PATH_MAX
)
1221 /* ignore, just don't try to fill in */
1222 if (!dir_exists(path
))
1225 INFO("Populating \"/dev\"");
1227 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1228 for (i
= 0; i
< sizeof(lxc_devices
) / sizeof(lxc_devices
[0]); i
++) {
1229 char hostpath
[PATH_MAX
];
1230 const struct lxc_device_node
*device
= &lxc_devices
[i
];
1232 ret
= snprintf(path
, PATH_MAX
, "%s/dev/%s",
1233 rootfs
->path
? rootfs
->mount
: "", device
->name
);
1234 if (ret
< 0 || ret
>= PATH_MAX
)
1237 if (use_mknod
>= LXC_DEVNODE_MKNOD
) {
1238 ret
= mknod(path
, device
->mode
, makedev(device
->maj
, device
->min
));
1239 if (ret
== 0 || (ret
< 0 && errno
== EEXIST
)) {
1240 DEBUG("Created device node \"%s\"", path
);
1241 } else if (ret
< 0) {
1242 if (errno
!= EPERM
) {
1243 SYSERROR("Failed to create device node \"%s\"", path
);
1247 use_mknod
= LXC_DEVNODE_BIND
;
1250 /* Device nodes are fully useable. */
1251 if (use_mknod
== LXC_DEVNODE_OPEN
)
1254 if (use_mknod
== LXC_DEVNODE_MKNOD
) {
1256 * - https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=55956b59df336f6738da916dbb520b6e37df9fbd
1257 * - https://lists.linuxfoundation.org/pipermail/containers/2018-June/039176.html
1259 ret
= open(path
, O_RDONLY
| O_CLOEXEC
);
1262 /* Device nodes are fully useable. */
1263 use_mknod
= LXC_DEVNODE_OPEN
;
1267 SYSTRACE("Failed to open \"%s\" device", path
);
1268 /* Device nodes are only partially useable. */
1269 use_mknod
= LXC_DEVNODE_PARTIAL
;
1273 if (use_mknod
!= LXC_DEVNODE_PARTIAL
) {
1274 /* If we are dealing with partially functional device
1275 * nodes the prio mknod() call will have created the
1276 * device node so we can use it as a bind-mount target.
1278 ret
= mknod(path
, S_IFREG
| 0000, 0);
1279 if (ret
< 0 && errno
!= EEXIST
) {
1280 SYSERROR("Failed to create file \"%s\"", path
);
1285 /* Fallback to bind-mounting the device from the host. */
1286 ret
= snprintf(hostpath
, PATH_MAX
, "/dev/%s", device
->name
);
1287 if (ret
< 0 || ret
>= PATH_MAX
)
1290 ret
= safe_mount(hostpath
, path
, 0, MS_BIND
, NULL
,
1291 rootfs
->path
? rootfs
->mount
: NULL
);
1293 SYSERROR("Failed to bind mount host device node \"%s\" "
1294 "onto \"%s\"", hostpath
, path
);
1297 DEBUG("Bind mounted host device node \"%s\" onto \"%s\"",
1302 INFO("Populated \"/dev\"");
1306 static int lxc_mount_rootfs(struct lxc_conf
*conf
)
1309 struct lxc_storage
*bdev
;
1310 const struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
1312 if (!rootfs
->path
) {
1313 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
1315 SYSERROR("Failed to remount \"/\" MS_REC | MS_SLAVE");
1322 ret
= access(rootfs
->mount
, F_OK
);
1324 SYSERROR("Failed to access to \"%s\". Check it is present",
1329 bdev
= storage_init(conf
);
1331 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1332 rootfs
->path
, rootfs
->mount
,
1333 rootfs
->options
? rootfs
->options
: "(null)");
1337 ret
= bdev
->ops
->mount(bdev
);
1340 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1341 rootfs
->path
, rootfs
->mount
,
1342 rootfs
->options
? rootfs
->options
: "(null)");
1346 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
1347 rootfs
->path
, rootfs
->mount
,
1348 rootfs
->options
? rootfs
->options
: "(null)");
1353 int lxc_chroot(const struct lxc_rootfs
*rootfs
)
1357 char buf
[LXC_LINELEN
];
1360 char *root
= rootfs
->mount
;
1362 nroot
= realpath(root
, NULL
);
1364 SYSERROR("Failed to resolve \"%s\"", root
);
1374 /* We could use here MS_MOVE, but in userns this mount is locked and
1377 ret
= mount(nroot
, "/", NULL
, MS_REC
| MS_BIND
, NULL
);
1379 SYSERROR("Failed to mount \"%s\" onto \"/\" as MS_REC | MS_BIND", nroot
);
1385 ret
= mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
);
1387 SYSERROR("Failed to remount \"/\"");
1391 /* The following code cleans up inherited mounts which are not required
1394 * The mountinfo file shows not all mounts, if a few points have been
1395 * unmounted between read operations from the mountinfo. So we need to
1396 * read mountinfo a few times.
1398 * This loop can be skipped if a container uses userns, because all
1399 * inherited mounts are locked and we should live with all this trash.
1404 f
= fopen("./proc/self/mountinfo", "r");
1406 SYSERROR("Failed to open \"/proc/self/mountinfo\"");
1410 while (fgets(buf
, LXC_LINELEN
, f
)) {
1411 for (p
= buf
, i
=0; p
&& i
< 4; i
++)
1412 p
= strchr(p
+1, ' ');
1417 p2
= strchr(p
+1, ' ');
1424 if (strcmp(p
+ 1, "/") == 0)
1427 if (strcmp(p
+ 1, "/proc") == 0)
1430 ret
= umount2(p
, MNT_DETACH
);
1441 /* This also can be skipped if a container uses userns. */
1442 (void)umount2("./proc", MNT_DETACH
);
1444 /* It is weird, but chdir("..") moves us in a new root */
1447 SYSERROR("Failed to chdir(\"..\")");
1453 SYSERROR("Failed to chroot(\".\")");
1460 /* (The following explanation is copied verbatim from the kernel.)
1462 * pivot_root Semantics:
1463 * Moves the root file system of the current process to the directory put_old,
1464 * makes new_root as the new root file system of the current process, and sets
1465 * root/cwd of all processes which had them on the current root to new_root.
1468 * The new_root and put_old must be directories, and must not be on the
1469 * same file system as the current process root. The put_old must be
1470 * underneath new_root, i.e. adding a non-zero number of /.. to the string
1471 * pointed to by put_old must yield the same directory as new_root. No other
1472 * file system may be mounted on put_old. After all, new_root is a mountpoint.
1474 * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
1475 * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
1476 * in this situation.
1479 * - we don't move root/cwd if they are not at the root (reason: if something
1480 * cared enough to change them, it's probably wrong to force them elsewhere)
1481 * - it's okay to pick a root that isn't the root of a file system, e.g.
1482 * /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
1483 * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
1486 static int lxc_pivot_root(const char *rootfs
)
1489 int newroot
= -1, ret
= -1;
1491 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1493 SYSERROR("Failed to open old root directory");
1497 newroot
= open(rootfs
, O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1499 SYSERROR("Failed to open new root directory");
1503 /* change into new root fs */
1504 ret
= fchdir(newroot
);
1507 SYSERROR("Failed to change to new rootfs \"%s\"", rootfs
);
1511 /* pivot_root into our new root fs */
1512 ret
= pivot_root(".", ".");
1515 SYSERROR("Failed to pivot_root()");
1519 /* At this point the old-root is mounted on top of our new-root. To
1520 * unmounted it we must not be chdir'd into it, so escape back to
1523 ret
= fchdir(oldroot
);
1526 SYSERROR("Failed to enter old root directory");
1530 /* Make oldroot rslave to make sure our umounts don't propagate to the
1533 ret
= mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
);
1536 SYSERROR("Failed to make oldroot rslave");
1540 ret
= umount2(".", MNT_DETACH
);
1543 SYSERROR("Failed to detach old root directory");
1547 ret
= fchdir(newroot
);
1550 SYSERROR("Failed to re-enter new root directory");
1556 TRACE("pivot_root(\"%s\") successful", rootfs
);
1567 static int lxc_setup_rootfs_switch_root(const struct lxc_rootfs
*rootfs
)
1569 if (!rootfs
->path
) {
1570 DEBUG("Container does not have a rootfs");
1574 if (detect_ramfs_rootfs())
1575 return lxc_chroot(rootfs
);
1577 return lxc_pivot_root(rootfs
->mount
);
1580 static const struct id_map
*find_mapped_nsid_entry(struct lxc_conf
*conf
,
1584 struct lxc_list
*it
;
1586 struct id_map
*retmap
= NULL
;
1588 /* Shortcut for container's root mappings. */
1590 if (idtype
== ID_TYPE_UID
)
1591 return conf
->root_nsuid_map
;
1593 if (idtype
== ID_TYPE_GID
)
1594 return conf
->root_nsgid_map
;
1597 lxc_list_for_each(it
, &conf
->id_map
) {
1599 if (map
->idtype
!= idtype
)
1602 if (id
>= map
->nsid
&& id
< map
->nsid
+ map
->range
) {
1611 static int lxc_setup_devpts(struct lxc_conf
*conf
)
1615 char devpts_mntopts
[256];
1616 char *mntopt_sets
[5];
1617 char default_devpts_mntopts
[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
1619 if (conf
->pty_max
<= 0) {
1620 DEBUG("No new devpts instance will be mounted since no pts "
1621 "devices are requested");
1625 ret
= snprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%zu",
1626 default_devpts_mntopts
, conf
->pty_max
);
1627 if (ret
< 0 || (size_t)ret
>= sizeof(devpts_mntopts
))
1630 (void)umount2("/dev/pts", MNT_DETACH
);
1632 /* Create mountpoint for devpts instance. */
1633 ret
= mkdir("/dev/pts", 0755);
1634 if (ret
< 0 && errno
!= EEXIST
) {
1635 SYSERROR("Failed to create \"/dev/pts\" directory");
1640 mntopt_sets
[0] = devpts_mntopts
;
1642 /* !gid=5 && max= */
1643 mntopt_sets
[1] = devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1645 /* gid=5 && !max= */
1646 mntopt_sets
[2] = default_devpts_mntopts
;
1648 /* !gid=5 && !max= */
1649 mntopt_sets
[3] = default_devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1652 mntopt_sets
[4] = NULL
;
1654 for (ret
= -1, opts
= mntopt_sets
; opts
&& *opts
; opts
++) {
1655 /* mount new devpts instance */
1656 ret
= mount("devpts", "/dev/pts", "devpts", MS_NOSUID
| MS_NOEXEC
, *opts
);
1662 SYSERROR("Failed to mount new devpts instance");
1665 DEBUG("Mount new devpts instance with options \"%s\"", *opts
);
1667 /* Remove any pre-existing /dev/ptmx file. */
1668 ret
= remove("/dev/ptmx");
1670 if (errno
!= ENOENT
) {
1671 SYSERROR("Failed to remove existing \"/dev/ptmx\" file");
1675 DEBUG("Removed existing \"/dev/ptmx\" file");
1678 /* Create dummy /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1679 ret
= mknod("/dev/ptmx", S_IFREG
| 0000, 0);
1680 if (ret
< 0 && errno
!= EEXIST
) {
1681 SYSERROR("Failed to create dummy \"/dev/ptmx\" file as bind mount target");
1684 DEBUG("Created dummy \"/dev/ptmx\" file as bind mount target");
1686 /* Fallback option: create symlink /dev/ptmx -> /dev/pts/ptmx */
1687 ret
= mount("/dev/pts/ptmx", "/dev/ptmx", NULL
, MS_BIND
, NULL
);
1689 DEBUG("Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1692 /* Fallthrough and try to create a symlink. */
1693 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1696 /* Remove the dummy /dev/ptmx file we created above. */
1697 ret
= remove("/dev/ptmx");
1699 SYSERROR("Failed to remove existing \"/dev/ptmx\"");
1703 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1704 ret
= symlink("/dev/pts/ptmx", "/dev/ptmx");
1706 SYSERROR("Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1709 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1714 static int setup_personality(int persona
)
1718 #if HAVE_SYS_PERSONALITY_H
1722 ret
= personality(persona
);
1724 SYSERROR("Failed to set personality to \"0x%x\"", persona
);
1728 INFO("Set personality to \"0x%x\"", persona
);
1734 static int lxc_setup_dev_console(const struct lxc_rootfs
*rootfs
,
1735 const struct lxc_terminal
*console
)
1738 char path
[PATH_MAX
];
1739 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1741 if (console
->path
&& !strcmp(console
->path
, "none"))
1744 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1745 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1748 /* When we are asked to setup a console we remove any previous
1749 * /dev/console bind-mounts.
1751 if (file_exists(path
)) {
1752 ret
= lxc_unstack_mountpoint(path
, false);
1754 SYSERROR("Failed to unmount \"%s\"", path
);
1757 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1761 /* For unprivileged containers autodev or automounts will already have
1762 * taken care of creating /dev/console.
1764 ret
= mknod(path
, S_IFREG
| 0000, 0);
1765 if (ret
< 0 && errno
!= EEXIST
) {
1766 SYSERROR("Failed to create console");
1770 ret
= fchmod(console
->slave
, S_IXUSR
| S_IXGRP
);
1772 SYSERROR("Failed to set mode \"0%o\" to \"%s\"",
1773 S_IXUSR
| S_IXGRP
, console
->name
);
1777 ret
= safe_mount(console
->name
, path
, "none", MS_BIND
, 0, rootfs_path
);
1779 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, path
);
1783 DEBUG("Mounted pts device \"%s\" onto \"%s\"", console
->name
, path
);
1787 static int lxc_setup_ttydir_console(const struct lxc_rootfs
*rootfs
,
1788 const struct lxc_terminal
*console
,
1792 char path
[PATH_MAX
], lxcpath
[PATH_MAX
];
1793 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1795 if (console
->path
&& !strcmp(console
->path
, "none"))
1798 /* create rootfs/dev/<ttydir> directory */
1799 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs_path
, ttydir
);
1800 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1803 ret
= mkdir(path
, 0755);
1804 if (ret
&& errno
!= EEXIST
) {
1805 SYSERROR("Failed to create \"%s\"", path
);
1808 DEBUG("Created directory for console and tty devices at \"%s\"", path
);
1810 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/dev/%s/console", rootfs_path
, ttydir
);
1811 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1814 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
1815 if (ret
< 0 && errno
!= EEXIST
) {
1816 SYSERROR("Failed to create \"%s\"", lxcpath
);
1820 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1821 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1824 if (file_exists(path
)) {
1825 ret
= lxc_unstack_mountpoint(path
, false);
1827 SYSERROR("Failed to unmount \"%s\"", path
);
1830 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1834 ret
= mknod(path
, S_IFREG
| 0000, 0);
1835 if (ret
< 0 && errno
!= EEXIST
) {
1836 SYSERROR("Failed to create console");
1840 ret
= fchmod(console
->slave
, S_IXUSR
| S_IXGRP
);
1842 SYSERROR("Failed to set mode \"0%o\" to \"%s\"",
1843 S_IXUSR
| S_IXGRP
, console
->name
);
1847 /* bind mount console->name to '/dev/<ttydir>/console' */
1848 ret
= safe_mount(console
->name
, lxcpath
, "none", MS_BIND
, 0, rootfs_path
);
1850 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1853 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1855 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
1856 ret
= safe_mount(lxcpath
, path
, "none", MS_BIND
, 0, rootfs_path
);
1858 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1861 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1863 DEBUG("Console has been setup under \"%s\" and mounted to \"%s\"", lxcpath
, path
);
1867 static int lxc_setup_console(const struct lxc_rootfs
*rootfs
,
1868 const struct lxc_terminal
*console
, char *ttydir
)
1872 return lxc_setup_dev_console(rootfs
, console
);
1874 return lxc_setup_ttydir_console(rootfs
, console
, ttydir
);
1877 static void parse_mntopt(char *opt
, unsigned long *flags
, char **data
, size_t size
)
1879 struct mount_opt
*mo
;
1881 /* If opt is found in mount_opt, set or clear flags.
1882 * Otherwise append it to data. */
1884 for (mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
1885 if (strncmp(opt
, mo
->name
, strlen(mo
->name
)) == 0) {
1887 *flags
&= ~mo
->flag
;
1895 (void)strlcat(*data
, ",", size
);
1897 (void)strlcat(*data
, opt
, size
);
1900 int parse_mntopts(const char *mntopts
, unsigned long *mntflags
, char **mntdata
)
1911 s
= strdup(mntopts
);
1915 size
= strlen(s
) + 1;
1916 data
= malloc(size
);
1923 lxc_iterate_parts(p
, s
, ",")
1924 parse_mntopt(p
, mntflags
, &data
, size
);
1935 static void parse_propagationopt(char *opt
, unsigned long *flags
)
1937 struct mount_opt
*mo
;
1939 /* If opt is found in propagation_opt, set or clear flags. */
1940 for (mo
= &propagation_opt
[0]; mo
->name
!= NULL
; mo
++) {
1941 if (strncmp(opt
, mo
->name
, strlen(mo
->name
)) != 0)
1945 *flags
&= ~mo
->flag
;
1953 int parse_propagationopts(const char *mntopts
, unsigned long *pflags
)
1960 s
= strdup(mntopts
);
1962 SYSERROR("Failed to allocate memory");
1967 lxc_iterate_parts(p
, s
, ",")
1968 parse_propagationopt(p
, pflags
);
1974 static void null_endofword(char *word
)
1976 while (*word
&& *word
!= ' ' && *word
!= '\t')
1981 /* skip @nfields spaces in @src */
1982 static char *get_field(char *src
, int nfields
)
1987 for (i
= 0; i
< nfields
; i
++) {
1988 while (*p
&& *p
!= ' ' && *p
!= '\t')
2000 static int mount_entry(const char *fsname
, const char *target
,
2001 const char *fstype
, unsigned long mountflags
,
2002 unsigned long pflags
, const char *data
, bool optional
,
2003 bool dev
, bool relative
, const char *rootfs
)
2006 char srcbuf
[PATH_MAX
];
2007 const char *srcpath
= fsname
;
2013 ret
= snprintf(srcbuf
, PATH_MAX
, "%s/%s", rootfs
? rootfs
: "/", fsname
? fsname
: "");
2014 if (ret
< 0 || ret
>= PATH_MAX
) {
2015 ERROR("source path is too long");
2021 ret
= safe_mount(srcpath
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
2025 SYSINFO("Failed to mount \"%s\" on \"%s\" (optional)",
2026 srcpath
? srcpath
: "(null)", target
);
2030 SYSERROR("Failed to mount \"%s\" on \"%s\"",
2031 srcpath
? srcpath
: "(null)", target
);
2035 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
2036 unsigned long rqd_flags
= 0;
2038 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount "
2039 "options", srcpath
? srcpath
: "(none)", target
? target
: "(none)");
2041 if (mountflags
& MS_RDONLY
)
2042 rqd_flags
|= MS_RDONLY
;
2044 if (srcpath
&& statvfs(srcpath
, &sb
) == 0) {
2045 unsigned long required_flags
= rqd_flags
;
2047 if (sb
.f_flag
& MS_NOSUID
)
2048 required_flags
|= MS_NOSUID
;
2050 if (sb
.f_flag
& MS_NODEV
&& !dev
)
2051 required_flags
|= MS_NODEV
;
2053 if (sb
.f_flag
& MS_RDONLY
)
2054 required_flags
|= MS_RDONLY
;
2056 if (sb
.f_flag
& MS_NOEXEC
)
2057 required_flags
|= MS_NOEXEC
;
2059 DEBUG("Flags for \"%s\" were %lu, required extra flags "
2060 "are %lu", srcpath
, sb
.f_flag
, required_flags
);
2062 /* If this was a bind mount request, and required_flags
2063 * does not have any flags which are not already in
2064 * mountflags, then skip the remount.
2066 if (!(mountflags
& MS_REMOUNT
)) {
2067 if (!(required_flags
& ~mountflags
) &&
2069 DEBUG("Mountflags already were %lu, "
2070 "skipping remount", mountflags
);
2075 mountflags
|= required_flags
;
2079 ret
= mount(srcpath
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
2082 SYSINFO("Failed to mount \"%s\" on \"%s\" (optional)",
2083 srcpath
? srcpath
: "(null)", target
);
2087 SYSERROR("Failed to mount \"%s\" on \"%s\"",
2088 srcpath
? srcpath
: "(null)", target
);
2097 ret
= mount(NULL
, target
, NULL
, pflags
, NULL
);
2100 SYSINFO("Failed to change mount propagation "
2101 "for \"%s\" (optional)", target
);
2104 SYSERROR("Failed to change mount propagation "
2105 "for \"%s\" (optional)", target
);
2109 DEBUG("Changed mount propagation for \"%s\"", target
);
2112 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
2113 srcpath
? srcpath
: "(null)", target
, fstype
);
2118 /* Remove "optional", "create=dir", and "create=file" from mntopt */
2119 static void cull_mntent_opt(struct mntent
*mntent
)
2130 for (i
= 0; list
[i
]; i
++) {
2133 p
= strstr(mntent
->mnt_opts
, list
[i
]);
2137 p2
= strchr(p
, ',');
2139 /* no more mntopts, so just chop it here */
2144 memmove(p
, p2
+ 1, strlen(p2
+ 1) + 1);
2148 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
2150 const struct lxc_rootfs
*rootfs
,
2151 const char *lxc_name
, const char *lxc_path
)
2156 if (strncmp(mntent
->mnt_type
, "overlay", 7) == 0) {
2157 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
2162 if (hasmntopt(mntent
, "create=dir")) {
2163 ret
= mkdir_p(path
, 0755);
2164 if (ret
< 0 && errno
!= EEXIST
) {
2165 SYSERROR("Failed to create directory \"%s\"", path
);
2170 if (!hasmntopt(mntent
, "create=file"))
2173 ret
= access(path
, F_OK
);
2183 ret
= mkdir_p(p2
, 0755);
2185 if (ret
< 0 && errno
!= EEXIST
) {
2186 SYSERROR("Failed to create directory \"%s\"", path
);
2190 ret
= mknod(path
, S_IFREG
| 0000, 0);
2191 if (ret
< 0 && errno
!= EEXIST
)
2197 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2198 * without a rootfs. */
2199 static inline int mount_entry_on_generic(struct mntent
*mntent
,
2201 const struct lxc_rootfs
*rootfs
,
2202 const char *lxc_name
,
2203 const char *lxc_path
)
2206 unsigned long mntflags
;
2208 bool dev
, optional
, relative
;
2209 unsigned long pflags
= 0;
2210 char *rootfs_path
= NULL
;
2212 optional
= hasmntopt(mntent
, "optional") != NULL
;
2213 dev
= hasmntopt(mntent
, "dev") != NULL
;
2214 relative
= hasmntopt(mntent
, "relative") != NULL
;
2216 if (rootfs
&& rootfs
->path
)
2217 rootfs_path
= rootfs
->mount
;
2219 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
2227 cull_mntent_opt(mntent
);
2229 ret
= parse_propagationopts(mntent
->mnt_opts
, &pflags
);
2233 ret
= parse_mntopts(mntent
->mnt_opts
, &mntflags
, &mntdata
);
2237 ret
= mount_entry(mntent
->mnt_fsname
, path
, mntent
->mnt_type
, mntflags
,
2238 pflags
, mntdata
, optional
, dev
, relative
, rootfs_path
);
2244 static inline int mount_entry_on_systemfs(struct mntent
*mntent
)
2247 char path
[PATH_MAX
];
2249 /* For containers created without a rootfs all mounts are treated as
2250 * absolute paths starting at / on the host.
2252 if (mntent
->mnt_dir
[0] != '/')
2253 ret
= snprintf(path
, sizeof(path
), "/%s", mntent
->mnt_dir
);
2255 ret
= snprintf(path
, sizeof(path
), "%s", mntent
->mnt_dir
);
2256 if (ret
< 0 || ret
>= sizeof(path
))
2259 return mount_entry_on_generic(mntent
, path
, NULL
, NULL
, NULL
);
2262 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
2263 const struct lxc_rootfs
*rootfs
,
2264 const char *lxc_name
,
2265 const char *lxc_path
)
2269 const char *lxcpath
;
2270 char path
[PATH_MAX
];
2273 lxcpath
= lxc_global_config_value("lxc.lxcpath");
2277 /* If rootfs->path is a blockdev path, allow container fstab to use
2278 * <lxcpath>/<name>/rootfs" as the target prefix.
2280 ret
= snprintf(path
, PATH_MAX
, "%s/%s/rootfs", lxcpath
, lxc_name
);
2281 if (ret
< 0 || ret
>= PATH_MAX
)
2284 aux
= strstr(mntent
->mnt_dir
, path
);
2286 offset
= strlen(path
);
2291 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
2293 WARN("Ignoring mount point \"%s\"", mntent
->mnt_dir
);
2296 offset
= strlen(rootfs
->path
);
2299 ret
= snprintf(path
, PATH_MAX
, "%s/%s", rootfs
->mount
, aux
+ offset
);
2300 if (ret
< 0 || ret
>= PATH_MAX
)
2303 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2306 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
2307 const struct lxc_rootfs
*rootfs
,
2308 const char *lxc_name
,
2309 const char *lxc_path
)
2312 char path
[PATH_MAX
];
2314 /* relative to root mount point */
2315 ret
= snprintf(path
, sizeof(path
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2316 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
2319 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2322 static int mount_file_entries(const struct lxc_conf
*conf
,
2323 const struct lxc_rootfs
*rootfs
, FILE *file
,
2324 const char *lxc_name
, const char *lxc_path
)
2327 struct mntent mntent
;
2329 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2333 ret
= mount_entry_on_systemfs(&mntent
);
2334 else if (mntent
.mnt_dir
[0] != '/')
2335 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2336 lxc_name
, lxc_path
);
2338 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2339 lxc_name
, lxc_path
);
2344 if (!feof(file
) || ferror(file
)) {
2345 ERROR("Failed to parse mount entries");
2352 static int setup_mount(const struct lxc_conf
*conf
,
2353 const struct lxc_rootfs
*rootfs
, const char *fstab
,
2354 const char *lxc_name
, const char *lxc_path
)
2362 f
= setmntent(fstab
, "r");
2364 SYSERROR("Failed to open \"%s\"", fstab
);
2368 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2370 ERROR("Failed to set up mount entries");
2377 * In order for nested containers to be able to mount /proc and /sys they need
2378 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2380 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2381 * apparmor rule to deny access to them. This is mostly for convenience: The
2382 * container's root user can mount them anyway and thus has access to the two
2383 * file systems. But a non-root user in the container should not be allowed to
2384 * access them as a side effect without explicitly allowing it.
2386 static const char nesting_helpers
[] =
2387 "proc dev/.lxc/proc proc create=dir,optional 0 0\n"
2388 "sys dev/.lxc/sys sysfs create=dir,optional 0 0\n";
2390 FILE *make_anonymous_mount_file(struct lxc_list
*mount
,
2391 bool include_nesting_helpers
)
2395 struct lxc_list
*iterator
;
2398 fd
= memfd_create(".lxc_mount_file", MFD_CLOEXEC
);
2400 char template[] = P_tmpdir
"/.lxc_mount_file_XXXXXX";
2402 if (errno
!= ENOSYS
)
2405 fd
= lxc_make_tmpfile(template, true);
2407 SYSERROR("Could not create temporary mount file");
2411 TRACE("Created temporary mount file");
2414 lxc_list_for_each (iterator
, mount
) {
2417 mount_entry
= iterator
->elem
;
2418 len
= strlen(mount_entry
);
2420 ret
= lxc_write_nointr(fd
, mount_entry
, len
);
2424 ret
= lxc_write_nointr(fd
, "\n", 1);
2429 if (include_nesting_helpers
) {
2430 ret
= lxc_write_nointr(fd
, nesting_helpers
,
2431 STRARRAYLEN(nesting_helpers
));
2432 if (ret
!= STRARRAYLEN(nesting_helpers
))
2436 ret
= lseek(fd
, 0, SEEK_SET
);
2440 return fdopen(fd
, "r+");
2443 SYSERROR("Failed to write mount entry to temporary mount file");
2448 static int setup_mount_entries(const struct lxc_conf
*conf
,
2449 const struct lxc_rootfs
*rootfs
,
2450 struct lxc_list
*mount
, const char *lxc_name
,
2451 const char *lxc_path
)
2456 f
= make_anonymous_mount_file(mount
, conf
->lsm_aa_allow_nesting
);
2460 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2466 static int parse_cap(const char *cap
)
2470 size_t end
= sizeof(caps_opt
) / sizeof(caps_opt
[0]);
2473 if (strcmp(cap
, "none") == 0)
2476 for (i
= 0; i
< end
; i
++) {
2477 if (strcmp(cap
, caps_opt
[i
].name
))
2480 capid
= caps_opt
[i
].value
;
2485 /* Try to see if it's numeric, so the user may specify
2486 * capabilities that the running kernel knows about but we
2490 capid
= strtol(cap
, &ptr
, 10);
2491 if (!ptr
|| *ptr
!= '\0' || errno
!= 0)
2492 /* not a valid number */
2494 else if (capid
> lxc_caps_last_cap())
2495 /* we have a number but it's not a valid
2503 int in_caplist(int cap
, struct lxc_list
*caps
)
2506 struct lxc_list
*iterator
;
2508 lxc_list_for_each (iterator
, caps
) {
2509 capid
= parse_cap(iterator
->elem
);
2517 static int setup_caps(struct lxc_list
*caps
)
2521 struct lxc_list
*iterator
;
2523 lxc_list_for_each (iterator
, caps
) {
2526 drop_entry
= iterator
->elem
;
2528 capid
= parse_cap(drop_entry
);
2530 ERROR("unknown capability %s", drop_entry
);
2534 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(capid
), prctl_arg(0),
2535 prctl_arg(0), prctl_arg(0));
2537 SYSERROR("Failed to remove %s capability", drop_entry
);
2540 DEBUG("Dropped %s (%d) capability", drop_entry
, capid
);
2543 DEBUG("Capabilities have been setup");
2547 static int dropcaps_except(struct lxc_list
*caps
)
2549 __do_free
int *caplist
= NULL
;
2550 int i
, capid
, numcaps
;
2552 struct lxc_list
*iterator
;
2554 numcaps
= lxc_caps_last_cap() + 1;
2555 if (numcaps
<= 0 || numcaps
> 200)
2557 TRACE("Found %d capabilities", numcaps
);
2559 /* caplist[i] is 1 if we keep capability i */
2560 caplist
= must_realloc(NULL
, numcaps
* sizeof(int));
2561 memset(caplist
, 0, numcaps
* sizeof(int));
2563 lxc_list_for_each (iterator
, caps
) {
2564 keep_entry
= iterator
->elem
;
2566 capid
= parse_cap(keep_entry
);
2571 ERROR("Unknown capability %s", keep_entry
);
2575 DEBUG("Keep capability %s (%d)", keep_entry
, capid
);
2579 for (i
= 0; i
< numcaps
; i
++) {
2585 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(i
), prctl_arg(0),
2586 prctl_arg(0), prctl_arg(0));
2588 SYSERROR("Failed to remove capability %d", i
);
2593 DEBUG("Capabilities have been setup");
2597 static int parse_resource(const char *res
)
2603 for (i
= 0; i
< sizeof(limit_opt
) / sizeof(limit_opt
[0]); ++i
)
2604 if (strcmp(res
, limit_opt
[i
].name
) == 0)
2605 return limit_opt
[i
].value
;
2607 /* Try to see if it's numeric, so the user may specify
2608 * resources that the running kernel knows about but
2611 ret
= lxc_safe_int(res
, &resid
);
2618 int setup_resource_limits(struct lxc_list
*limits
, pid_t pid
)
2621 struct lxc_list
*it
;
2622 struct lxc_limit
*lim
;
2624 lxc_list_for_each (it
, limits
) {
2627 resid
= parse_resource(lim
->resource
);
2629 ERROR("Unknown resource %s", lim
->resource
);
2633 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
2634 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0) {
2635 SYSERROR("Failed to set limit %s", lim
->resource
);
2639 TRACE("Setup \"%s\" limit", lim
->resource
);
2641 ERROR("Cannot set limit \"%s\" as prlimit is missing", lim
->resource
);
2649 int setup_sysctl_parameters(struct lxc_list
*sysctls
)
2651 struct lxc_list
*it
;
2652 struct lxc_sysctl
*elem
;
2655 char filename
[PATH_MAX
] = {0};
2657 lxc_list_for_each (it
, sysctls
) {
2659 tmp
= lxc_string_replace(".", "/", elem
->key
);
2661 ERROR("Failed to replace key %s", elem
->key
);
2665 ret
= snprintf(filename
, sizeof(filename
), "/proc/sys/%s", tmp
);
2667 if (ret
< 0 || (size_t)ret
>= sizeof(filename
)) {
2668 ERROR("Error setting up sysctl parameters path");
2672 ret
= lxc_write_to_file(filename
, elem
->value
,
2673 strlen(elem
->value
), false, 0666);
2675 SYSERROR("Failed to setup sysctl parameters %s to %s",
2676 elem
->key
, elem
->value
);
2684 int setup_proc_filesystem(struct lxc_list
*procs
, pid_t pid
)
2686 struct lxc_list
*it
;
2687 struct lxc_proc
*elem
;
2690 char filename
[PATH_MAX
] = {0};
2692 lxc_list_for_each (it
, procs
) {
2694 tmp
= lxc_string_replace(".", "/", elem
->filename
);
2696 ERROR("Failed to replace key %s", elem
->filename
);
2700 ret
= snprintf(filename
, sizeof(filename
), "/proc/%d/%s", pid
, tmp
);
2702 if (ret
< 0 || (size_t)ret
>= sizeof(filename
)) {
2703 ERROR("Error setting up proc filesystem path");
2707 ret
= lxc_write_to_file(filename
, elem
->value
,
2708 strlen(elem
->value
), false, 0666);
2710 SYSERROR("Failed to setup proc filesystem %s to %s",
2711 elem
->filename
, elem
->value
);
2719 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
2721 struct lxc_conf
*lxc_conf_init(void)
2724 struct lxc_conf
*new;
2726 new = malloc(sizeof(*new));
2729 memset(new, 0, sizeof(*new));
2731 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
2732 new->personality
= -1;
2734 new->console
.buffer_size
= 0;
2735 new->console
.log_path
= NULL
;
2736 new->console
.log_fd
= -1;
2737 new->console
.log_size
= 0;
2738 new->console
.path
= NULL
;
2739 new->console
.peer
= -1;
2740 new->console
.proxy
.busy
= -1;
2741 new->console
.proxy
.master
= -1;
2742 new->console
.proxy
.slave
= -1;
2743 new->console
.master
= -1;
2744 new->console
.slave
= -1;
2745 new->console
.name
[0] = '\0';
2746 memset(&new->console
.ringbuf
, 0, sizeof(struct lxc_ringbuf
));
2747 new->maincmd_fd
= -1;
2748 new->monitor_signal_pdeath
= SIGKILL
;
2750 new->rootfs
.mount
= strdup(default_rootfs_mount
);
2751 if (!new->rootfs
.mount
) {
2755 new->rootfs
.managed
= true;
2757 lxc_list_init(&new->cgroup
);
2758 lxc_list_init(&new->cgroup2
);
2759 lxc_list_init(&new->network
);
2760 lxc_list_init(&new->mount_list
);
2761 lxc_list_init(&new->caps
);
2762 lxc_list_init(&new->keepcaps
);
2763 lxc_list_init(&new->id_map
);
2764 new->root_nsuid_map
= NULL
;
2765 new->root_nsgid_map
= NULL
;
2766 lxc_list_init(&new->includes
);
2767 lxc_list_init(&new->aliens
);
2768 lxc_list_init(&new->environment
);
2769 lxc_list_init(&new->limits
);
2770 lxc_list_init(&new->sysctls
);
2771 lxc_list_init(&new->procs
);
2772 new->hooks_version
= 0;
2773 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++)
2774 lxc_list_init(&new->hooks
[i
]);
2775 lxc_list_init(&new->groups
);
2776 lxc_list_init(&new->state_clients
);
2777 new->lsm_aa_profile
= NULL
;
2778 lxc_list_init(&new->lsm_aa_raw
);
2779 new->lsm_se_context
= NULL
;
2780 new->tmp_umount_proc
= false;
2781 new->tmp_umount_proc
= 0;
2782 new->shmount
.path_host
= NULL
;
2783 new->shmount
.path_cont
= NULL
;
2785 /* if running in a new user namespace, init and COMMAND
2786 * default to running as UID/GID 0 when using lxc-execute */
2789 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
2790 memset(&new->ns_share
, 0, sizeof(char *) * LXC_NS_MAX
);
2795 int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
2799 char path
[PATH_MAX
];
2801 if (geteuid() != 0 && idtype
== ID_TYPE_GID
) {
2804 ret
= snprintf(path
, PATH_MAX
, "/proc/%d/setgroups", pid
);
2805 if (ret
< 0 || ret
>= PATH_MAX
)
2808 fd
= open(path
, O_WRONLY
);
2809 if (fd
< 0 && errno
!= ENOENT
) {
2810 SYSERROR("Failed to open \"%s\"", path
);
2815 buflen
= STRLITERALLEN("deny\n");
2817 ret
= lxc_write_nointr(fd
, "deny\n", buflen
);
2819 if (ret
!= buflen
) {
2820 SYSERROR("Failed to write \"deny\" to "
2821 "\"/proc/%d/setgroups\"", pid
);
2824 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid
);
2828 ret
= snprintf(path
, PATH_MAX
, "/proc/%d/%cid_map", pid
,
2829 idtype
== ID_TYPE_UID
? 'u' : 'g');
2830 if (ret
< 0 || ret
>= PATH_MAX
)
2833 fd
= open(path
, O_WRONLY
);
2835 SYSERROR("Failed to open \"%s\"", path
);
2840 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
2842 if (ret
!= buf_size
) {
2843 SYSERROR("Failed to write %cid mapping to \"%s\"",
2844 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
2851 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2853 * @return 1 if functional binary was found
2854 * @return 0 if binary exists but is lacking privilege
2855 * @return -ENOENT if binary does not exist
2856 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2858 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
2865 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
2868 path
= on_path(binary
, NULL
);
2872 ret
= stat(path
, &st
);
2878 /* Check if the binary is setuid. */
2879 if (st
.st_mode
& S_ISUID
) {
2880 DEBUG("The binary \"%s\" does have the setuid bit set", path
);
2885 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
2886 /* Check if it has the CAP_SETUID capability. */
2887 if ((cap
& CAP_SETUID
) &&
2888 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
2889 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
)) {
2890 DEBUG("The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE "
2891 "and CAP_PERMITTED sets", path
);
2896 /* Check if it has the CAP_SETGID capability. */
2897 if ((cap
& CAP_SETGID
) &&
2898 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
2899 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
)) {
2900 DEBUG("The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE "
2901 "and CAP_PERMITTED sets", path
);
2906 /* If we cannot check for file capabilities we need to give the benefit
2907 * of the doubt. Otherwise we might fail even though all the necessary
2908 * file capabilities are set.
2910 DEBUG("Cannot check for file capabilities as full capability support is "
2911 "missing. Manual intervention needed");
2920 int lxc_map_ids_exec_wrapper(void *args
)
2922 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
2926 int lxc_map_ids(struct lxc_list
*idmap
, pid_t pid
)
2931 char cmd_output
[PATH_MAX
];
2933 struct lxc_list
*iterator
;
2935 /* strlen("new@idmap") = 9
2939 * INTTYPE_TO_STRLEN(uint32_t)
2943 * We add some additional space to make sure that we really have
2944 * LXC_IDMAPLEN bytes available for our the {g,u]id mapping.
2946 int ret
= 0, gidmap
= 0, uidmap
= 0;
2947 char mapbuf
[9 + 1 + INTTYPE_TO_STRLEN(uint32_t) + 1 + LXC_IDMAPLEN
] = {0};
2948 bool had_entry
= false, use_shadow
= false;
2949 int hostuid
, hostgid
;
2951 hostuid
= geteuid();
2952 hostgid
= getegid();
2954 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2955 * ranges, then insist that root also reserve ranges in subuid. This
2956 * will protected it by preventing another user from being handed the
2959 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
2960 if (uidmap
== -ENOENT
)
2961 WARN("newuidmap binary is missing");
2963 WARN("newuidmap is lacking necessary privileges");
2965 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
2966 if (gidmap
== -ENOENT
)
2967 WARN("newgidmap binary is missing");
2969 WARN("newgidmap is lacking necessary privileges");
2971 if (uidmap
> 0 && gidmap
> 0) {
2972 DEBUG("Functional newuidmap and newgidmap binary found");
2975 /* In case unprivileged users run application containers via
2976 * execute() or a start*() there are valid cases where they may
2977 * only want to map their own {g,u}id. Let's not block them from
2978 * doing so by requiring geteuid() == 0.
2980 DEBUG("No newuidmap and newgidmap binary found. Trying to "
2981 "write directly with euid %d", hostuid
);
2984 /* Check if we really need to use newuidmap and newgidmap.
2985 * If the user is only remapping his own {g,u}id, we don't need it.
2987 if (use_shadow
&& lxc_list_len(idmap
) == 2) {
2989 lxc_list_for_each(iterator
, idmap
) {
2990 map
= iterator
->elem
;
2991 if (map
->idtype
== ID_TYPE_UID
&& map
->range
== 1 &&
2992 map
->nsid
== hostuid
&& map
->hostid
== hostuid
)
2994 if (map
->idtype
== ID_TYPE_GID
&& map
->range
== 1 &&
2995 map
->nsid
== hostgid
&& map
->hostid
== hostgid
)
3002 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
3003 type
++, u_or_g
= 'g') {
3007 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
3009 lxc_list_for_each(iterator
, idmap
) {
3010 map
= iterator
->elem
;
3011 if (map
->idtype
!= type
)
3016 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
3017 fill
= snprintf(pos
, left
, "%s%lu %lu %lu%s",
3018 use_shadow
? " " : "", map
->nsid
,
3019 map
->hostid
, map
->range
,
3020 use_shadow
? "" : "\n");
3021 if (fill
<= 0 || fill
>= left
) {
3022 /* The kernel only takes <= 4k for writes to
3023 * /proc/<pid>/{g,u}id_map
3025 SYSERROR("Too many %cid mappings defined", u_or_g
);
3034 /* Try to catch the output of new{g,u}idmap to make debugging
3038 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3039 lxc_map_ids_exec_wrapper
,
3042 ERROR("new%cidmap failed to write mapping \"%s\": %s",
3043 u_or_g
, cmd_output
, mapbuf
);
3046 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g
, mapbuf
);
3048 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
3050 ERROR("Failed to write mapping: %s", mapbuf
);
3053 TRACE("Wrote mapping \"%s\"", mapbuf
);
3056 memset(mapbuf
, 0, sizeof(mapbuf
));
3062 /* Return the host uid/gid to which the container root is mapped in val.
3063 * Return true if id was found, false otherwise.
3065 bool get_mapped_rootid(struct lxc_conf
*conf
, enum idtype idtype
,
3070 struct lxc_list
*it
;
3072 if (idtype
== ID_TYPE_UID
)
3073 nsid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
3075 nsid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
3077 lxc_list_for_each (it
, &conf
->id_map
) {
3079 if (map
->idtype
!= idtype
)
3081 if (map
->nsid
!= nsid
)
3090 int mapped_hostid(unsigned id
, struct lxc_conf
*conf
, enum idtype idtype
)
3093 struct lxc_list
*it
;
3095 lxc_list_for_each (it
, &conf
->id_map
) {
3097 if (map
->idtype
!= idtype
)
3100 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
3101 return (id
- map
->hostid
) + map
->nsid
;
3107 int find_unmapped_nsid(struct lxc_conf
*conf
, enum idtype idtype
)
3110 struct lxc_list
*it
;
3111 unsigned int freeid
= 0;
3114 lxc_list_for_each (it
, &conf
->id_map
) {
3116 if (map
->idtype
!= idtype
)
3119 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
3120 freeid
= map
->nsid
+ map
->range
;
3128 int chown_mapped_root_exec_wrapper(void *args
)
3130 execvp("lxc-usernsexec", args
);
3134 /* chown_mapped_root: for an unprivileged user with uid/gid X to
3135 * chown a dir to subuid/subgid Y, he needs to run chown as root
3136 * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and
3137 * nsid Y is mapped to hostuid/hostgid X. That way, the container
3138 * root is privileged with respect to hostuid/hostgid X, allowing
3139 * him to do the chown.
3141 int chown_mapped_root(const char *path
, struct lxc_conf
*conf
)
3143 uid_t rootuid
, rootgid
;
3145 int hostuid
, hostgid
, ret
;
3147 char map1
[100], map2
[100], map3
[100], map4
[100], map5
[100];
3149 const char *args1
[] = {"lxc-usernsexec",
3154 "--", "chown", ugid
, path
,
3156 const char *args2
[] = {"lxc-usernsexec",
3162 "--", "chown", ugid
, path
,
3164 char cmd_output
[PATH_MAX
];
3166 hostuid
= geteuid();
3167 hostgid
= getegid();
3169 if (!get_mapped_rootid(conf
, ID_TYPE_UID
, &val
)) {
3170 ERROR("No uid mapping for container root");
3173 rootuid
= (uid_t
)val
;
3175 if (!get_mapped_rootid(conf
, ID_TYPE_GID
, &val
)) {
3176 ERROR("No gid mapping for container root");
3179 rootgid
= (gid_t
)val
;
3182 if (chown(path
, rootuid
, rootgid
) < 0) {
3183 ERROR("Error chowning %s", path
);
3190 if (rootuid
== hostuid
) {
3192 INFO("Container root is our uid; no need to chown");
3196 /* save the current gid of "path" */
3197 if (stat(path
, &sb
) < 0) {
3198 ERROR("Error stat %s", path
);
3202 /* Update the path argument in case this was overlayfs. */
3203 args1
[sizeof(args1
) / sizeof(args1
[0]) - 2] = path
;
3204 args2
[sizeof(args2
) / sizeof(args2
[0]) - 2] = path
;
3207 * A file has to be group-owned by a gid mapped into the
3208 * container, or the container won't be privileged over it.
3210 DEBUG("trying to chown \"%s\" to %d", path
, hostgid
);
3211 if (sb
.st_uid
== hostuid
&&
3212 mapped_hostid(sb
.st_gid
, conf
, ID_TYPE_GID
) < 0 &&
3213 chown(path
, -1, hostgid
) < 0) {
3214 ERROR("Failed chgrping %s", path
);
3218 /* "u:0:rootuid:1" */
3219 ret
= snprintf(map1
, 100, "u:0:%d:1", rootuid
);
3220 if (ret
< 0 || ret
>= 100) {
3221 ERROR("Error uid printing map string");
3225 /* "u:hostuid:hostuid:1" */
3226 ret
= snprintf(map2
, 100, "u:%d:%d:1", hostuid
, hostuid
);
3227 if (ret
< 0 || ret
>= 100) {
3228 ERROR("Error uid printing map string");
3232 /* "g:0:rootgid:1" */
3233 ret
= snprintf(map3
, 100, "g:0:%d:1", rootgid
);
3234 if (ret
< 0 || ret
>= 100) {
3235 ERROR("Error gid printing map string");
3239 /* "g:pathgid:rootgid+pathgid:1" */
3240 ret
= snprintf(map4
, 100, "g:%d:%d:1", (gid_t
)sb
.st_gid
,
3241 rootgid
+ (gid_t
)sb
.st_gid
);
3242 if (ret
< 0 || ret
>= 100) {
3243 ERROR("Error gid printing map string");
3247 /* "g:hostgid:hostgid:1" */
3248 ret
= snprintf(map5
, 100, "g:%d:%d:1", hostgid
, hostgid
);
3249 if (ret
< 0 || ret
>= 100) {
3250 ERROR("Error gid printing map string");
3254 /* "0:pathgid" (chown) */
3255 ret
= snprintf(ugid
, 100, "0:%d", (gid_t
)sb
.st_gid
);
3256 if (ret
< 0 || ret
>= 100) {
3257 ERROR("Error owner printing format string for chown");
3261 if (hostgid
== sb
.st_gid
)
3262 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3263 chown_mapped_root_exec_wrapper
,
3266 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3267 chown_mapped_root_exec_wrapper
,
3270 ERROR("lxc-usernsexec failed: %s", cmd_output
);
3275 /* NOTE: Must not be called from inside the container namespace! */
3276 int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
3280 mounted
= lxc_mount_proc_if_needed(conf
->rootfs
.path
? conf
->rootfs
.mount
: "");
3281 if (mounted
== -1) {
3282 SYSERROR("Failed to mount proc in the container");
3283 /* continue only if there is no rootfs */
3284 if (conf
->rootfs
.path
)
3286 } else if (mounted
== 1) {
3287 conf
->tmp_umount_proc
= true;
3293 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
3295 if (!lxc_conf
->tmp_umount_proc
)
3298 (void)umount2("/proc", MNT_DETACH
);
3299 lxc_conf
->tmp_umount_proc
= false;
3302 /* Walk /proc/mounts and change any shared entries to slave. */
3303 void remount_all_slave(void)
3305 int memfd
, mntinfo_fd
, ret
;
3311 mntinfo_fd
= open("/proc/self/mountinfo", O_RDONLY
| O_CLOEXEC
);
3312 if (mntinfo_fd
< 0) {
3313 SYSERROR("Failed to open \"/proc/self/mountinfo\"");
3317 memfd
= memfd_create(".lxc_mountinfo", MFD_CLOEXEC
);
3319 char template[] = P_tmpdir
"/.lxc_mountinfo_XXXXXX";
3321 if (errno
!= ENOSYS
) {
3322 SYSERROR("Failed to create temporary in-memory file");
3327 memfd
= lxc_make_tmpfile(template, true);
3330 WARN("Failed to create temporary file");
3336 copied
= lxc_sendfile_nointr(memfd
, mntinfo_fd
, NULL
, LXC_SENDFILE_MAX
);
3341 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
3348 /* After a successful fdopen() memfd will be closed when calling
3349 * fclose(f). Calling close(memfd) afterwards is undefined.
3351 ret
= lseek(memfd
, 0, SEEK_SET
);
3353 SYSERROR("Failed to reset file descriptor offset");
3358 f
= fdopen(memfd
, "r");
3360 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark "
3361 "all shared. Continuing");
3366 while (getline(&line
, &len
, f
) != -1) {
3367 char *opts
, *target
;
3369 target
= get_field(line
, 4);
3373 opts
= get_field(target
, 2);
3377 null_endofword(opts
);
3378 if (!strstr(opts
, "shared"))
3381 null_endofword(target
);
3382 ret
= mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
);
3384 SYSERROR("Failed to make \"%s\" MS_SLAVE", target
);
3385 ERROR("Continuing...");
3388 TRACE("Remounted \"%s\" as MS_SLAVE", target
);
3392 TRACE("Remounted all mount table entries as MS_SLAVE");
3395 static int lxc_execute_bind_init(struct lxc_handler
*handler
)
3399 char path
[PATH_MAX
], destpath
[PATH_MAX
];
3400 struct lxc_conf
*conf
= handler
->conf
;
3402 /* If init exists in the container, don't bind mount a static one */
3403 p
= choose_init(conf
->rootfs
.mount
);
3407 p
= strdup(old
+ strlen(conf
->rootfs
.mount
));
3412 INFO("Found existing init at \"%s\"", p
);
3416 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3417 if (ret
< 0 || ret
>= PATH_MAX
)
3420 if (!file_exists(path
)) {
3421 ERROR("The file \"%s\" does not exist on host", path
);
3425 ret
= snprintf(destpath
, PATH_MAX
, "%s" P_tmpdir
"%s", conf
->rootfs
.mount
, "/.lxc-init");
3426 if (ret
< 0 || ret
>= PATH_MAX
)
3429 if (!file_exists(destpath
)) {
3430 ret
= mknod(destpath
, S_IFREG
| 0000, 0);
3431 if (ret
< 0 && errno
!= EEXIST
) {
3432 SYSERROR("Failed to create dummy \"%s\" file as bind mount target", destpath
);
3437 ret
= safe_mount(path
, destpath
, "none", MS_BIND
, NULL
, conf
->rootfs
.mount
);
3439 SYSERROR("Failed to bind mount lxc.init.static into container");
3443 p
= strdup(destpath
+ strlen(conf
->rootfs
.mount
));
3447 INFO("Bind mounted lxc.init.static into container at \"%s\"", path
);
3449 ((struct execute_args
*)handler
->data
)->init_fd
= -1;
3450 ((struct execute_args
*)handler
->data
)->init_path
= p
;
3454 /* This does the work of remounting / if it is shared, calling the container
3455 * pre-mount hooks, and mounting the rootfs.
3457 int lxc_setup_rootfs_prepare_root(struct lxc_conf
*conf
, const char *name
,
3458 const char *lxcpath
)
3462 if (conf
->rootfs_setup
) {
3463 const char *path
= conf
->rootfs
.mount
;
3465 /* The rootfs was set up in another namespace. bind-mount it to
3466 * give us a mount in our own ns so we can pivot_root to it
3468 ret
= mount(path
, path
, "rootfs", MS_BIND
, NULL
);
3470 ERROR("Failed to bind mount container / onto itself");
3474 TRACE("Bind mounted container / onto itself");
3478 remount_all_slave();
3480 ret
= run_lxc_hooks(name
, "pre-mount", conf
, NULL
);
3482 ERROR("Failed to run pre-mount hooks");
3486 ret
= lxc_mount_rootfs(conf
);
3488 ERROR("Failed to setup rootfs for");
3492 conf
->rootfs_setup
= true;
3496 static bool verify_start_hooks(struct lxc_conf
*conf
)
3498 char path
[PATH_MAX
];
3499 struct lxc_list
*it
;
3501 lxc_list_for_each (it
, &conf
->hooks
[LXCHOOK_START
]) {
3503 char *hookname
= it
->elem
;
3505 ret
= snprintf(path
, PATH_MAX
, "%s%s",
3506 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
3508 if (ret
< 0 || ret
>= PATH_MAX
)
3511 ret
= access(path
, X_OK
);
3513 SYSERROR("Start hook \"%s\" not found in container",
3524 static bool execveat_supported(void)
3526 lxc_raw_execveat(-1, "", NULL
, NULL
, AT_EMPTY_PATH
);
3527 if (errno
== ENOSYS
)
3533 int lxc_setup(struct lxc_handler
*handler
)
3536 const char *lxcpath
= handler
->lxcpath
, *name
= handler
->name
;
3537 struct lxc_conf
*lxc_conf
= handler
->conf
;
3539 ret
= lxc_setup_rootfs_prepare_root(lxc_conf
, name
, lxcpath
);
3541 ERROR("Failed to setup rootfs");
3545 if (handler
->nsfd
[LXC_NS_UTS
] == -1) {
3546 ret
= setup_utsname(lxc_conf
->utsname
);
3548 ERROR("Failed to setup the utsname %s", name
);
3553 ret
= lxc_setup_keyring();
3557 ret
= lxc_setup_network_in_child_namespaces(lxc_conf
, &lxc_conf
->network
);
3559 ERROR("Failed to setup network");
3563 ret
= lxc_network_send_name_and_ifindex_to_parent(handler
);
3565 ERROR("Failed to send network device names and ifindices to parent");
3569 if (lxc_conf
->autodev
> 0) {
3570 ret
= mount_autodev(name
, &lxc_conf
->rootfs
, lxcpath
);
3572 ERROR("Failed to mount \"/dev\"");
3577 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
3578 * need to wait until other stuff has finished.
3580 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
, handler
);
3582 ERROR("Failed to setup first automatic mounts");
3586 ret
= setup_mount(lxc_conf
, &lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
);
3588 ERROR("Failed to setup mounts");
3592 if (lxc_conf
->is_execute
) {
3593 if (execveat_supported()) {
3595 char path
[PATH_MAX
];
3597 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3598 if (ret
< 0 || ret
>= PATH_MAX
) {
3599 ERROR("Path to init.lxc.static too long");
3603 fd
= open(path
, O_PATH
| O_CLOEXEC
);
3605 SYSERROR("Unable to open lxc.init.static");
3609 ((struct execute_args
*)handler
->data
)->init_fd
= fd
;
3610 ((struct execute_args
*)handler
->data
)->init_path
= NULL
;
3612 ret
= lxc_execute_bind_init(handler
);
3614 ERROR("Failed to bind-mount the lxc init system");
3620 /* Now mount only cgroups, if wanted. Before, /sys could not have been
3621 * mounted. It is guaranteed to be mounted now either through
3622 * automatically or via fstab entries.
3624 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
, handler
);
3626 ERROR("Failed to setup remaining automatic mounts");
3630 ret
= run_lxc_hooks(name
, "mount", lxc_conf
, NULL
);
3632 ERROR("Failed to run mount hooks");
3636 if (lxc_conf
->autodev
> 0) {
3637 ret
= run_lxc_hooks(name
, "autodev", lxc_conf
, NULL
);
3639 ERROR("Failed to run autodev hooks");
3643 ret
= lxc_fill_autodev(&lxc_conf
->rootfs
);
3645 ERROR("Failed to populate \"/dev\"");
3650 if (!lxc_list_empty(&lxc_conf
->mount_list
)) {
3651 ret
= setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
,
3652 &lxc_conf
->mount_list
, name
, lxcpath
);
3654 ERROR("Failed to setup mount entries");
3659 /* Make sure any start hooks are in the container */
3660 if (!verify_start_hooks(lxc_conf
)) {
3661 ERROR("Failed to verify start hooks");
3665 ret
= lxc_setup_console(&lxc_conf
->rootfs
, &lxc_conf
->console
,
3666 lxc_conf
->ttys
.dir
);
3668 ERROR("Failed to setup console");
3672 ret
= lxc_setup_dev_symlinks(&lxc_conf
->rootfs
);
3674 ERROR("Failed to setup \"/dev\" symlinks");
3678 ret
= lxc_create_tmp_proc_mount(lxc_conf
);
3680 ERROR("Failed to \"/proc\" LSMs");
3684 ret
= lxc_setup_rootfs_switch_root(&lxc_conf
->rootfs
);
3686 ERROR("Failed to pivot root into rootfs");
3690 ret
= lxc_setup_devpts(lxc_conf
);
3692 ERROR("Failed to setup new devpts instance");
3696 ret
= lxc_create_ttys(handler
);
3700 ret
= setup_personality(lxc_conf
->personality
);
3702 ERROR("Failed to set personality");
3706 /* Set sysctl value to a path under /proc/sys as determined from the
3707 * key. For e.g. net.ipv4.ip_forward translated to
3708 * /proc/sys/net/ipv4/ip_forward.
3710 if (!lxc_list_empty(&lxc_conf
->sysctls
)) {
3711 ret
= setup_sysctl_parameters(&lxc_conf
->sysctls
);
3713 ERROR("Failed to setup sysctl parameters");
3718 if (!lxc_list_empty(&lxc_conf
->keepcaps
)) {
3719 if (!lxc_list_empty(&lxc_conf
->caps
)) {
3720 ERROR("Container requests lxc.cap.drop and "
3721 "lxc.cap.keep: either use lxc.cap.drop or "
3722 "lxc.cap.keep, not both");
3726 if (dropcaps_except(&lxc_conf
->keepcaps
)) {
3727 ERROR("Failed to keep capabilities");
3730 } else if (setup_caps(&lxc_conf
->caps
)) {
3731 ERROR("Failed to drop capabilities");
3735 NOTICE("The container \"%s\" is set up", name
);
3740 int run_lxc_hooks(const char *name
, char *hookname
, struct lxc_conf
*conf
,
3743 struct lxc_list
*it
;
3746 if (strcmp(hookname
, "pre-start") == 0)
3747 which
= LXCHOOK_PRESTART
;
3748 else if (strcmp(hookname
, "start-host") == 0)
3749 which
= LXCHOOK_START_HOST
;
3750 else if (strcmp(hookname
, "pre-mount") == 0)
3751 which
= LXCHOOK_PREMOUNT
;
3752 else if (strcmp(hookname
, "mount") == 0)
3753 which
= LXCHOOK_MOUNT
;
3754 else if (strcmp(hookname
, "autodev") == 0)
3755 which
= LXCHOOK_AUTODEV
;
3756 else if (strcmp(hookname
, "start") == 0)
3757 which
= LXCHOOK_START
;
3758 else if (strcmp(hookname
, "stop") == 0)
3759 which
= LXCHOOK_STOP
;
3760 else if (strcmp(hookname
, "post-stop") == 0)
3761 which
= LXCHOOK_POSTSTOP
;
3762 else if (strcmp(hookname
, "clone") == 0)
3763 which
= LXCHOOK_CLONE
;
3764 else if (strcmp(hookname
, "destroy") == 0)
3765 which
= LXCHOOK_DESTROY
;
3769 lxc_list_for_each (it
, &conf
->hooks
[which
]) {
3771 char *hook
= it
->elem
;
3773 ret
= run_script_argv(name
, conf
->hooks_version
, "lxc", hook
,
3782 int lxc_clear_config_caps(struct lxc_conf
*c
)
3784 struct lxc_list
*it
, *next
;
3786 lxc_list_for_each_safe (it
, &c
->caps
, next
) {
3795 static int lxc_free_idmap(struct lxc_list
*id_map
)
3797 struct lxc_list
*it
, *next
;
3799 lxc_list_for_each_safe (it
, id_map
, next
) {
3808 int lxc_clear_idmaps(struct lxc_conf
*c
)
3810 return lxc_free_idmap(&c
->id_map
);
3813 int lxc_clear_config_keepcaps(struct lxc_conf
*c
)
3815 struct lxc_list
*it
, *next
;
3817 lxc_list_for_each_safe (it
, &c
->keepcaps
, next
) {
3826 int lxc_clear_namespace(struct lxc_conf
*c
)
3829 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
3830 free(c
->ns_share
[i
]);
3831 c
->ns_share
[i
] = NULL
;
3836 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
, int version
)
3838 char *global_token
, *namespaced_token
;
3839 size_t namespaced_token_len
;
3840 struct lxc_list
*it
, *next
, *list
;
3841 const char *k
= key
;
3844 if (version
== CGROUP2_SUPER_MAGIC
) {
3845 global_token
= "lxc.cgroup2";
3846 namespaced_token
= "lxc.cgroup2.";
3847 namespaced_token_len
= STRLITERALLEN("lxc.cgroup2.");
3849 } else if (version
== CGROUP_SUPER_MAGIC
) {
3850 global_token
= "lxc.cgroup";
3851 namespaced_token
= "lxc.cgroup.";
3852 namespaced_token_len
= STRLITERALLEN("lxc.cgroup.");
3858 if (strcmp(key
, global_token
) == 0)
3860 else if (strncmp(key
, namespaced_token
, namespaced_token_len
) == 0)
3861 k
+= namespaced_token_len
;
3865 lxc_list_for_each_safe (it
, list
, next
) {
3866 struct lxc_cgroup
*cg
= it
->elem
;
3868 if (!all
&& strcmp(cg
->subsystem
, k
) != 0)
3872 free(cg
->subsystem
);
3881 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
3883 struct lxc_list
*it
, *next
;
3884 const char *k
= NULL
;
3887 if (strcmp(key
, "lxc.limit") == 0 || strcmp(key
, "lxc.prlimit") == 0)
3889 else if (strncmp(key
, "lxc.limit.", STRLITERALLEN("lxc.limit.")) == 0)
3890 k
= key
+ STRLITERALLEN("lxc.limit.");
3891 else if (strncmp(key
, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")) == 0)
3892 k
= key
+ STRLITERALLEN("lxc.prlimit.");
3896 lxc_list_for_each_safe (it
, &c
->limits
, next
) {
3897 struct lxc_limit
*lim
= it
->elem
;
3899 if (!all
&& strcmp(lim
->resource
, k
) != 0)
3903 free(lim
->resource
);
3911 int lxc_clear_sysctls(struct lxc_conf
*c
, const char *key
)
3913 struct lxc_list
*it
, *next
;
3914 const char *k
= NULL
;
3917 if (strcmp(key
, "lxc.sysctl") == 0)
3919 else if (strncmp(key
, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")) == 0)
3920 k
= key
+ STRLITERALLEN("lxc.sysctl.");
3924 lxc_list_for_each_safe (it
, &c
->sysctls
, next
) {
3925 struct lxc_sysctl
*elem
= it
->elem
;
3927 if (!all
&& strcmp(elem
->key
, k
) != 0)
3940 int lxc_clear_procs(struct lxc_conf
*c
, const char *key
)
3942 struct lxc_list
*it
, *next
;
3943 const char *k
= NULL
;
3946 if (strcmp(key
, "lxc.proc") == 0)
3948 else if (strncmp(key
, "lxc.proc.", STRLITERALLEN("lxc.proc.")) == 0)
3949 k
= key
+ STRLITERALLEN("lxc.proc.");
3953 lxc_list_for_each_safe (it
, &c
->procs
, next
) {
3954 struct lxc_proc
*proc
= it
->elem
;
3956 if (!all
&& strcmp(proc
->filename
, k
) != 0)
3960 free(proc
->filename
);
3969 int lxc_clear_groups(struct lxc_conf
*c
)
3971 struct lxc_list
*it
, *next
;
3973 lxc_list_for_each_safe (it
, &c
->groups
, next
) {
3982 int lxc_clear_environment(struct lxc_conf
*c
)
3984 struct lxc_list
*it
, *next
;
3986 lxc_list_for_each_safe (it
, &c
->environment
, next
) {
3995 int lxc_clear_mount_entries(struct lxc_conf
*c
)
3997 struct lxc_list
*it
, *next
;
3999 lxc_list_for_each_safe (it
, &c
->mount_list
, next
) {
4008 int lxc_clear_automounts(struct lxc_conf
*c
)
4014 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
4017 struct lxc_list
*it
, *next
;
4018 const char *k
= NULL
;
4019 bool all
= false, done
= false;
4021 if (strcmp(key
, "lxc.hook") == 0)
4023 else if (strncmp(key
, "lxc.hook.", STRLITERALLEN("lxc.hook.")) == 0)
4024 k
= key
+ STRLITERALLEN("lxc.hook.");
4028 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++) {
4029 if (all
|| strcmp(k
, lxchook_names
[i
]) == 0) {
4030 lxc_list_for_each_safe (it
, &c
->hooks
[i
], next
) {
4041 ERROR("Invalid hook key: %s", key
);
4048 static inline void lxc_clear_aliens(struct lxc_conf
*conf
)
4050 struct lxc_list
*it
, *next
;
4052 lxc_list_for_each_safe (it
, &conf
->aliens
, next
) {
4059 void lxc_clear_includes(struct lxc_conf
*conf
)
4061 struct lxc_list
*it
, *next
;
4063 lxc_list_for_each_safe (it
, &conf
->includes
, next
) {
4070 int lxc_clear_apparmor_raw(struct lxc_conf
*c
)
4072 struct lxc_list
*it
, *next
;
4074 lxc_list_for_each_safe (it
, &c
->lsm_aa_raw
, next
) {
4083 void lxc_conf_free(struct lxc_conf
*conf
)
4088 if (current_config
== conf
)
4089 current_config
= NULL
;
4090 lxc_terminal_conf_free(&conf
->console
);
4091 free(conf
->rootfs
.mount
);
4092 free(conf
->rootfs
.bdev_type
);
4093 free(conf
->rootfs
.options
);
4094 free(conf
->rootfs
.path
);
4095 free(conf
->logfile
);
4096 if (conf
->logfd
!= -1)
4098 free(conf
->utsname
);
4099 free(conf
->ttys
.dir
);
4100 free(conf
->ttys
.tty_names
);
4103 free(conf
->execute_cmd
);
4104 free(conf
->init_cmd
);
4105 free(conf
->init_cwd
);
4106 free(conf
->unexpanded_config
);
4108 lxc_free_networks(&conf
->network
);
4109 free(conf
->lsm_aa_profile
);
4110 free(conf
->lsm_aa_profile_computed
);
4111 free(conf
->lsm_se_context
);
4112 lxc_seccomp_free(conf
);
4113 lxc_clear_config_caps(conf
);
4114 lxc_clear_config_keepcaps(conf
);
4115 lxc_clear_cgroups(conf
, "lxc.cgroup", CGROUP_SUPER_MAGIC
);
4116 lxc_clear_cgroups(conf
, "lxc.cgroup2", CGROUP2_SUPER_MAGIC
);
4117 lxc_clear_hooks(conf
, "lxc.hook");
4118 lxc_clear_mount_entries(conf
);
4119 lxc_clear_idmaps(conf
);
4120 lxc_clear_groups(conf
);
4121 lxc_clear_includes(conf
);
4122 lxc_clear_aliens(conf
);
4123 lxc_clear_environment(conf
);
4124 lxc_clear_limits(conf
, "lxc.prlimit");
4125 lxc_clear_sysctls(conf
, "lxc.sysctl");
4126 lxc_clear_procs(conf
, "lxc.proc");
4127 lxc_clear_apparmor_raw(conf
);
4128 lxc_clear_namespace(conf
);
4129 free(conf
->cgroup_meta
.dir
);
4130 free(conf
->cgroup_meta
.controllers
);
4131 free(conf
->shmount
.path_host
);
4132 free(conf
->shmount
.path_cont
);
4136 struct userns_fn_data
{
4138 const char *fn_name
;
4143 static int run_userns_fn(void *data
)
4147 struct userns_fn_data
*d
= data
;
4149 /* Close write end of the pipe. */
4152 /* Wait for parent to finish establishing a new mapping in the user
4153 * namespace we are executing in.
4155 ret
= lxc_read_nointr(d
->p
[0], &c
, 1);
4156 /* Close read end of the pipe. */
4162 TRACE("Calling function \"%s\"", d
->fn_name
);
4164 /* Call function to run. */
4165 return d
->fn(d
->arg
);
4168 static struct id_map
*mapped_nsid_add(struct lxc_conf
*conf
, unsigned id
,
4171 const struct id_map
*map
;
4172 struct id_map
*retmap
;
4174 map
= find_mapped_nsid_entry(conf
, id
, idtype
);
4178 retmap
= malloc(sizeof(*retmap
));
4182 memcpy(retmap
, map
, sizeof(*retmap
));
4186 static struct id_map
*find_mapped_hostid_entry(struct lxc_conf
*conf
,
4187 unsigned id
, enum idtype idtype
)
4190 struct lxc_list
*it
;
4191 struct id_map
*retmap
= NULL
;
4193 lxc_list_for_each (it
, &conf
->id_map
) {
4195 if (map
->idtype
!= idtype
)
4198 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
4207 /* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
4208 * existing one or establish a new one.
4210 static struct id_map
*mapped_hostid_add(struct lxc_conf
*conf
, uid_t id
,
4214 struct id_map
*entry
= NULL
, *tmp
= NULL
;
4216 entry
= malloc(sizeof(*entry
));
4220 /* Reuse existing mapping. */
4221 tmp
= find_mapped_hostid_entry(conf
, id
, type
);
4223 return memcpy(entry
, tmp
, sizeof(*entry
));
4225 /* Find new mapping. */
4226 hostid_mapped
= find_unmapped_nsid(conf
, type
);
4227 if (hostid_mapped
< 0) {
4228 DEBUG("Failed to find free mapping for id %d", id
);
4233 entry
->idtype
= type
;
4234 entry
->nsid
= hostid_mapped
;
4235 entry
->hostid
= (unsigned long)id
;
4241 struct lxc_list
*get_minimal_idmap(struct lxc_conf
*conf
)
4244 uid_t nsuid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
4245 gid_t nsgid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
4246 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
4247 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
4248 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4250 /* Find container root mappings. */
4251 container_root_uid
= mapped_nsid_add(conf
, nsuid
, ID_TYPE_UID
);
4252 if (!container_root_uid
) {
4253 DEBUG("Failed to find mapping for namespace uid %d", 0);
4257 if (euid
>= container_root_uid
->hostid
&&
4258 euid
< (container_root_uid
->hostid
+ container_root_uid
->range
))
4259 host_uid_map
= container_root_uid
;
4261 container_root_gid
= mapped_nsid_add(conf
, nsgid
, ID_TYPE_GID
);
4262 if (!container_root_gid
) {
4263 DEBUG("Failed to find mapping for namespace gid %d", 0);
4267 if (egid
>= container_root_gid
->hostid
&&
4268 egid
< (container_root_gid
->hostid
+ container_root_gid
->range
))
4269 host_gid_map
= container_root_gid
;
4271 /* Check whether the {g,u}id of the user has a mapping. */
4273 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4274 if (!host_uid_map
) {
4275 DEBUG("Failed to find mapping for uid %d", euid
);
4280 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4281 if (!host_gid_map
) {
4282 DEBUG("Failed to find mapping for gid %d", egid
);
4286 /* Allocate new {g,u}id map list. */
4287 idmap
= malloc(sizeof(*idmap
));
4290 lxc_list_init(idmap
);
4292 /* Add container root to the map. */
4293 tmplist
= malloc(sizeof(*tmplist
));
4296 lxc_list_add_elem(tmplist
, container_root_uid
);
4297 lxc_list_add_tail(idmap
, tmplist
);
4299 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4300 /* idmap will now keep track of that memory. */
4301 container_root_uid
= NULL
;
4303 /* Add container root to the map. */
4304 tmplist
= malloc(sizeof(*tmplist
));
4307 lxc_list_add_elem(tmplist
, host_uid_map
);
4308 lxc_list_add_tail(idmap
, tmplist
);
4310 /* idmap will now keep track of that memory. */
4311 container_root_uid
= NULL
;
4312 /* idmap will now keep track of that memory. */
4313 host_uid_map
= NULL
;
4315 tmplist
= malloc(sizeof(*tmplist
));
4318 lxc_list_add_elem(tmplist
, container_root_gid
);
4319 lxc_list_add_tail(idmap
, tmplist
);
4321 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4322 /* idmap will now keep track of that memory. */
4323 container_root_gid
= NULL
;
4325 tmplist
= malloc(sizeof(*tmplist
));
4328 lxc_list_add_elem(tmplist
, host_gid_map
);
4329 lxc_list_add_tail(idmap
, tmplist
);
4331 /* idmap will now keep track of that memory. */
4332 container_root_gid
= NULL
;
4333 /* idmap will now keep track of that memory. */
4334 host_gid_map
= NULL
;
4336 TRACE("Allocated minimal idmapping");
4341 lxc_free_idmap(idmap
);
4344 if (container_root_uid
)
4345 free(container_root_uid
);
4346 if (container_root_gid
)
4347 free(container_root_gid
);
4348 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
4350 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
4356 /* Run a function in a new user namespace.
4357 * The caller's euid/egid will be mapped if it is not already.
4358 * Afaict, userns_exec_1() is only used to operate based on privileges for the
4359 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
4360 * This means we require only to establish a mapping from:
4361 * - the container root {g,u}id as seen from the host > user's host {g,u}id
4362 * - the container root -> some sub{g,u}id
4363 * The former we add, if the user did not specify a mapping. The latter we
4364 * retrieve from the container's configured {g,u}id mappings as it must have been
4365 * there to start the container in the first place.
4367 int userns_exec_1(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4368 const char *fn_name
)
4372 struct userns_fn_data d
;
4373 struct lxc_list
*idmap
;
4374 int ret
= -1, status
= -1;
4380 idmap
= get_minimal_idmap(conf
);
4384 ret
= pipe2(p
, O_CLOEXEC
);
4386 SYSERROR("Failed to create pipe");
4390 d
.fn_name
= fn_name
;
4395 /* Clone child in new user namespace. */
4396 pid
= lxc_raw_clone_cb(run_userns_fn
, &d
, CLONE_NEWUSER
);
4398 ERROR("Failed to clone process in new user namespace");
4405 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4406 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4408 struct lxc_list
*it
;
4410 lxc_list_for_each (it
, idmap
) {
4412 TRACE("Establishing %cid mapping for \"%d\" in new "
4413 "user namespace: nsuid %lu - hostid %lu - range "
4415 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4416 map
->nsid
, map
->hostid
, map
->range
);
4420 /* Set up {g,u}id mapping for user namespace of child process. */
4421 ret
= lxc_map_ids(idmap
, pid
);
4423 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
4427 /* Tell child to proceed. */
4428 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4429 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4438 /* Wait for child to finish. */
4440 status
= wait_for_pid(pid
);
4448 int userns_exec_full(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4449 const char *fn_name
)
4455 struct lxc_list
*cur
;
4456 struct userns_fn_data d
;
4459 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
4460 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
4461 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4466 ret
= pipe2(p
, O_CLOEXEC
);
4468 SYSERROR("opening pipe");
4472 d
.fn_name
= fn_name
;
4477 /* Clone child in new user namespace. */
4478 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
);
4480 ERROR("Failed to clone process in new user namespace");
4490 /* Allocate new {g,u}id map list. */
4491 idmap
= malloc(sizeof(*idmap
));
4494 lxc_list_init(idmap
);
4496 /* Find container root. */
4497 lxc_list_for_each (cur
, &conf
->id_map
) {
4498 struct id_map
*tmpmap
;
4500 tmplist
= malloc(sizeof(*tmplist
));
4504 tmpmap
= malloc(sizeof(*tmpmap
));
4510 memset(tmpmap
, 0, sizeof(*tmpmap
));
4511 memcpy(tmpmap
, cur
->elem
, sizeof(*tmpmap
));
4512 tmplist
->elem
= tmpmap
;
4514 lxc_list_add_tail(idmap
, tmplist
);
4518 if (map
->idtype
== ID_TYPE_UID
)
4519 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
4522 if (map
->idtype
== ID_TYPE_GID
)
4523 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
4529 if (map
->idtype
== ID_TYPE_UID
)
4530 if (container_root_uid
== NULL
)
4531 container_root_uid
= map
;
4533 if (map
->idtype
== ID_TYPE_GID
)
4534 if (container_root_gid
== NULL
)
4535 container_root_gid
= map
;
4538 if (!container_root_uid
|| !container_root_gid
) {
4539 ERROR("No mapping for container root found");
4543 /* Check whether the {g,u}id of the user has a mapping. */
4545 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4547 host_uid_map
= container_root_uid
;
4550 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4552 host_gid_map
= container_root_gid
;
4554 if (!host_uid_map
) {
4555 DEBUG("Failed to find mapping for uid %d", euid
);
4559 if (!host_gid_map
) {
4560 DEBUG("Failed to find mapping for gid %d", egid
);
4564 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4565 /* Add container root to the map. */
4566 tmplist
= malloc(sizeof(*tmplist
));
4569 lxc_list_add_elem(tmplist
, host_uid_map
);
4570 lxc_list_add_tail(idmap
, tmplist
);
4572 /* idmap will now keep track of that memory. */
4573 host_uid_map
= NULL
;
4575 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4576 tmplist
= malloc(sizeof(*tmplist
));
4579 lxc_list_add_elem(tmplist
, host_gid_map
);
4580 lxc_list_add_tail(idmap
, tmplist
);
4582 /* idmap will now keep track of that memory. */
4583 host_gid_map
= NULL
;
4585 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4586 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4587 lxc_list_for_each (cur
, idmap
) {
4589 TRACE("establishing %cid mapping for \"%d\" in new "
4590 "user namespace: nsuid %lu - hostid %lu - range "
4592 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4593 map
->nsid
, map
->hostid
, map
->range
);
4597 /* Set up {g,u}id mapping for user namespace of child process. */
4598 ret
= lxc_map_ids(idmap
, pid
);
4600 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid
);
4604 /* Tell child to proceed. */
4605 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4606 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4615 /* Wait for child to finish. */
4617 ret
= wait_for_pid(pid
);
4620 lxc_free_idmap(idmap
);
4624 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
4626 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
4632 /* not thread-safe, do not use from api without first forking */
4633 static char *getuname(void)
4635 struct passwd pwent
;
4636 struct passwd
*pwentp
= NULL
;
4642 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
4646 buf
= malloc(bufsize
);
4650 ret
= getpwuid_r(geteuid(), &pwent
, buf
, bufsize
, &pwentp
);
4653 WARN("Could not find matched password record.");
4655 ERROR("Failed to get password record - %u", geteuid());
4660 username
= strdup(pwent
.pw_name
);
4666 /* not thread-safe, do not use from api without first forking */
4667 static char *getgname(void)
4670 struct group
*grentp
= NULL
;
4676 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
4680 buf
= malloc(bufsize
);
4684 ret
= getgrgid_r(getegid(), &grent
, buf
, bufsize
, &grentp
);
4687 WARN("Could not find matched group record");
4689 ERROR("Failed to get group record - %u", getegid());
4694 grname
= strdup(grent
.gr_name
);
4700 /* not thread-safe, do not use from api without first forking */
4701 void suggest_default_idmap(void)
4703 char *uname
, *gname
;
4705 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
4719 f
= fopen(subuidfile
, "r");
4721 ERROR("Your system is not configured with subuids");
4727 while (getline(&line
, &len
, f
) != -1) {
4729 size_t no_newline
= 0;
4731 p
= strchr(line
, ':');
4739 if (strcmp(line
, uname
))
4742 p2
= strchr(p
, ':');
4749 no_newline
= strcspn(p2
, "\n");
4750 p2
[no_newline
] = '\0';
4752 if (lxc_safe_uint(p
, &uid
) < 0)
4753 WARN("Could not parse UID");
4754 if (lxc_safe_uint(p2
, &urange
) < 0)
4755 WARN("Could not parse UID range");
4759 f
= fopen(subgidfile
, "r");
4761 ERROR("Your system is not configured with subgids");
4767 while (getline(&line
, &len
, f
) != -1) {
4769 size_t no_newline
= 0;
4771 p
= strchr(line
, ':');
4779 if (strcmp(line
, uname
))
4782 p2
= strchr(p
, ':');
4789 no_newline
= strcspn(p2
, "\n");
4790 p2
[no_newline
] = '\0';
4792 if (lxc_safe_uint(p
, &gid
) < 0)
4793 WARN("Could not parse GID");
4794 if (lxc_safe_uint(p2
, &grange
) < 0)
4795 WARN("Could not parse GID range");
4801 if (!urange
|| !grange
) {
4802 ERROR("You do not have subuids or subgids allocated");
4803 ERROR("Unprivileged containers require subuids and subgids");
4809 ERROR("You must either run as root, or define uid mappings");
4810 ERROR("To pass uid mappings to lxc-create, you could create");
4811 ERROR("~/.config/lxc/default.conf:");
4812 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
4813 ERROR("lxc.idmap = u 0 %u %u", uid
, urange
);
4814 ERROR("lxc.idmap = g 0 %u %u", gid
, grange
);
4820 static void free_cgroup_settings(struct lxc_list
*result
)
4822 struct lxc_list
*iterator
, *next
;
4824 lxc_list_for_each_safe (iterator
, result
, next
) {
4825 lxc_list_del(iterator
);
4831 /* Return the list of cgroup_settings sorted according to the following rules
4832 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4834 struct lxc_list
*sort_cgroup_settings(struct lxc_list
*cgroup_settings
)
4836 struct lxc_list
*result
;
4837 struct lxc_cgroup
*cg
= NULL
;
4838 struct lxc_list
*it
= NULL
, *item
= NULL
, *memsw_limit
= NULL
;
4840 result
= malloc(sizeof(*result
));
4843 lxc_list_init(result
);
4845 /* Iterate over the cgroup settings and copy them to the output list. */
4846 lxc_list_for_each (it
, cgroup_settings
) {
4847 item
= malloc(sizeof(*item
));
4849 free_cgroup_settings(result
);
4853 item
->elem
= it
->elem
;
4855 if (strcmp(cg
->subsystem
, "memory.memsw.limit_in_bytes") == 0) {
4856 /* Store the memsw_limit location */
4858 } else if (strcmp(cg
->subsystem
, "memory.limit_in_bytes") == 0 &&
4859 memsw_limit
!= NULL
) {
4860 /* lxc.cgroup.memory.memsw.limit_in_bytes is found
4861 * before lxc.cgroup.memory.limit_in_bytes, swap these
4863 item
->elem
= memsw_limit
->elem
;
4864 memsw_limit
->elem
= it
->elem
;
4866 lxc_list_add_tail(result
, item
);