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
++) {
692 __do_free
char *destination
= NULL
, *source
= NULL
;
694 unsigned long mflags
;
695 if ((flags
& default_mounts
[i
].match_mask
) != default_mounts
[i
].match_flag
)
698 if (default_mounts
[i
].source
) {
699 /* will act like strdup if %r is not present */
700 source
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].source
);
705 if (!default_mounts
[i
].destination
) {
706 ERROR("BUG: auto mounts destination %d was NULL", i
);
710 /* will act like strdup if %r is not present */
711 destination
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].destination
);
716 mflags
= add_required_remount_flags(source
, destination
,
717 default_mounts
[i
].flags
);
718 r
= safe_mount(source
, destination
, default_mounts
[i
].fstype
,
719 mflags
, default_mounts
[i
].options
,
720 conf
->rootfs
.path
? conf
->rootfs
.mount
: NULL
);
722 if (r
< 0 && errno
== ENOENT
) {
723 INFO("Mount source or target for \"%s\" on \"%s\" does "
724 "not exist. Skipping", source
, destination
);
727 SYSERROR("Failed to mount \"%s\" on \"%s\" with flags %lu", source
, destination
, mflags
);
736 if (flags
& LXC_AUTO_CGROUP_MASK
) {
739 cg_flags
= flags
& (LXC_AUTO_CGROUP_MASK
& ~LXC_AUTO_CGROUP_FORCE
);
740 /* If the type of cgroup mount was not specified, it depends on
741 * the container's capabilities as to what makes sense: if we
742 * have CAP_SYS_ADMIN, the read-only part can be remounted
743 * read-write anyway, so we may as well default to read-write;
744 * then the admin will not be given a false sense of security.
745 * (And if they really want mixed r/o r/w, then they can
746 * explicitly specify :mixed.) OTOH, if the container lacks
747 * CAP_SYS_ADMIN, do only default to :mixed, because then the
748 * container can't remount it read-write.
750 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
|| cg_flags
== LXC_AUTO_CGROUP_FULL_NOSPEC
) {
751 int has_sys_admin
= 0;
753 if (!lxc_list_empty(&conf
->keepcaps
))
754 has_sys_admin
= in_caplist(CAP_SYS_ADMIN
, &conf
->keepcaps
);
756 has_sys_admin
= !in_caplist(CAP_SYS_ADMIN
, &conf
->caps
);
758 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
759 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_RW
: LXC_AUTO_CGROUP_MIXED
;
761 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_FULL_RW
: LXC_AUTO_CGROUP_FULL_MIXED
;
764 if (flags
& LXC_AUTO_CGROUP_FORCE
)
765 cg_flags
|= LXC_AUTO_CGROUP_FORCE
;
767 if (!handler
->cgroup_ops
->mount(handler
->cgroup_ops
,
769 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
771 SYSERROR("Failed to mount \"/sys/fs/cgroup\"");
776 if (flags
& LXC_AUTO_SHMOUNTS_MASK
) {
777 int ret
= add_shmount_to_list(conf
);
779 ERROR("Failed to add shmount entry to container config");
787 static int setup_utsname(struct utsname
*utsname
)
794 ret
= sethostname(utsname
->nodename
, strlen(utsname
->nodename
));
796 SYSERROR("Failed to set the hostname to \"%s\"", utsname
->nodename
);
800 INFO("Set hostname to \"%s\"", utsname
->nodename
);
805 struct dev_symlinks
{
810 static const struct dev_symlinks dev_symlinks
[] = {
811 { "/proc/self/fd", "fd" },
812 { "/proc/self/fd/0", "stdin" },
813 { "/proc/self/fd/1", "stdout" },
814 { "/proc/self/fd/2", "stderr" },
817 static int lxc_setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
823 for (i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
824 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
826 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s",
827 rootfs
->path
? rootfs
->mount
: "", d
->name
);
828 if (ret
< 0 || ret
>= PATH_MAX
)
831 /* Stat the path first. If we don't get an error accept it as
832 * is and don't try to create it
834 ret
= stat(path
, &s
);
838 ret
= symlink(d
->oldpath
, path
);
839 if (ret
&& errno
!= EEXIST
) {
840 if (errno
== EROFS
) {
841 WARN("Failed to create \"%s\". Read-only filesystem", path
);
843 SYSERROR("Failed to create \"%s\"", path
);
852 /* Build a space-separate list of ptys to pass to systemd. */
853 static bool append_ttyname(char **pp
, char *name
)
859 *pp
= malloc(strlen(name
) + strlen("container_ttys=") + 1);
863 sprintf(*pp
, "container_ttys=%s", name
);
867 size
= strlen(*pp
) + strlen(name
) + 2;
868 p
= realloc(*pp
, size
);
873 (void)strlcat(p
, " ", size
);
874 (void)strlcat(p
, name
, size
);
879 static int lxc_setup_ttys(struct lxc_conf
*conf
)
882 const struct lxc_tty_info
*ttys
= &conf
->ttys
;
883 char *ttydir
= ttys
->dir
;
884 char path
[PATH_MAX
], lxcpath
[PATH_MAX
];
886 if (!conf
->rootfs
.path
)
889 for (i
= 0; i
< ttys
->max
; i
++) {
890 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
892 ret
= snprintf(path
, sizeof(path
), "/dev/tty%d", i
+ 1);
893 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
897 /* create dev/lxc/tty%d" */
898 ret
= snprintf(lxcpath
, sizeof(lxcpath
),
899 "/dev/%s/tty%d", ttydir
, i
+ 1);
900 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
903 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
904 if (ret
< 0 && errno
!= EEXIST
) {
905 SYSERROR("Failed to create \"%s\"", lxcpath
);
910 if (ret
< 0 && errno
!= ENOENT
) {
911 SYSERROR("Failed to unlink \"%s\"", path
);
915 ret
= mount(tty
->name
, lxcpath
, "none", MS_BIND
, 0);
917 SYSWARN("Failed to bind mount \"%s\" onto \"%s\"",
921 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
,
924 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/tty%d",
926 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
929 ret
= symlink(lxcpath
, path
);
931 SYSERROR("Failed to create symlink \"%s\" -> \"%s\"",
936 /* If we populated /dev, then we need to create
939 ret
= mknod(path
, S_IFREG
| 0000, 0);
940 if (ret
< 0) /* this isn't fatal, continue */
941 SYSERROR("Failed to create \"%s\"", path
);
943 ret
= mount(tty
->name
, path
, "none", MS_BIND
, 0);
945 SYSERROR("Failed to mount '%s'->'%s'", tty
->name
, path
);
949 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, path
);
952 if (!append_ttyname(&conf
->ttys
.tty_names
, tty
->name
)) {
953 ERROR("Error setting up container_ttys string");
958 INFO("Finished setting up %zu /dev/tty<N> device(s)", ttys
->max
);
962 int lxc_allocate_ttys(struct lxc_conf
*conf
)
966 struct lxc_tty_info
*ttys
= &conf
->ttys
;
968 /* no tty in the configuration */
972 ttys
->tty
= malloc(sizeof(*ttys
->tty
) * ttys
->max
);
976 for (i
= 0; i
< ttys
->max
; i
++) {
977 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
979 tty
->master
= -EBADF
;
981 ret
= openpty(&tty
->master
, &tty
->slave
, NULL
, NULL
, NULL
);
983 SYSERROR("Failed to create tty %zu", i
);
985 lxc_delete_tty(ttys
);
989 ret
= ttyname_r(tty
->slave
, tty
->name
, sizeof(tty
->name
));
991 SYSERROR("Failed to retrieve name of tty %zu slave", i
);
993 lxc_delete_tty(ttys
);
997 DEBUG("Created tty \"%s\" with master fd %d and slave fd %d",
998 tty
->name
, tty
->master
, tty
->slave
);
1000 /* Prevent leaking the file descriptors to the container */
1001 ret
= fd_cloexec(tty
->master
, true);
1003 SYSWARN("Failed to set FD_CLOEXEC flag on master fd %d of "
1004 "tty device \"%s\"", tty
->master
, tty
->name
);
1006 ret
= fd_cloexec(tty
->slave
, true);
1008 SYSWARN("Failed to set FD_CLOEXEC flag on slave fd %d of "
1009 "tty device \"%s\"", tty
->slave
, tty
->name
);
1014 INFO("Finished creating %zu tty devices", ttys
->max
);
1018 void lxc_delete_tty(struct lxc_tty_info
*ttys
)
1025 for (i
= 0; i
< ttys
->max
; i
++) {
1026 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1028 if (tty
->master
>= 0) {
1030 tty
->master
= -EBADF
;
1033 if (tty
->slave
>= 0) {
1035 tty
->slave
= -EBADF
;
1043 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
1047 struct lxc_conf
*conf
= handler
->conf
;
1048 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1049 int sock
= handler
->data_sock
[0];
1054 for (i
= 0; i
< ttys
->max
; i
++) {
1056 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1058 ttyfds
[0] = tty
->master
;
1059 ttyfds
[1] = tty
->slave
;
1061 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, 2, NULL
, 0);
1065 TRACE("Sent tty \"%s\" with master fd %d and slave fd %d to "
1066 "parent", tty
->name
, tty
->master
, tty
->slave
);
1070 SYSERROR("Failed to send %zu ttys to parent", ttys
->max
);
1072 TRACE("Sent %zu ttys to parent", ttys
->max
);
1077 static int lxc_create_ttys(struct lxc_handler
*handler
)
1080 struct lxc_conf
*conf
= handler
->conf
;
1082 ret
= lxc_allocate_ttys(conf
);
1084 ERROR("Failed to allocate ttys");
1088 ret
= lxc_send_ttys_to_parent(handler
);
1090 ERROR("Failed to send ttys to parent");
1094 if (!conf
->is_execute
) {
1095 ret
= lxc_setup_ttys(conf
);
1097 ERROR("Failed to setup ttys");
1102 if (conf
->ttys
.tty_names
) {
1103 ret
= setenv("container_ttys", conf
->ttys
.tty_names
, 1);
1105 SYSERROR("Failed to set \"container_ttys=%s\"", conf
->ttys
.tty_names
);
1111 lxc_delete_tty(&conf
->ttys
);
1116 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1117 * error, log it but don't fail yet.
1119 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
,
1120 const char *lxcpath
)
1122 __do_free
char *path
= NULL
;
1127 INFO("Preparing \"/dev\"");
1129 /* $(rootfs->mount) + "/dev/pts" + '\0' */
1130 clen
= (rootfs
->path
? strlen(rootfs
->mount
) : 0) + 9;
1131 path
= must_realloc(NULL
, clen
);
1133 ret
= snprintf(path
, clen
, "%s/dev", rootfs
->path
? rootfs
->mount
: "");
1134 if (ret
< 0 || (size_t)ret
>= clen
)
1137 cur_mask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1138 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1139 if (ret
< 0 && errno
!= EEXIST
) {
1140 SYSERROR("Failed to create \"/dev\" directory");
1145 ret
= safe_mount("none", path
, "tmpfs", 0, "size=500000,mode=755",
1146 rootfs
->path
? rootfs
->mount
: NULL
);
1148 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1151 TRACE("Mounted tmpfs on \"%s\"", path
);
1153 ret
= snprintf(path
, clen
, "%s/dev/pts", rootfs
->path
? rootfs
->mount
: "");
1154 if (ret
< 0 || (size_t)ret
>= clen
) {
1159 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1160 * If not, then create it and exit if that fails...
1162 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1163 if (ret
< 0 && errno
!= EEXIST
) {
1164 SYSERROR("Failed to create directory \"%s\"", path
);
1172 (void)umask(cur_mask
);
1174 INFO("Prepared \"/dev\"");
1178 struct lxc_device_node
{
1185 static const struct lxc_device_node lxc_devices
[] = {
1186 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1187 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1188 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1189 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1190 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1191 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1198 LXC_DEVNODE_PARTIAL
,
1202 static int lxc_fill_autodev(const struct lxc_rootfs
*rootfs
)
1205 char path
[PATH_MAX
];
1207 int use_mknod
= LXC_DEVNODE_MKNOD
;
1209 ret
= snprintf(path
, PATH_MAX
, "%s/dev",
1210 rootfs
->path
? rootfs
->mount
: "");
1211 if (ret
< 0 || ret
>= PATH_MAX
)
1214 /* ignore, just don't try to fill in */
1215 if (!dir_exists(path
))
1218 INFO("Populating \"/dev\"");
1220 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1221 for (i
= 0; i
< sizeof(lxc_devices
) / sizeof(lxc_devices
[0]); i
++) {
1222 char hostpath
[PATH_MAX
];
1223 const struct lxc_device_node
*device
= &lxc_devices
[i
];
1225 ret
= snprintf(path
, PATH_MAX
, "%s/dev/%s",
1226 rootfs
->path
? rootfs
->mount
: "", device
->name
);
1227 if (ret
< 0 || ret
>= PATH_MAX
)
1230 if (use_mknod
>= LXC_DEVNODE_MKNOD
) {
1231 ret
= mknod(path
, device
->mode
, makedev(device
->maj
, device
->min
));
1232 if (ret
== 0 || (ret
< 0 && errno
== EEXIST
)) {
1233 DEBUG("Created device node \"%s\"", path
);
1234 } else if (ret
< 0) {
1235 if (errno
!= EPERM
) {
1236 SYSERROR("Failed to create device node \"%s\"", path
);
1240 use_mknod
= LXC_DEVNODE_BIND
;
1243 /* Device nodes are fully useable. */
1244 if (use_mknod
== LXC_DEVNODE_OPEN
)
1247 if (use_mknod
== LXC_DEVNODE_MKNOD
) {
1249 * - https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=55956b59df336f6738da916dbb520b6e37df9fbd
1250 * - https://lists.linuxfoundation.org/pipermail/containers/2018-June/039176.html
1252 ret
= open(path
, O_RDONLY
| O_CLOEXEC
);
1254 close_prot_errno_disarm(ret
);
1255 /* Device nodes are fully useable. */
1256 use_mknod
= LXC_DEVNODE_OPEN
;
1260 SYSTRACE("Failed to open \"%s\" device", path
);
1261 /* Device nodes are only partially useable. */
1262 use_mknod
= LXC_DEVNODE_PARTIAL
;
1266 if (use_mknod
!= LXC_DEVNODE_PARTIAL
) {
1267 /* If we are dealing with partially functional device
1268 * nodes the prio mknod() call will have created the
1269 * device node so we can use it as a bind-mount target.
1271 ret
= mknod(path
, S_IFREG
| 0000, 0);
1272 if (ret
< 0 && errno
!= EEXIST
) {
1273 SYSERROR("Failed to create file \"%s\"", path
);
1278 /* Fallback to bind-mounting the device from the host. */
1279 ret
= snprintf(hostpath
, PATH_MAX
, "/dev/%s", device
->name
);
1280 if (ret
< 0 || ret
>= PATH_MAX
)
1283 ret
= safe_mount(hostpath
, path
, 0, MS_BIND
, NULL
,
1284 rootfs
->path
? rootfs
->mount
: NULL
);
1286 SYSERROR("Failed to bind mount host device node \"%s\" "
1287 "onto \"%s\"", hostpath
, path
);
1290 DEBUG("Bind mounted host device node \"%s\" onto \"%s\"",
1295 INFO("Populated \"/dev\"");
1299 static int lxc_mount_rootfs(struct lxc_conf
*conf
)
1302 struct lxc_storage
*bdev
;
1303 const struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
1305 if (!rootfs
->path
) {
1306 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
1308 SYSERROR("Failed to remount \"/\" MS_REC | MS_SLAVE");
1315 ret
= access(rootfs
->mount
, F_OK
);
1317 SYSERROR("Failed to access to \"%s\". Check it is present",
1322 bdev
= storage_init(conf
);
1324 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1325 rootfs
->path
, rootfs
->mount
,
1326 rootfs
->options
? rootfs
->options
: "(null)");
1330 ret
= bdev
->ops
->mount(bdev
);
1333 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1334 rootfs
->path
, rootfs
->mount
,
1335 rootfs
->options
? rootfs
->options
: "(null)");
1339 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
1340 rootfs
->path
, rootfs
->mount
,
1341 rootfs
->options
? rootfs
->options
: "(null)");
1346 int lxc_chroot(const struct lxc_rootfs
*rootfs
)
1348 __do_free
char *nroot
= NULL
;
1351 char buf
[LXC_LINELEN
];
1352 char *root
= rootfs
->mount
;
1354 nroot
= realpath(root
, NULL
);
1356 SYSERROR("Failed to resolve \"%s\"", root
);
1364 /* We could use here MS_MOVE, but in userns this mount is locked and
1367 ret
= mount(nroot
, "/", NULL
, MS_REC
| MS_BIND
, NULL
);
1369 SYSERROR("Failed to mount \"%s\" onto \"/\" as MS_REC | MS_BIND", nroot
);
1373 ret
= mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
);
1375 SYSERROR("Failed to remount \"/\"");
1379 /* The following code cleans up inherited mounts which are not required
1382 * The mountinfo file shows not all mounts, if a few points have been
1383 * unmounted between read operations from the mountinfo. So we need to
1384 * read mountinfo a few times.
1386 * This loop can be skipped if a container uses userns, because all
1387 * inherited mounts are locked and we should live with all this trash.
1390 __do_fclose
FILE *f
= NULL
;
1393 f
= fopen("./proc/self/mountinfo", "r");
1395 SYSERROR("Failed to open \"/proc/self/mountinfo\"");
1399 while (fgets(buf
, LXC_LINELEN
, f
)) {
1400 for (p
= buf
, i
=0; p
&& i
< 4; i
++)
1401 p
= strchr(p
+1, ' ');
1406 p2
= strchr(p
+1, ' ');
1413 if (strcmp(p
+ 1, "/") == 0)
1416 if (strcmp(p
+ 1, "/proc") == 0)
1419 ret
= umount2(p
, MNT_DETACH
);
1428 /* This also can be skipped if a container uses userns. */
1429 (void)umount2("./proc", MNT_DETACH
);
1431 /* It is weird, but chdir("..") moves us in a new root */
1434 SYSERROR("Failed to chdir(\"..\")");
1440 SYSERROR("Failed to chroot(\".\")");
1447 /* (The following explanation is copied verbatim from the kernel.)
1449 * pivot_root Semantics:
1450 * Moves the root file system of the current process to the directory put_old,
1451 * makes new_root as the new root file system of the current process, and sets
1452 * root/cwd of all processes which had them on the current root to new_root.
1455 * The new_root and put_old must be directories, and must not be on the
1456 * same file system as the current process root. The put_old must be
1457 * underneath new_root, i.e. adding a non-zero number of /.. to the string
1458 * pointed to by put_old must yield the same directory as new_root. No other
1459 * file system may be mounted on put_old. After all, new_root is a mountpoint.
1461 * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
1462 * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
1463 * in this situation.
1466 * - we don't move root/cwd if they are not at the root (reason: if something
1467 * cared enough to change them, it's probably wrong to force them elsewhere)
1468 * - it's okay to pick a root that isn't the root of a file system, e.g.
1469 * /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
1470 * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
1473 static int lxc_pivot_root(const char *rootfs
)
1475 __do_close_prot_errno
int oldroot
= -EBADF
, newroot
= -EBADF
;
1478 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1480 SYSERROR("Failed to open old root directory");
1484 newroot
= open(rootfs
, O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1486 SYSERROR("Failed to open new root directory");
1490 /* change into new root fs */
1491 ret
= fchdir(newroot
);
1493 SYSERROR("Failed to change to new rootfs \"%s\"", rootfs
);
1497 /* pivot_root into our new root fs */
1498 ret
= pivot_root(".", ".");
1500 SYSERROR("Failed to pivot_root()");
1504 /* At this point the old-root is mounted on top of our new-root. To
1505 * unmounted it we must not be chdir'd into it, so escape back to
1508 ret
= fchdir(oldroot
);
1510 SYSERROR("Failed to enter old root directory");
1514 /* Make oldroot rslave to make sure our umounts don't propagate to the
1517 ret
= mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
);
1519 SYSERROR("Failed to make oldroot rslave");
1523 ret
= umount2(".", MNT_DETACH
);
1525 SYSERROR("Failed to detach old root directory");
1529 ret
= fchdir(newroot
);
1531 SYSERROR("Failed to re-enter new root directory");
1535 TRACE("pivot_root(\"%s\") successful", rootfs
);
1540 static int lxc_setup_rootfs_switch_root(const struct lxc_rootfs
*rootfs
)
1542 if (!rootfs
->path
) {
1543 DEBUG("Container does not have a rootfs");
1547 if (detect_ramfs_rootfs())
1548 return lxc_chroot(rootfs
);
1550 return lxc_pivot_root(rootfs
->mount
);
1553 static const struct id_map
*find_mapped_nsid_entry(struct lxc_conf
*conf
,
1557 struct lxc_list
*it
;
1559 struct id_map
*retmap
= NULL
;
1561 /* Shortcut for container's root mappings. */
1563 if (idtype
== ID_TYPE_UID
)
1564 return conf
->root_nsuid_map
;
1566 if (idtype
== ID_TYPE_GID
)
1567 return conf
->root_nsgid_map
;
1570 lxc_list_for_each(it
, &conf
->id_map
) {
1572 if (map
->idtype
!= idtype
)
1575 if (id
>= map
->nsid
&& id
< map
->nsid
+ map
->range
) {
1584 static int lxc_setup_devpts(struct lxc_conf
*conf
)
1588 char devpts_mntopts
[256];
1589 char *mntopt_sets
[5];
1590 char default_devpts_mntopts
[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
1592 if (conf
->pty_max
<= 0) {
1593 DEBUG("No new devpts instance will be mounted since no pts "
1594 "devices are requested");
1598 ret
= snprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%zu",
1599 default_devpts_mntopts
, conf
->pty_max
);
1600 if (ret
< 0 || (size_t)ret
>= sizeof(devpts_mntopts
))
1603 (void)umount2("/dev/pts", MNT_DETACH
);
1605 /* Create mountpoint for devpts instance. */
1606 ret
= mkdir("/dev/pts", 0755);
1607 if (ret
< 0 && errno
!= EEXIST
) {
1608 SYSERROR("Failed to create \"/dev/pts\" directory");
1613 mntopt_sets
[0] = devpts_mntopts
;
1615 /* !gid=5 && max= */
1616 mntopt_sets
[1] = devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1618 /* gid=5 && !max= */
1619 mntopt_sets
[2] = default_devpts_mntopts
;
1621 /* !gid=5 && !max= */
1622 mntopt_sets
[3] = default_devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1625 mntopt_sets
[4] = NULL
;
1627 for (ret
= -1, opts
= mntopt_sets
; opts
&& *opts
; opts
++) {
1628 /* mount new devpts instance */
1629 ret
= mount("devpts", "/dev/pts", "devpts", MS_NOSUID
| MS_NOEXEC
, *opts
);
1635 SYSERROR("Failed to mount new devpts instance");
1638 DEBUG("Mount new devpts instance with options \"%s\"", *opts
);
1640 /* Remove any pre-existing /dev/ptmx file. */
1641 ret
= remove("/dev/ptmx");
1643 if (errno
!= ENOENT
) {
1644 SYSERROR("Failed to remove existing \"/dev/ptmx\" file");
1648 DEBUG("Removed existing \"/dev/ptmx\" file");
1651 /* Create dummy /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1652 ret
= mknod("/dev/ptmx", S_IFREG
| 0000, 0);
1653 if (ret
< 0 && errno
!= EEXIST
) {
1654 SYSERROR("Failed to create dummy \"/dev/ptmx\" file as bind mount target");
1657 DEBUG("Created dummy \"/dev/ptmx\" file as bind mount target");
1659 /* Fallback option: create symlink /dev/ptmx -> /dev/pts/ptmx */
1660 ret
= mount("/dev/pts/ptmx", "/dev/ptmx", NULL
, MS_BIND
, NULL
);
1662 DEBUG("Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1665 /* Fallthrough and try to create a symlink. */
1666 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1669 /* Remove the dummy /dev/ptmx file we created above. */
1670 ret
= remove("/dev/ptmx");
1672 SYSERROR("Failed to remove existing \"/dev/ptmx\"");
1676 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1677 ret
= symlink("/dev/pts/ptmx", "/dev/ptmx");
1679 SYSERROR("Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1682 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1687 static int setup_personality(int persona
)
1691 #if HAVE_SYS_PERSONALITY_H
1695 ret
= personality(persona
);
1697 SYSERROR("Failed to set personality to \"0x%x\"", persona
);
1701 INFO("Set personality to \"0x%x\"", persona
);
1707 static int lxc_setup_dev_console(const struct lxc_rootfs
*rootfs
,
1708 const struct lxc_terminal
*console
)
1711 char path
[PATH_MAX
];
1712 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1714 if (console
->path
&& !strcmp(console
->path
, "none"))
1717 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1718 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1721 /* When we are asked to setup a console we remove any previous
1722 * /dev/console bind-mounts.
1724 if (file_exists(path
)) {
1725 ret
= lxc_unstack_mountpoint(path
, false);
1727 SYSERROR("Failed to unmount \"%s\"", path
);
1730 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1734 /* For unprivileged containers autodev or automounts will already have
1735 * taken care of creating /dev/console.
1737 ret
= mknod(path
, S_IFREG
| 0000, 0);
1738 if (ret
< 0 && errno
!= EEXIST
) {
1739 SYSERROR("Failed to create console");
1743 ret
= fchmod(console
->slave
, S_IXUSR
| S_IXGRP
);
1745 SYSERROR("Failed to set mode \"0%o\" to \"%s\"",
1746 S_IXUSR
| S_IXGRP
, console
->name
);
1750 ret
= safe_mount(console
->name
, path
, "none", MS_BIND
, 0, rootfs_path
);
1752 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, path
);
1756 DEBUG("Mounted pts device \"%s\" onto \"%s\"", console
->name
, path
);
1760 static int lxc_setup_ttydir_console(const struct lxc_rootfs
*rootfs
,
1761 const struct lxc_terminal
*console
,
1765 char path
[PATH_MAX
], lxcpath
[PATH_MAX
];
1766 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1768 if (console
->path
&& !strcmp(console
->path
, "none"))
1771 /* create rootfs/dev/<ttydir> directory */
1772 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs_path
, ttydir
);
1773 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1776 ret
= mkdir(path
, 0755);
1777 if (ret
&& errno
!= EEXIST
) {
1778 SYSERROR("Failed to create \"%s\"", path
);
1781 DEBUG("Created directory for console and tty devices at \"%s\"", path
);
1783 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/dev/%s/console", rootfs_path
, ttydir
);
1784 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1787 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
1788 if (ret
< 0 && errno
!= EEXIST
) {
1789 SYSERROR("Failed to create \"%s\"", lxcpath
);
1793 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1794 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1797 if (file_exists(path
)) {
1798 ret
= lxc_unstack_mountpoint(path
, false);
1800 SYSERROR("Failed to unmount \"%s\"", path
);
1803 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1807 ret
= mknod(path
, S_IFREG
| 0000, 0);
1808 if (ret
< 0 && errno
!= EEXIST
) {
1809 SYSERROR("Failed to create console");
1813 ret
= fchmod(console
->slave
, S_IXUSR
| S_IXGRP
);
1815 SYSERROR("Failed to set mode \"0%o\" to \"%s\"",
1816 S_IXUSR
| S_IXGRP
, console
->name
);
1820 /* bind mount console->name to '/dev/<ttydir>/console' */
1821 ret
= safe_mount(console
->name
, lxcpath
, "none", MS_BIND
, 0, rootfs_path
);
1823 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1826 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1828 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
1829 ret
= safe_mount(lxcpath
, path
, "none", MS_BIND
, 0, rootfs_path
);
1831 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1834 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1836 DEBUG("Console has been setup under \"%s\" and mounted to \"%s\"", lxcpath
, path
);
1840 static int lxc_setup_console(const struct lxc_rootfs
*rootfs
,
1841 const struct lxc_terminal
*console
, char *ttydir
)
1845 return lxc_setup_dev_console(rootfs
, console
);
1847 return lxc_setup_ttydir_console(rootfs
, console
, ttydir
);
1850 static void parse_mntopt(char *opt
, unsigned long *flags
, char **data
, size_t size
)
1852 struct mount_opt
*mo
;
1854 /* If opt is found in mount_opt, set or clear flags.
1855 * Otherwise append it to data. */
1857 for (mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
1858 if (strncmp(opt
, mo
->name
, strlen(mo
->name
)) == 0) {
1860 *flags
&= ~mo
->flag
;
1868 (void)strlcat(*data
, ",", size
);
1870 (void)strlcat(*data
, opt
, size
);
1873 int parse_mntopts(const char *mntopts
, unsigned long *mntflags
, char **mntdata
)
1875 __do_free
char *data
= NULL
, *s
= NULL
;
1885 s
= strdup(mntopts
);
1889 size
= strlen(s
) + 1;
1890 data
= malloc(size
);
1895 lxc_iterate_parts(p
, s
, ",")
1896 parse_mntopt(p
, mntflags
, &data
, size
);
1899 *mntdata
= move_ptr(data
);
1904 static void parse_propagationopt(char *opt
, unsigned long *flags
)
1906 struct mount_opt
*mo
;
1908 /* If opt is found in propagation_opt, set or clear flags. */
1909 for (mo
= &propagation_opt
[0]; mo
->name
!= NULL
; mo
++) {
1910 if (strncmp(opt
, mo
->name
, strlen(mo
->name
)) != 0)
1914 *flags
&= ~mo
->flag
;
1922 int parse_propagationopts(const char *mntopts
, unsigned long *pflags
)
1924 __do_free
char *s
= NULL
;
1930 s
= strdup(mntopts
);
1932 SYSERROR("Failed to allocate memory");
1937 lxc_iterate_parts(p
, s
, ",")
1938 parse_propagationopt(p
, pflags
);
1943 static void null_endofword(char *word
)
1945 while (*word
&& *word
!= ' ' && *word
!= '\t')
1950 /* skip @nfields spaces in @src */
1951 static char *get_field(char *src
, int nfields
)
1956 for (i
= 0; i
< nfields
; i
++) {
1957 while (*p
&& *p
!= ' ' && *p
!= '\t')
1969 static int mount_entry(const char *fsname
, const char *target
,
1970 const char *fstype
, unsigned long mountflags
,
1971 unsigned long pflags
, const char *data
, bool optional
,
1972 bool dev
, bool relative
, const char *rootfs
)
1975 char srcbuf
[PATH_MAX
];
1976 const char *srcpath
= fsname
;
1982 ret
= snprintf(srcbuf
, PATH_MAX
, "%s/%s", rootfs
? rootfs
: "/", fsname
? fsname
: "");
1983 if (ret
< 0 || ret
>= PATH_MAX
) {
1984 ERROR("source path is too long");
1990 ret
= safe_mount(srcpath
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
1994 SYSINFO("Failed to mount \"%s\" on \"%s\" (optional)",
1995 srcpath
? srcpath
: "(null)", target
);
1999 SYSERROR("Failed to mount \"%s\" on \"%s\"",
2000 srcpath
? srcpath
: "(null)", target
);
2004 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
2005 unsigned long rqd_flags
= 0;
2007 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount "
2008 "options", srcpath
? srcpath
: "(none)", target
? target
: "(none)");
2010 if (mountflags
& MS_RDONLY
)
2011 rqd_flags
|= MS_RDONLY
;
2013 if (srcpath
&& statvfs(srcpath
, &sb
) == 0) {
2014 unsigned long required_flags
= rqd_flags
;
2016 if (sb
.f_flag
& MS_NOSUID
)
2017 required_flags
|= MS_NOSUID
;
2019 if (sb
.f_flag
& MS_NODEV
&& !dev
)
2020 required_flags
|= MS_NODEV
;
2022 if (sb
.f_flag
& MS_RDONLY
)
2023 required_flags
|= MS_RDONLY
;
2025 if (sb
.f_flag
& MS_NOEXEC
)
2026 required_flags
|= MS_NOEXEC
;
2028 DEBUG("Flags for \"%s\" were %lu, required extra flags "
2029 "are %lu", srcpath
, sb
.f_flag
, required_flags
);
2031 /* If this was a bind mount request, and required_flags
2032 * does not have any flags which are not already in
2033 * mountflags, then skip the remount.
2035 if (!(mountflags
& MS_REMOUNT
)) {
2036 if (!(required_flags
& ~mountflags
) &&
2038 DEBUG("Mountflags already were %lu, "
2039 "skipping remount", mountflags
);
2044 mountflags
|= required_flags
;
2048 ret
= mount(srcpath
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
2051 SYSINFO("Failed to mount \"%s\" on \"%s\" (optional)",
2052 srcpath
? srcpath
: "(null)", target
);
2056 SYSERROR("Failed to mount \"%s\" on \"%s\"",
2057 srcpath
? srcpath
: "(null)", target
);
2066 ret
= mount(NULL
, target
, NULL
, pflags
, NULL
);
2069 SYSINFO("Failed to change mount propagation "
2070 "for \"%s\" (optional)", target
);
2073 SYSERROR("Failed to change mount propagation "
2074 "for \"%s\" (optional)", target
);
2078 DEBUG("Changed mount propagation for \"%s\"", target
);
2081 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
2082 srcpath
? srcpath
: "(null)", target
, fstype
);
2087 /* Remove "optional", "create=dir", and "create=file" from mntopt */
2088 static void cull_mntent_opt(struct mntent
*mntent
)
2099 for (i
= 0; list
[i
]; i
++) {
2102 p
= strstr(mntent
->mnt_opts
, list
[i
]);
2106 p2
= strchr(p
, ',');
2108 /* no more mntopts, so just chop it here */
2113 memmove(p
, p2
+ 1, strlen(p2
+ 1) + 1);
2117 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
2119 const struct lxc_rootfs
*rootfs
,
2120 const char *lxc_name
, const char *lxc_path
)
2122 __do_free
char *p1
= NULL
;
2126 if (strncmp(mntent
->mnt_type
, "overlay", 7) == 0) {
2127 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
2132 if (hasmntopt(mntent
, "create=dir")) {
2133 ret
= mkdir_p(path
, 0755);
2134 if (ret
< 0 && errno
!= EEXIST
) {
2135 SYSERROR("Failed to create directory \"%s\"", path
);
2140 if (!hasmntopt(mntent
, "create=file"))
2143 ret
= access(path
, F_OK
);
2153 ret
= mkdir_p(p2
, 0755);
2154 if (ret
< 0 && errno
!= EEXIST
) {
2155 SYSERROR("Failed to create directory \"%s\"", path
);
2159 ret
= mknod(path
, S_IFREG
| 0000, 0);
2160 if (ret
< 0 && errno
!= EEXIST
)
2166 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2167 * without a rootfs. */
2168 static inline int mount_entry_on_generic(struct mntent
*mntent
,
2170 const struct lxc_rootfs
*rootfs
,
2171 const char *lxc_name
,
2172 const char *lxc_path
)
2174 __do_free
char *mntdata
= NULL
;
2176 unsigned long mntflags
;
2177 bool dev
, optional
, relative
;
2178 unsigned long pflags
= 0;
2179 char *rootfs_path
= NULL
;
2181 optional
= hasmntopt(mntent
, "optional") != NULL
;
2182 dev
= hasmntopt(mntent
, "dev") != NULL
;
2183 relative
= hasmntopt(mntent
, "relative") != NULL
;
2185 if (rootfs
&& rootfs
->path
)
2186 rootfs_path
= rootfs
->mount
;
2188 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
2196 cull_mntent_opt(mntent
);
2198 ret
= parse_propagationopts(mntent
->mnt_opts
, &pflags
);
2202 ret
= parse_mntopts(mntent
->mnt_opts
, &mntflags
, &mntdata
);
2206 ret
= mount_entry(mntent
->mnt_fsname
, path
, mntent
->mnt_type
, mntflags
,
2207 pflags
, mntdata
, optional
, dev
, relative
, rootfs_path
);
2212 static inline int mount_entry_on_systemfs(struct mntent
*mntent
)
2215 char path
[PATH_MAX
];
2217 /* For containers created without a rootfs all mounts are treated as
2218 * absolute paths starting at / on the host.
2220 if (mntent
->mnt_dir
[0] != '/')
2221 ret
= snprintf(path
, sizeof(path
), "/%s", mntent
->mnt_dir
);
2223 ret
= snprintf(path
, sizeof(path
), "%s", mntent
->mnt_dir
);
2224 if (ret
< 0 || ret
>= sizeof(path
))
2227 return mount_entry_on_generic(mntent
, path
, NULL
, NULL
, NULL
);
2230 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
2231 const struct lxc_rootfs
*rootfs
,
2232 const char *lxc_name
,
2233 const char *lxc_path
)
2237 const char *lxcpath
;
2238 char path
[PATH_MAX
];
2241 lxcpath
= lxc_global_config_value("lxc.lxcpath");
2245 /* If rootfs->path is a blockdev path, allow container fstab to use
2246 * <lxcpath>/<name>/rootfs" as the target prefix.
2248 ret
= snprintf(path
, PATH_MAX
, "%s/%s/rootfs", lxcpath
, lxc_name
);
2249 if (ret
< 0 || ret
>= PATH_MAX
)
2252 aux
= strstr(mntent
->mnt_dir
, path
);
2254 offset
= strlen(path
);
2259 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
2261 WARN("Ignoring mount point \"%s\"", mntent
->mnt_dir
);
2264 offset
= strlen(rootfs
->path
);
2267 ret
= snprintf(path
, PATH_MAX
, "%s/%s", rootfs
->mount
, aux
+ offset
);
2268 if (ret
< 0 || ret
>= PATH_MAX
)
2271 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2274 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
2275 const struct lxc_rootfs
*rootfs
,
2276 const char *lxc_name
,
2277 const char *lxc_path
)
2280 char path
[PATH_MAX
];
2282 /* relative to root mount point */
2283 ret
= snprintf(path
, sizeof(path
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2284 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
2287 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2290 static int mount_file_entries(const struct lxc_conf
*conf
,
2291 const struct lxc_rootfs
*rootfs
, FILE *file
,
2292 const char *lxc_name
, const char *lxc_path
)
2295 struct mntent mntent
;
2297 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2301 ret
= mount_entry_on_systemfs(&mntent
);
2302 else if (mntent
.mnt_dir
[0] != '/')
2303 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2304 lxc_name
, lxc_path
);
2306 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2307 lxc_name
, lxc_path
);
2312 if (!feof(file
) || ferror(file
)) {
2313 ERROR("Failed to parse mount entries");
2320 static int setup_mount(const struct lxc_conf
*conf
,
2321 const struct lxc_rootfs
*rootfs
, const char *fstab
,
2322 const char *lxc_name
, const char *lxc_path
)
2330 f
= setmntent(fstab
, "r");
2332 SYSERROR("Failed to open \"%s\"", fstab
);
2336 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2338 ERROR("Failed to set up mount entries");
2345 * In order for nested containers to be able to mount /proc and /sys they need
2346 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2348 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2349 * apparmor rule to deny access to them. This is mostly for convenience: The
2350 * container's root user can mount them anyway and thus has access to the two
2351 * file systems. But a non-root user in the container should not be allowed to
2352 * access them as a side effect without explicitly allowing it.
2354 static const char nesting_helpers
[] =
2355 "proc dev/.lxc/proc proc create=dir,optional 0 0\n"
2356 "sys dev/.lxc/sys sysfs create=dir,optional 0 0\n";
2358 FILE *make_anonymous_mount_file(struct lxc_list
*mount
,
2359 bool include_nesting_helpers
)
2361 __do_close_prot_errno
int fd
= -EBADF
;
2364 struct lxc_list
*iterator
;
2366 fd
= memfd_create(".lxc_mount_file", MFD_CLOEXEC
);
2368 char template[] = P_tmpdir
"/.lxc_mount_file_XXXXXX";
2370 if (errno
!= ENOSYS
)
2373 fd
= lxc_make_tmpfile(template, true);
2375 SYSERROR("Could not create temporary mount file");
2379 TRACE("Created temporary mount file");
2382 lxc_list_for_each (iterator
, mount
) {
2385 mount_entry
= iterator
->elem
;
2386 len
= strlen(mount_entry
);
2388 ret
= lxc_write_nointr(fd
, mount_entry
, len
);
2392 ret
= lxc_write_nointr(fd
, "\n", 1);
2397 if (include_nesting_helpers
) {
2398 ret
= lxc_write_nointr(fd
, nesting_helpers
,
2399 STRARRAYLEN(nesting_helpers
));
2400 if (ret
!= STRARRAYLEN(nesting_helpers
))
2404 ret
= lseek(fd
, 0, SEEK_SET
);
2408 return fdopen(move_fd(fd
), "r+");
2411 static int setup_mount_entries(const struct lxc_conf
*conf
,
2412 const struct lxc_rootfs
*rootfs
,
2413 struct lxc_list
*mount
, const char *lxc_name
,
2414 const char *lxc_path
)
2416 __do_fclose
FILE *f
= NULL
;
2418 f
= make_anonymous_mount_file(mount
, conf
->lsm_aa_allow_nesting
);
2422 return mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2425 static int parse_cap(const char *cap
)
2429 size_t end
= sizeof(caps_opt
) / sizeof(caps_opt
[0]);
2432 if (strcmp(cap
, "none") == 0)
2435 for (i
= 0; i
< end
; i
++) {
2436 if (strcmp(cap
, caps_opt
[i
].name
))
2439 capid
= caps_opt
[i
].value
;
2444 /* Try to see if it's numeric, so the user may specify
2445 * capabilities that the running kernel knows about but we
2449 capid
= strtol(cap
, &ptr
, 10);
2450 if (!ptr
|| *ptr
!= '\0' || errno
!= 0)
2451 /* not a valid number */
2453 else if (capid
> lxc_caps_last_cap())
2454 /* we have a number but it's not a valid
2462 int in_caplist(int cap
, struct lxc_list
*caps
)
2465 struct lxc_list
*iterator
;
2467 lxc_list_for_each (iterator
, caps
) {
2468 capid
= parse_cap(iterator
->elem
);
2476 static int setup_caps(struct lxc_list
*caps
)
2480 struct lxc_list
*iterator
;
2482 lxc_list_for_each (iterator
, caps
) {
2485 drop_entry
= iterator
->elem
;
2487 capid
= parse_cap(drop_entry
);
2489 ERROR("unknown capability %s", drop_entry
);
2493 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(capid
), prctl_arg(0),
2494 prctl_arg(0), prctl_arg(0));
2496 SYSERROR("Failed to remove %s capability", drop_entry
);
2499 DEBUG("Dropped %s (%d) capability", drop_entry
, capid
);
2502 DEBUG("Capabilities have been setup");
2506 static int dropcaps_except(struct lxc_list
*caps
)
2508 __do_free
int *caplist
= NULL
;
2509 int i
, capid
, numcaps
;
2511 struct lxc_list
*iterator
;
2513 numcaps
= lxc_caps_last_cap() + 1;
2514 if (numcaps
<= 0 || numcaps
> 200)
2516 TRACE("Found %d capabilities", numcaps
);
2518 /* caplist[i] is 1 if we keep capability i */
2519 caplist
= must_realloc(NULL
, numcaps
* sizeof(int));
2520 memset(caplist
, 0, numcaps
* sizeof(int));
2522 lxc_list_for_each (iterator
, caps
) {
2523 keep_entry
= iterator
->elem
;
2525 capid
= parse_cap(keep_entry
);
2530 ERROR("Unknown capability %s", keep_entry
);
2534 DEBUG("Keep capability %s (%d)", keep_entry
, capid
);
2538 for (i
= 0; i
< numcaps
; i
++) {
2544 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(i
), prctl_arg(0),
2545 prctl_arg(0), prctl_arg(0));
2547 SYSERROR("Failed to remove capability %d", i
);
2552 DEBUG("Capabilities have been setup");
2556 static int parse_resource(const char *res
)
2562 for (i
= 0; i
< sizeof(limit_opt
) / sizeof(limit_opt
[0]); ++i
)
2563 if (strcmp(res
, limit_opt
[i
].name
) == 0)
2564 return limit_opt
[i
].value
;
2566 /* Try to see if it's numeric, so the user may specify
2567 * resources that the running kernel knows about but
2570 ret
= lxc_safe_int(res
, &resid
);
2577 int setup_resource_limits(struct lxc_list
*limits
, pid_t pid
)
2580 struct lxc_list
*it
;
2581 struct lxc_limit
*lim
;
2583 lxc_list_for_each (it
, limits
) {
2586 resid
= parse_resource(lim
->resource
);
2588 ERROR("Unknown resource %s", lim
->resource
);
2592 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
2593 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0) {
2594 SYSERROR("Failed to set limit %s", lim
->resource
);
2598 TRACE("Setup \"%s\" limit", lim
->resource
);
2600 ERROR("Cannot set limit \"%s\" as prlimit is missing", lim
->resource
);
2608 int setup_sysctl_parameters(struct lxc_list
*sysctls
)
2610 __do_free
char *tmp
= NULL
;
2611 struct lxc_list
*it
;
2612 struct lxc_sysctl
*elem
;
2614 char filename
[PATH_MAX
] = {0};
2616 lxc_list_for_each (it
, sysctls
) {
2618 tmp
= lxc_string_replace(".", "/", elem
->key
);
2620 ERROR("Failed to replace key %s", elem
->key
);
2624 ret
= snprintf(filename
, sizeof(filename
), "/proc/sys/%s", tmp
);
2625 if (ret
< 0 || (size_t)ret
>= sizeof(filename
)) {
2626 ERROR("Error setting up sysctl parameters path");
2630 ret
= lxc_write_to_file(filename
, elem
->value
,
2631 strlen(elem
->value
), false, 0666);
2633 SYSERROR("Failed to setup sysctl parameters %s to %s",
2634 elem
->key
, elem
->value
);
2642 int setup_proc_filesystem(struct lxc_list
*procs
, pid_t pid
)
2644 __do_free
char *tmp
= NULL
;
2645 struct lxc_list
*it
;
2646 struct lxc_proc
*elem
;
2648 char filename
[PATH_MAX
] = {0};
2650 lxc_list_for_each (it
, procs
) {
2652 tmp
= lxc_string_replace(".", "/", elem
->filename
);
2654 ERROR("Failed to replace key %s", elem
->filename
);
2658 ret
= snprintf(filename
, sizeof(filename
), "/proc/%d/%s", pid
, tmp
);
2659 if (ret
< 0 || (size_t)ret
>= sizeof(filename
)) {
2660 ERROR("Error setting up proc filesystem path");
2664 ret
= lxc_write_to_file(filename
, elem
->value
,
2665 strlen(elem
->value
), false, 0666);
2667 SYSERROR("Failed to setup proc filesystem %s to %s",
2668 elem
->filename
, elem
->value
);
2676 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
2678 struct lxc_conf
*lxc_conf_init(void)
2681 struct lxc_conf
*new;
2683 new = malloc(sizeof(*new));
2686 memset(new, 0, sizeof(*new));
2688 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
2689 new->personality
= -1;
2691 new->console
.buffer_size
= 0;
2692 new->console
.log_path
= NULL
;
2693 new->console
.log_fd
= -1;
2694 new->console
.log_size
= 0;
2695 new->console
.path
= NULL
;
2696 new->console
.peer
= -1;
2697 new->console
.proxy
.busy
= -1;
2698 new->console
.proxy
.master
= -1;
2699 new->console
.proxy
.slave
= -1;
2700 new->console
.master
= -1;
2701 new->console
.slave
= -1;
2702 new->console
.name
[0] = '\0';
2703 memset(&new->console
.ringbuf
, 0, sizeof(struct lxc_ringbuf
));
2704 new->maincmd_fd
= -1;
2705 new->monitor_signal_pdeath
= SIGKILL
;
2707 new->rootfs
.mount
= strdup(default_rootfs_mount
);
2708 if (!new->rootfs
.mount
) {
2712 new->rootfs
.managed
= true;
2714 lxc_list_init(&new->cgroup
);
2715 lxc_list_init(&new->cgroup2
);
2716 lxc_list_init(&new->network
);
2717 lxc_list_init(&new->mount_list
);
2718 lxc_list_init(&new->caps
);
2719 lxc_list_init(&new->keepcaps
);
2720 lxc_list_init(&new->id_map
);
2721 new->root_nsuid_map
= NULL
;
2722 new->root_nsgid_map
= NULL
;
2723 lxc_list_init(&new->includes
);
2724 lxc_list_init(&new->aliens
);
2725 lxc_list_init(&new->environment
);
2726 lxc_list_init(&new->limits
);
2727 lxc_list_init(&new->sysctls
);
2728 lxc_list_init(&new->procs
);
2729 new->hooks_version
= 0;
2730 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++)
2731 lxc_list_init(&new->hooks
[i
]);
2732 lxc_list_init(&new->groups
);
2733 lxc_list_init(&new->state_clients
);
2734 new->lsm_aa_profile
= NULL
;
2735 lxc_list_init(&new->lsm_aa_raw
);
2736 new->lsm_se_context
= NULL
;
2737 new->tmp_umount_proc
= false;
2738 new->tmp_umount_proc
= 0;
2739 new->shmount
.path_host
= NULL
;
2740 new->shmount
.path_cont
= NULL
;
2742 /* if running in a new user namespace, init and COMMAND
2743 * default to running as UID/GID 0 when using lxc-execute */
2746 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
2747 memset(&new->ns_share
, 0, sizeof(char *) * LXC_NS_MAX
);
2752 int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
2755 __do_close_prot_errno
int fd
;
2757 char path
[PATH_MAX
];
2759 if (geteuid() != 0 && idtype
== ID_TYPE_GID
) {
2760 __do_close_prot_errno
int setgroups_fd
= -EBADF
;
2762 ret
= snprintf(path
, PATH_MAX
, "/proc/%d/setgroups", pid
);
2763 if (ret
< 0 || ret
>= PATH_MAX
)
2766 setgroups_fd
= open(path
, O_WRONLY
);
2767 if (setgroups_fd
< 0 && errno
!= ENOENT
) {
2768 SYSERROR("Failed to open \"%s\"", path
);
2772 if (setgroups_fd
>= 0) {
2773 ret
= lxc_write_nointr(setgroups_fd
, "deny\n",
2774 STRLITERALLEN("deny\n"));
2775 if (ret
!= STRLITERALLEN("deny\n")) {
2776 SYSERROR("Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid
);
2779 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid
);
2783 ret
= snprintf(path
, PATH_MAX
, "/proc/%d/%cid_map", pid
,
2784 idtype
== ID_TYPE_UID
? 'u' : 'g');
2785 if (ret
< 0 || ret
>= PATH_MAX
)
2788 fd
= open(path
, O_WRONLY
);
2790 SYSERROR("Failed to open \"%s\"", path
);
2794 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
2795 if (ret
!= buf_size
) {
2796 SYSERROR("Failed to write %cid mapping to \"%s\"",
2797 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
2804 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2806 * @return 1 if functional binary was found
2807 * @return 0 if binary exists but is lacking privilege
2808 * @return -ENOENT if binary does not exist
2809 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2811 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
2813 __do_free
char *path
= NULL
;
2818 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
2822 path
= on_path(binary
, NULL
);
2826 ret
= stat(path
, &st
);
2830 /* Check if the binary is setuid. */
2831 if (st
.st_mode
& S_ISUID
) {
2832 DEBUG("The binary \"%s\" does have the setuid bit set", path
);
2836 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
2837 /* Check if it has the CAP_SETUID capability. */
2838 if ((cap
& CAP_SETUID
) &&
2839 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
2840 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
)) {
2841 DEBUG("The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE "
2842 "and CAP_PERMITTED sets", path
);
2846 /* Check if it has the CAP_SETGID capability. */
2847 if ((cap
& CAP_SETGID
) &&
2848 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
2849 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
)) {
2850 DEBUG("The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE "
2851 "and CAP_PERMITTED sets", path
);
2855 /* If we cannot check for file capabilities we need to give the benefit
2856 * of the doubt. Otherwise we might fail even though all the necessary
2857 * file capabilities are set.
2859 DEBUG("Cannot check for file capabilities as full capability support is "
2860 "missing. Manual intervention needed");
2866 int lxc_map_ids_exec_wrapper(void *args
)
2868 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
2872 int lxc_map_ids(struct lxc_list
*idmap
, pid_t pid
)
2877 char cmd_output
[PATH_MAX
];
2879 struct lxc_list
*iterator
;
2881 /* strlen("new@idmap") = 9
2885 * INTTYPE_TO_STRLEN(uint32_t)
2889 * We add some additional space to make sure that we really have
2890 * LXC_IDMAPLEN bytes available for our the {g,u]id mapping.
2892 int ret
= 0, gidmap
= 0, uidmap
= 0;
2893 char mapbuf
[9 + 1 + INTTYPE_TO_STRLEN(uint32_t) + 1 + LXC_IDMAPLEN
] = {0};
2894 bool had_entry
= false, use_shadow
= false;
2895 int hostuid
, hostgid
;
2897 hostuid
= geteuid();
2898 hostgid
= getegid();
2900 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2901 * ranges, then insist that root also reserve ranges in subuid. This
2902 * will protected it by preventing another user from being handed the
2905 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
2906 if (uidmap
== -ENOENT
)
2907 WARN("newuidmap binary is missing");
2909 WARN("newuidmap is lacking necessary privileges");
2911 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
2912 if (gidmap
== -ENOENT
)
2913 WARN("newgidmap binary is missing");
2915 WARN("newgidmap is lacking necessary privileges");
2917 if (uidmap
> 0 && gidmap
> 0) {
2918 DEBUG("Functional newuidmap and newgidmap binary found");
2921 /* In case unprivileged users run application containers via
2922 * execute() or a start*() there are valid cases where they may
2923 * only want to map their own {g,u}id. Let's not block them from
2924 * doing so by requiring geteuid() == 0.
2926 DEBUG("No newuidmap and newgidmap binary found. Trying to "
2927 "write directly with euid %d", hostuid
);
2930 /* Check if we really need to use newuidmap and newgidmap.
2931 * If the user is only remapping his own {g,u}id, we don't need it.
2933 if (use_shadow
&& lxc_list_len(idmap
) == 2) {
2935 lxc_list_for_each(iterator
, idmap
) {
2936 map
= iterator
->elem
;
2937 if (map
->idtype
== ID_TYPE_UID
&& map
->range
== 1 &&
2938 map
->nsid
== hostuid
&& map
->hostid
== hostuid
)
2940 if (map
->idtype
== ID_TYPE_GID
&& map
->range
== 1 &&
2941 map
->nsid
== hostgid
&& map
->hostid
== hostgid
)
2948 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
2949 type
++, u_or_g
= 'g') {
2953 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
2955 lxc_list_for_each(iterator
, idmap
) {
2956 map
= iterator
->elem
;
2957 if (map
->idtype
!= type
)
2962 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
2963 fill
= snprintf(pos
, left
, "%s%lu %lu %lu%s",
2964 use_shadow
? " " : "", map
->nsid
,
2965 map
->hostid
, map
->range
,
2966 use_shadow
? "" : "\n");
2967 if (fill
<= 0 || fill
>= left
) {
2968 /* The kernel only takes <= 4k for writes to
2969 * /proc/<pid>/{g,u}id_map
2971 SYSERROR("Too many %cid mappings defined", u_or_g
);
2980 /* Try to catch the output of new{g,u}idmap to make debugging
2984 ret
= run_command(cmd_output
, sizeof(cmd_output
),
2985 lxc_map_ids_exec_wrapper
,
2988 ERROR("new%cidmap failed to write mapping \"%s\": %s",
2989 u_or_g
, cmd_output
, mapbuf
);
2992 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g
, mapbuf
);
2994 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
2996 ERROR("Failed to write mapping: %s", mapbuf
);
2999 TRACE("Wrote mapping \"%s\"", mapbuf
);
3002 memset(mapbuf
, 0, sizeof(mapbuf
));
3008 /* Return the host uid/gid to which the container root is mapped in val.
3009 * Return true if id was found, false otherwise.
3011 bool get_mapped_rootid(struct lxc_conf
*conf
, enum idtype idtype
,
3016 struct lxc_list
*it
;
3018 if (idtype
== ID_TYPE_UID
)
3019 nsid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
3021 nsid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
3023 lxc_list_for_each (it
, &conf
->id_map
) {
3025 if (map
->idtype
!= idtype
)
3027 if (map
->nsid
!= nsid
)
3036 int mapped_hostid(unsigned id
, struct lxc_conf
*conf
, enum idtype idtype
)
3039 struct lxc_list
*it
;
3041 lxc_list_for_each (it
, &conf
->id_map
) {
3043 if (map
->idtype
!= idtype
)
3046 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
3047 return (id
- map
->hostid
) + map
->nsid
;
3053 int find_unmapped_nsid(struct lxc_conf
*conf
, enum idtype idtype
)
3056 struct lxc_list
*it
;
3057 unsigned int freeid
= 0;
3060 lxc_list_for_each (it
, &conf
->id_map
) {
3062 if (map
->idtype
!= idtype
)
3065 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
3066 freeid
= map
->nsid
+ map
->range
;
3074 int chown_mapped_root_exec_wrapper(void *args
)
3076 execvp("lxc-usernsexec", args
);
3080 /* chown_mapped_root: for an unprivileged user with uid/gid X to
3081 * chown a dir to subuid/subgid Y, he needs to run chown as root
3082 * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and
3083 * nsid Y is mapped to hostuid/hostgid X. That way, the container
3084 * root is privileged with respect to hostuid/hostgid X, allowing
3085 * him to do the chown.
3087 int chown_mapped_root(const char *path
, struct lxc_conf
*conf
)
3089 uid_t rootuid
, rootgid
;
3091 int hostuid
, hostgid
, ret
;
3093 char map1
[100], map2
[100], map3
[100], map4
[100], map5
[100];
3095 const char *args1
[] = {"lxc-usernsexec",
3100 "--", "chown", ugid
, path
,
3102 const char *args2
[] = {"lxc-usernsexec",
3108 "--", "chown", ugid
, path
,
3110 char cmd_output
[PATH_MAX
];
3112 hostuid
= geteuid();
3113 hostgid
= getegid();
3115 if (!get_mapped_rootid(conf
, ID_TYPE_UID
, &val
)) {
3116 ERROR("No uid mapping for container root");
3119 rootuid
= (uid_t
)val
;
3121 if (!get_mapped_rootid(conf
, ID_TYPE_GID
, &val
)) {
3122 ERROR("No gid mapping for container root");
3125 rootgid
= (gid_t
)val
;
3128 if (chown(path
, rootuid
, rootgid
) < 0) {
3129 ERROR("Error chowning %s", path
);
3136 if (rootuid
== hostuid
) {
3138 INFO("Container root is our uid; no need to chown");
3142 /* save the current gid of "path" */
3143 if (stat(path
, &sb
) < 0) {
3144 ERROR("Error stat %s", path
);
3148 /* Update the path argument in case this was overlayfs. */
3149 args1
[sizeof(args1
) / sizeof(args1
[0]) - 2] = path
;
3150 args2
[sizeof(args2
) / sizeof(args2
[0]) - 2] = path
;
3153 * A file has to be group-owned by a gid mapped into the
3154 * container, or the container won't be privileged over it.
3156 DEBUG("trying to chown \"%s\" to %d", path
, hostgid
);
3157 if (sb
.st_uid
== hostuid
&&
3158 mapped_hostid(sb
.st_gid
, conf
, ID_TYPE_GID
) < 0 &&
3159 chown(path
, -1, hostgid
) < 0) {
3160 ERROR("Failed chgrping %s", path
);
3164 /* "u:0:rootuid:1" */
3165 ret
= snprintf(map1
, 100, "u:0:%d:1", rootuid
);
3166 if (ret
< 0 || ret
>= 100) {
3167 ERROR("Error uid printing map string");
3171 /* "u:hostuid:hostuid:1" */
3172 ret
= snprintf(map2
, 100, "u:%d:%d:1", hostuid
, hostuid
);
3173 if (ret
< 0 || ret
>= 100) {
3174 ERROR("Error uid printing map string");
3178 /* "g:0:rootgid:1" */
3179 ret
= snprintf(map3
, 100, "g:0:%d:1", rootgid
);
3180 if (ret
< 0 || ret
>= 100) {
3181 ERROR("Error gid printing map string");
3185 /* "g:pathgid:rootgid+pathgid:1" */
3186 ret
= snprintf(map4
, 100, "g:%d:%d:1", (gid_t
)sb
.st_gid
,
3187 rootgid
+ (gid_t
)sb
.st_gid
);
3188 if (ret
< 0 || ret
>= 100) {
3189 ERROR("Error gid printing map string");
3193 /* "g:hostgid:hostgid:1" */
3194 ret
= snprintf(map5
, 100, "g:%d:%d:1", hostgid
, hostgid
);
3195 if (ret
< 0 || ret
>= 100) {
3196 ERROR("Error gid printing map string");
3200 /* "0:pathgid" (chown) */
3201 ret
= snprintf(ugid
, 100, "0:%d", (gid_t
)sb
.st_gid
);
3202 if (ret
< 0 || ret
>= 100) {
3203 ERROR("Error owner printing format string for chown");
3207 if (hostgid
== sb
.st_gid
)
3208 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3209 chown_mapped_root_exec_wrapper
,
3212 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3213 chown_mapped_root_exec_wrapper
,
3216 ERROR("lxc-usernsexec failed: %s", cmd_output
);
3221 /* NOTE: Must not be called from inside the container namespace! */
3222 int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
3226 mounted
= lxc_mount_proc_if_needed(conf
->rootfs
.path
? conf
->rootfs
.mount
: "");
3227 if (mounted
== -1) {
3228 SYSERROR("Failed to mount proc in the container");
3229 /* continue only if there is no rootfs */
3230 if (conf
->rootfs
.path
)
3232 } else if (mounted
== 1) {
3233 conf
->tmp_umount_proc
= true;
3239 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
3241 if (!lxc_conf
->tmp_umount_proc
)
3244 (void)umount2("/proc", MNT_DETACH
);
3245 lxc_conf
->tmp_umount_proc
= false;
3248 /* Walk /proc/mounts and change any shared entries to slave. */
3249 void remount_all_slave(void)
3251 __do_free
char *line
= NULL
;
3252 __do_fclose
FILE *f
= NULL
;
3253 __do_close_prot_errno
int memfd
= -EBADF
, mntinfo_fd
= -EBADF
;
3258 mntinfo_fd
= open("/proc/self/mountinfo", O_RDONLY
| O_CLOEXEC
);
3259 if (mntinfo_fd
< 0) {
3260 SYSERROR("Failed to open \"/proc/self/mountinfo\"");
3264 memfd
= memfd_create(".lxc_mountinfo", MFD_CLOEXEC
);
3266 char template[] = P_tmpdir
"/.lxc_mountinfo_XXXXXX";
3268 if (errno
!= ENOSYS
) {
3269 SYSERROR("Failed to create temporary in-memory file");
3273 memfd
= lxc_make_tmpfile(template, true);
3275 WARN("Failed to create temporary file");
3281 copied
= lxc_sendfile_nointr(memfd
, mntinfo_fd
, NULL
, LXC_SENDFILE_MAX
);
3286 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
3290 ret
= lseek(memfd
, 0, SEEK_SET
);
3292 SYSERROR("Failed to reset file descriptor offset");
3296 f
= fdopen(memfd
, "r");
3298 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark all shared. Continuing");
3303 * After a successful fdopen() memfd will be closed when calling
3304 * fclose(f). Calling close(memfd) afterwards is undefined.
3308 while (getline(&line
, &len
, f
) != -1) {
3309 char *opts
, *target
;
3311 target
= get_field(line
, 4);
3315 opts
= get_field(target
, 2);
3319 null_endofword(opts
);
3320 if (!strstr(opts
, "shared"))
3323 null_endofword(target
);
3324 ret
= mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
);
3326 SYSERROR("Failed to make \"%s\" MS_SLAVE", target
);
3327 ERROR("Continuing...");
3330 TRACE("Remounted \"%s\" as MS_SLAVE", target
);
3332 TRACE("Remounted all mount table entries as MS_SLAVE");
3335 static int lxc_execute_bind_init(struct lxc_handler
*handler
)
3339 char path
[PATH_MAX
], destpath
[PATH_MAX
];
3340 struct lxc_conf
*conf
= handler
->conf
;
3342 /* If init exists in the container, don't bind mount a static one */
3343 p
= choose_init(conf
->rootfs
.mount
);
3345 __do_free
char *old
= p
;
3347 p
= strdup(old
+ strlen(conf
->rootfs
.mount
));
3351 INFO("Found existing init at \"%s\"", p
);
3355 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3356 if (ret
< 0 || ret
>= PATH_MAX
)
3359 if (!file_exists(path
)) {
3360 ERROR("The file \"%s\" does not exist on host", path
);
3364 ret
= snprintf(destpath
, PATH_MAX
, "%s" P_tmpdir
"%s", conf
->rootfs
.mount
, "/.lxc-init");
3365 if (ret
< 0 || ret
>= PATH_MAX
)
3368 if (!file_exists(destpath
)) {
3369 ret
= mknod(destpath
, S_IFREG
| 0000, 0);
3370 if (ret
< 0 && errno
!= EEXIST
) {
3371 SYSERROR("Failed to create dummy \"%s\" file as bind mount target", destpath
);
3376 ret
= safe_mount(path
, destpath
, "none", MS_BIND
, NULL
, conf
->rootfs
.mount
);
3378 SYSERROR("Failed to bind mount lxc.init.static into container");
3382 p
= strdup(destpath
+ strlen(conf
->rootfs
.mount
));
3386 INFO("Bind mounted lxc.init.static into container at \"%s\"", path
);
3388 ((struct execute_args
*)handler
->data
)->init_fd
= -1;
3389 ((struct execute_args
*)handler
->data
)->init_path
= p
;
3393 /* This does the work of remounting / if it is shared, calling the container
3394 * pre-mount hooks, and mounting the rootfs.
3396 int lxc_setup_rootfs_prepare_root(struct lxc_conf
*conf
, const char *name
,
3397 const char *lxcpath
)
3401 if (conf
->rootfs_setup
) {
3402 const char *path
= conf
->rootfs
.mount
;
3404 /* The rootfs was set up in another namespace. bind-mount it to
3405 * give us a mount in our own ns so we can pivot_root to it
3407 ret
= mount(path
, path
, "rootfs", MS_BIND
, NULL
);
3409 ERROR("Failed to bind mount container / onto itself");
3413 TRACE("Bind mounted container / onto itself");
3417 remount_all_slave();
3419 ret
= run_lxc_hooks(name
, "pre-mount", conf
, NULL
);
3421 ERROR("Failed to run pre-mount hooks");
3425 ret
= lxc_mount_rootfs(conf
);
3427 ERROR("Failed to setup rootfs for");
3431 conf
->rootfs_setup
= true;
3435 static bool verify_start_hooks(struct lxc_conf
*conf
)
3437 char path
[PATH_MAX
];
3438 struct lxc_list
*it
;
3440 lxc_list_for_each (it
, &conf
->hooks
[LXCHOOK_START
]) {
3442 char *hookname
= it
->elem
;
3444 ret
= snprintf(path
, PATH_MAX
, "%s%s",
3445 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
3447 if (ret
< 0 || ret
>= PATH_MAX
)
3450 ret
= access(path
, X_OK
);
3452 SYSERROR("Start hook \"%s\" not found in container",
3463 static bool execveat_supported(void)
3465 lxc_raw_execveat(-1, "", NULL
, NULL
, AT_EMPTY_PATH
);
3466 if (errno
== ENOSYS
)
3472 int lxc_setup(struct lxc_handler
*handler
)
3475 const char *lxcpath
= handler
->lxcpath
, *name
= handler
->name
;
3476 struct lxc_conf
*lxc_conf
= handler
->conf
;
3478 ret
= lxc_setup_rootfs_prepare_root(lxc_conf
, name
, lxcpath
);
3480 ERROR("Failed to setup rootfs");
3484 if (handler
->nsfd
[LXC_NS_UTS
] == -1) {
3485 ret
= setup_utsname(lxc_conf
->utsname
);
3487 ERROR("Failed to setup the utsname %s", name
);
3492 ret
= lxc_setup_keyring();
3496 ret
= lxc_setup_network_in_child_namespaces(lxc_conf
, &lxc_conf
->network
);
3498 ERROR("Failed to setup network");
3502 ret
= lxc_network_send_name_and_ifindex_to_parent(handler
);
3504 ERROR("Failed to send network device names and ifindices to parent");
3508 if (lxc_conf
->autodev
> 0) {
3509 ret
= mount_autodev(name
, &lxc_conf
->rootfs
, lxcpath
);
3511 ERROR("Failed to mount \"/dev\"");
3516 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
3517 * need to wait until other stuff has finished.
3519 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
, handler
);
3521 ERROR("Failed to setup first automatic mounts");
3525 ret
= setup_mount(lxc_conf
, &lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
);
3527 ERROR("Failed to setup mounts");
3531 if (lxc_conf
->is_execute
) {
3532 if (execveat_supported()) {
3534 char path
[PATH_MAX
];
3536 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3537 if (ret
< 0 || ret
>= PATH_MAX
) {
3538 ERROR("Path to init.lxc.static too long");
3542 fd
= open(path
, O_PATH
| O_CLOEXEC
);
3544 SYSERROR("Unable to open lxc.init.static");
3548 ((struct execute_args
*)handler
->data
)->init_fd
= fd
;
3549 ((struct execute_args
*)handler
->data
)->init_path
= NULL
;
3551 ret
= lxc_execute_bind_init(handler
);
3553 ERROR("Failed to bind-mount the lxc init system");
3559 /* Now mount only cgroups, if wanted. Before, /sys could not have been
3560 * mounted. It is guaranteed to be mounted now either through
3561 * automatically or via fstab entries.
3563 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
, handler
);
3565 ERROR("Failed to setup remaining automatic mounts");
3569 ret
= run_lxc_hooks(name
, "mount", lxc_conf
, NULL
);
3571 ERROR("Failed to run mount hooks");
3575 if (lxc_conf
->autodev
> 0) {
3576 ret
= run_lxc_hooks(name
, "autodev", lxc_conf
, NULL
);
3578 ERROR("Failed to run autodev hooks");
3582 ret
= lxc_fill_autodev(&lxc_conf
->rootfs
);
3584 ERROR("Failed to populate \"/dev\"");
3589 if (!lxc_list_empty(&lxc_conf
->mount_list
)) {
3590 ret
= setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
,
3591 &lxc_conf
->mount_list
, name
, lxcpath
);
3593 ERROR("Failed to setup mount entries");
3598 /* Make sure any start hooks are in the container */
3599 if (!verify_start_hooks(lxc_conf
)) {
3600 ERROR("Failed to verify start hooks");
3604 ret
= lxc_setup_console(&lxc_conf
->rootfs
, &lxc_conf
->console
,
3605 lxc_conf
->ttys
.dir
);
3607 ERROR("Failed to setup console");
3611 ret
= lxc_setup_dev_symlinks(&lxc_conf
->rootfs
);
3613 ERROR("Failed to setup \"/dev\" symlinks");
3617 ret
= lxc_create_tmp_proc_mount(lxc_conf
);
3619 ERROR("Failed to \"/proc\" LSMs");
3623 ret
= lxc_setup_rootfs_switch_root(&lxc_conf
->rootfs
);
3625 ERROR("Failed to pivot root into rootfs");
3629 ret
= lxc_setup_devpts(lxc_conf
);
3631 ERROR("Failed to setup new devpts instance");
3635 ret
= lxc_create_ttys(handler
);
3639 ret
= setup_personality(lxc_conf
->personality
);
3641 ERROR("Failed to set personality");
3645 /* Set sysctl value to a path under /proc/sys as determined from the
3646 * key. For e.g. net.ipv4.ip_forward translated to
3647 * /proc/sys/net/ipv4/ip_forward.
3649 if (!lxc_list_empty(&lxc_conf
->sysctls
)) {
3650 ret
= setup_sysctl_parameters(&lxc_conf
->sysctls
);
3652 ERROR("Failed to setup sysctl parameters");
3657 if (!lxc_list_empty(&lxc_conf
->keepcaps
)) {
3658 if (!lxc_list_empty(&lxc_conf
->caps
)) {
3659 ERROR("Container requests lxc.cap.drop and "
3660 "lxc.cap.keep: either use lxc.cap.drop or "
3661 "lxc.cap.keep, not both");
3665 if (dropcaps_except(&lxc_conf
->keepcaps
)) {
3666 ERROR("Failed to keep capabilities");
3669 } else if (setup_caps(&lxc_conf
->caps
)) {
3670 ERROR("Failed to drop capabilities");
3674 NOTICE("The container \"%s\" is set up", name
);
3679 int run_lxc_hooks(const char *name
, char *hookname
, struct lxc_conf
*conf
,
3682 struct lxc_list
*it
;
3685 if (strcmp(hookname
, "pre-start") == 0)
3686 which
= LXCHOOK_PRESTART
;
3687 else if (strcmp(hookname
, "start-host") == 0)
3688 which
= LXCHOOK_START_HOST
;
3689 else if (strcmp(hookname
, "pre-mount") == 0)
3690 which
= LXCHOOK_PREMOUNT
;
3691 else if (strcmp(hookname
, "mount") == 0)
3692 which
= LXCHOOK_MOUNT
;
3693 else if (strcmp(hookname
, "autodev") == 0)
3694 which
= LXCHOOK_AUTODEV
;
3695 else if (strcmp(hookname
, "start") == 0)
3696 which
= LXCHOOK_START
;
3697 else if (strcmp(hookname
, "stop") == 0)
3698 which
= LXCHOOK_STOP
;
3699 else if (strcmp(hookname
, "post-stop") == 0)
3700 which
= LXCHOOK_POSTSTOP
;
3701 else if (strcmp(hookname
, "clone") == 0)
3702 which
= LXCHOOK_CLONE
;
3703 else if (strcmp(hookname
, "destroy") == 0)
3704 which
= LXCHOOK_DESTROY
;
3708 lxc_list_for_each (it
, &conf
->hooks
[which
]) {
3710 char *hook
= it
->elem
;
3712 ret
= run_script_argv(name
, conf
->hooks_version
, "lxc", hook
,
3721 int lxc_clear_config_caps(struct lxc_conf
*c
)
3723 struct lxc_list
*it
, *next
;
3725 lxc_list_for_each_safe (it
, &c
->caps
, next
) {
3734 static int lxc_free_idmap(struct lxc_list
*id_map
)
3736 struct lxc_list
*it
, *next
;
3738 lxc_list_for_each_safe (it
, id_map
, next
) {
3747 int lxc_clear_idmaps(struct lxc_conf
*c
)
3749 return lxc_free_idmap(&c
->id_map
);
3752 int lxc_clear_config_keepcaps(struct lxc_conf
*c
)
3754 struct lxc_list
*it
, *next
;
3756 lxc_list_for_each_safe (it
, &c
->keepcaps
, next
) {
3765 int lxc_clear_namespace(struct lxc_conf
*c
)
3768 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
3769 free(c
->ns_share
[i
]);
3770 c
->ns_share
[i
] = NULL
;
3775 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
, int version
)
3777 char *global_token
, *namespaced_token
;
3778 size_t namespaced_token_len
;
3779 struct lxc_list
*it
, *next
, *list
;
3780 const char *k
= key
;
3783 if (version
== CGROUP2_SUPER_MAGIC
) {
3784 global_token
= "lxc.cgroup2";
3785 namespaced_token
= "lxc.cgroup2.";
3786 namespaced_token_len
= STRLITERALLEN("lxc.cgroup2.");
3788 } else if (version
== CGROUP_SUPER_MAGIC
) {
3789 global_token
= "lxc.cgroup";
3790 namespaced_token
= "lxc.cgroup.";
3791 namespaced_token_len
= STRLITERALLEN("lxc.cgroup.");
3797 if (strcmp(key
, global_token
) == 0)
3799 else if (strncmp(key
, namespaced_token
, namespaced_token_len
) == 0)
3800 k
+= namespaced_token_len
;
3804 lxc_list_for_each_safe (it
, list
, next
) {
3805 struct lxc_cgroup
*cg
= it
->elem
;
3807 if (!all
&& strcmp(cg
->subsystem
, k
) != 0)
3811 free(cg
->subsystem
);
3820 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
3822 struct lxc_list
*it
, *next
;
3823 const char *k
= NULL
;
3826 if (strcmp(key
, "lxc.limit") == 0 || strcmp(key
, "lxc.prlimit") == 0)
3828 else if (strncmp(key
, "lxc.limit.", STRLITERALLEN("lxc.limit.")) == 0)
3829 k
= key
+ STRLITERALLEN("lxc.limit.");
3830 else if (strncmp(key
, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")) == 0)
3831 k
= key
+ STRLITERALLEN("lxc.prlimit.");
3835 lxc_list_for_each_safe (it
, &c
->limits
, next
) {
3836 struct lxc_limit
*lim
= it
->elem
;
3838 if (!all
&& strcmp(lim
->resource
, k
) != 0)
3842 free(lim
->resource
);
3850 int lxc_clear_sysctls(struct lxc_conf
*c
, const char *key
)
3852 struct lxc_list
*it
, *next
;
3853 const char *k
= NULL
;
3856 if (strcmp(key
, "lxc.sysctl") == 0)
3858 else if (strncmp(key
, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")) == 0)
3859 k
= key
+ STRLITERALLEN("lxc.sysctl.");
3863 lxc_list_for_each_safe (it
, &c
->sysctls
, next
) {
3864 struct lxc_sysctl
*elem
= it
->elem
;
3866 if (!all
&& strcmp(elem
->key
, k
) != 0)
3879 int lxc_clear_procs(struct lxc_conf
*c
, const char *key
)
3881 struct lxc_list
*it
, *next
;
3882 const char *k
= NULL
;
3885 if (strcmp(key
, "lxc.proc") == 0)
3887 else if (strncmp(key
, "lxc.proc.", STRLITERALLEN("lxc.proc.")) == 0)
3888 k
= key
+ STRLITERALLEN("lxc.proc.");
3892 lxc_list_for_each_safe (it
, &c
->procs
, next
) {
3893 struct lxc_proc
*proc
= it
->elem
;
3895 if (!all
&& strcmp(proc
->filename
, k
) != 0)
3899 free(proc
->filename
);
3908 int lxc_clear_groups(struct lxc_conf
*c
)
3910 struct lxc_list
*it
, *next
;
3912 lxc_list_for_each_safe (it
, &c
->groups
, next
) {
3921 int lxc_clear_environment(struct lxc_conf
*c
)
3923 struct lxc_list
*it
, *next
;
3925 lxc_list_for_each_safe (it
, &c
->environment
, next
) {
3934 int lxc_clear_mount_entries(struct lxc_conf
*c
)
3936 struct lxc_list
*it
, *next
;
3938 lxc_list_for_each_safe (it
, &c
->mount_list
, next
) {
3947 int lxc_clear_automounts(struct lxc_conf
*c
)
3953 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
3956 struct lxc_list
*it
, *next
;
3957 const char *k
= NULL
;
3958 bool all
= false, done
= false;
3960 if (strcmp(key
, "lxc.hook") == 0)
3962 else if (strncmp(key
, "lxc.hook.", STRLITERALLEN("lxc.hook.")) == 0)
3963 k
= key
+ STRLITERALLEN("lxc.hook.");
3967 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++) {
3968 if (all
|| strcmp(k
, lxchook_names
[i
]) == 0) {
3969 lxc_list_for_each_safe (it
, &c
->hooks
[i
], next
) {
3980 ERROR("Invalid hook key: %s", key
);
3987 static inline void lxc_clear_aliens(struct lxc_conf
*conf
)
3989 struct lxc_list
*it
, *next
;
3991 lxc_list_for_each_safe (it
, &conf
->aliens
, next
) {
3998 void lxc_clear_includes(struct lxc_conf
*conf
)
4000 struct lxc_list
*it
, *next
;
4002 lxc_list_for_each_safe (it
, &conf
->includes
, next
) {
4009 int lxc_clear_apparmor_raw(struct lxc_conf
*c
)
4011 struct lxc_list
*it
, *next
;
4013 lxc_list_for_each_safe (it
, &c
->lsm_aa_raw
, next
) {
4022 void lxc_conf_free(struct lxc_conf
*conf
)
4027 if (current_config
== conf
)
4028 current_config
= NULL
;
4029 lxc_terminal_conf_free(&conf
->console
);
4030 free(conf
->rootfs
.mount
);
4031 free(conf
->rootfs
.bdev_type
);
4032 free(conf
->rootfs
.options
);
4033 free(conf
->rootfs
.path
);
4034 free(conf
->logfile
);
4035 if (conf
->logfd
!= -1)
4037 free(conf
->utsname
);
4038 free(conf
->ttys
.dir
);
4039 free(conf
->ttys
.tty_names
);
4042 free(conf
->execute_cmd
);
4043 free(conf
->init_cmd
);
4044 free(conf
->init_cwd
);
4045 free(conf
->unexpanded_config
);
4047 lxc_free_networks(&conf
->network
);
4048 free(conf
->lsm_aa_profile
);
4049 free(conf
->lsm_aa_profile_computed
);
4050 free(conf
->lsm_se_context
);
4051 lxc_seccomp_free(conf
);
4052 lxc_clear_config_caps(conf
);
4053 lxc_clear_config_keepcaps(conf
);
4054 lxc_clear_cgroups(conf
, "lxc.cgroup", CGROUP_SUPER_MAGIC
);
4055 lxc_clear_cgroups(conf
, "lxc.cgroup2", CGROUP2_SUPER_MAGIC
);
4056 lxc_clear_hooks(conf
, "lxc.hook");
4057 lxc_clear_mount_entries(conf
);
4058 lxc_clear_idmaps(conf
);
4059 lxc_clear_groups(conf
);
4060 lxc_clear_includes(conf
);
4061 lxc_clear_aliens(conf
);
4062 lxc_clear_environment(conf
);
4063 lxc_clear_limits(conf
, "lxc.prlimit");
4064 lxc_clear_sysctls(conf
, "lxc.sysctl");
4065 lxc_clear_procs(conf
, "lxc.proc");
4066 lxc_clear_apparmor_raw(conf
);
4067 lxc_clear_namespace(conf
);
4068 free(conf
->cgroup_meta
.dir
);
4069 free(conf
->cgroup_meta
.controllers
);
4070 free(conf
->shmount
.path_host
);
4071 free(conf
->shmount
.path_cont
);
4075 struct userns_fn_data
{
4077 const char *fn_name
;
4082 static int run_userns_fn(void *data
)
4086 struct userns_fn_data
*d
= data
;
4088 /* Close write end of the pipe. */
4091 /* Wait for parent to finish establishing a new mapping in the user
4092 * namespace we are executing in.
4094 ret
= lxc_read_nointr(d
->p
[0], &c
, 1);
4095 /* Close read end of the pipe. */
4101 TRACE("Calling function \"%s\"", d
->fn_name
);
4103 /* Call function to run. */
4104 return d
->fn(d
->arg
);
4107 static struct id_map
*mapped_nsid_add(struct lxc_conf
*conf
, unsigned id
,
4110 const struct id_map
*map
;
4111 struct id_map
*retmap
;
4113 map
= find_mapped_nsid_entry(conf
, id
, idtype
);
4117 retmap
= malloc(sizeof(*retmap
));
4121 memcpy(retmap
, map
, sizeof(*retmap
));
4125 static struct id_map
*find_mapped_hostid_entry(struct lxc_conf
*conf
,
4126 unsigned id
, enum idtype idtype
)
4129 struct lxc_list
*it
;
4130 struct id_map
*retmap
= NULL
;
4132 lxc_list_for_each (it
, &conf
->id_map
) {
4134 if (map
->idtype
!= idtype
)
4137 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
4146 /* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
4147 * existing one or establish a new one.
4149 static struct id_map
*mapped_hostid_add(struct lxc_conf
*conf
, uid_t id
,
4153 struct id_map
*entry
= NULL
, *tmp
= NULL
;
4155 entry
= malloc(sizeof(*entry
));
4159 /* Reuse existing mapping. */
4160 tmp
= find_mapped_hostid_entry(conf
, id
, type
);
4162 return memcpy(entry
, tmp
, sizeof(*entry
));
4164 /* Find new mapping. */
4165 hostid_mapped
= find_unmapped_nsid(conf
, type
);
4166 if (hostid_mapped
< 0) {
4167 DEBUG("Failed to find free mapping for id %d", id
);
4172 entry
->idtype
= type
;
4173 entry
->nsid
= hostid_mapped
;
4174 entry
->hostid
= (unsigned long)id
;
4180 struct lxc_list
*get_minimal_idmap(struct lxc_conf
*conf
)
4182 __do_free
struct id_map
*container_root_uid
= NULL
,
4183 *container_root_gid
= NULL
,
4184 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4185 __do_free
struct lxc_list
*idmap
= NULL
;
4187 uid_t nsuid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
4188 gid_t nsgid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
4189 struct lxc_list
*tmplist
= NULL
;
4191 /* Find container root mappings. */
4192 container_root_uid
= mapped_nsid_add(conf
, nsuid
, ID_TYPE_UID
);
4193 if (!container_root_uid
) {
4194 DEBUG("Failed to find mapping for namespace uid %d", 0);
4198 if (euid
>= container_root_uid
->hostid
&&
4199 euid
< (container_root_uid
->hostid
+ container_root_uid
->range
))
4200 host_uid_map
= container_root_uid
;
4202 container_root_gid
= mapped_nsid_add(conf
, nsgid
, ID_TYPE_GID
);
4203 if (!container_root_gid
) {
4204 DEBUG("Failed to find mapping for namespace gid %d", 0);
4208 if (egid
>= container_root_gid
->hostid
&&
4209 egid
< (container_root_gid
->hostid
+ container_root_gid
->range
))
4210 host_gid_map
= container_root_gid
;
4212 /* Check whether the {g,u}id of the user has a mapping. */
4214 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4215 if (!host_uid_map
) {
4216 DEBUG("Failed to find mapping for uid %d", euid
);
4221 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4222 if (!host_gid_map
) {
4223 DEBUG("Failed to find mapping for gid %d", egid
);
4227 /* Allocate new {g,u}id map list. */
4228 idmap
= malloc(sizeof(*idmap
));
4231 lxc_list_init(idmap
);
4233 /* Add container root to the map. */
4234 tmplist
= malloc(sizeof(*tmplist
));
4237 lxc_list_add_elem(tmplist
, container_root_uid
);
4238 lxc_list_add_tail(idmap
, tmplist
);
4240 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4241 /* idmap will now keep track of that memory. */
4242 move_ptr(container_root_uid
);
4244 /* Add container root to the map. */
4245 tmplist
= malloc(sizeof(*tmplist
));
4248 lxc_list_add_elem(tmplist
, host_uid_map
);
4249 lxc_list_add_tail(idmap
, tmplist
);
4251 /* idmap will now keep track of that memory. */
4252 move_ptr(container_root_uid
);
4253 /* idmap will now keep track of that memory. */
4254 move_ptr(host_uid_map
);
4256 tmplist
= malloc(sizeof(*tmplist
));
4259 lxc_list_add_elem(tmplist
, container_root_gid
);
4260 lxc_list_add_tail(idmap
, tmplist
);
4262 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4263 /* idmap will now keep track of that memory. */
4264 move_ptr(container_root_gid
);
4266 tmplist
= malloc(sizeof(*tmplist
));
4269 lxc_list_add_elem(tmplist
, host_gid_map
);
4270 lxc_list_add_tail(idmap
, tmplist
);
4272 /* idmap will now keep track of that memory. */
4273 move_ptr(container_root_gid
);
4274 /* idmap will now keep track of that memory. */
4275 move_ptr(host_gid_map
);
4277 TRACE("Allocated minimal idmapping");
4278 return move_ptr(idmap
);
4281 /* Run a function in a new user namespace.
4282 * The caller's euid/egid will be mapped if it is not already.
4283 * Afaict, userns_exec_1() is only used to operate based on privileges for the
4284 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
4285 * This means we require only to establish a mapping from:
4286 * - the container root {g,u}id as seen from the host > user's host {g,u}id
4287 * - the container root -> some sub{g,u}id
4288 * The former we add, if the user did not specify a mapping. The latter we
4289 * retrieve from the container's configured {g,u}id mappings as it must have been
4290 * there to start the container in the first place.
4292 int userns_exec_1(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4293 const char *fn_name
)
4297 struct userns_fn_data d
;
4298 struct lxc_list
*idmap
;
4299 int ret
= -1, status
= -1;
4305 idmap
= get_minimal_idmap(conf
);
4309 ret
= pipe2(p
, O_CLOEXEC
);
4311 SYSERROR("Failed to create pipe");
4315 d
.fn_name
= fn_name
;
4320 /* Clone child in new user namespace. */
4321 pid
= lxc_raw_clone_cb(run_userns_fn
, &d
, CLONE_NEWUSER
);
4323 ERROR("Failed to clone process in new user namespace");
4330 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4331 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4333 struct lxc_list
*it
;
4335 lxc_list_for_each (it
, idmap
) {
4337 TRACE("Establishing %cid mapping for \"%d\" in new "
4338 "user namespace: nsuid %lu - hostid %lu - range "
4340 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4341 map
->nsid
, map
->hostid
, map
->range
);
4345 /* Set up {g,u}id mapping for user namespace of child process. */
4346 ret
= lxc_map_ids(idmap
, pid
);
4348 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
4352 /* Tell child to proceed. */
4353 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4354 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4363 /* Wait for child to finish. */
4365 status
= wait_for_pid(pid
);
4373 int userns_exec_full(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4374 const char *fn_name
)
4380 struct lxc_list
*cur
;
4381 struct userns_fn_data d
;
4384 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
4385 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
4386 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4391 ret
= pipe2(p
, O_CLOEXEC
);
4393 SYSERROR("opening pipe");
4397 d
.fn_name
= fn_name
;
4402 /* Clone child in new user namespace. */
4403 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
);
4405 ERROR("Failed to clone process in new user namespace");
4415 /* Allocate new {g,u}id map list. */
4416 idmap
= malloc(sizeof(*idmap
));
4419 lxc_list_init(idmap
);
4421 /* Find container root. */
4422 lxc_list_for_each (cur
, &conf
->id_map
) {
4423 struct id_map
*tmpmap
;
4425 tmplist
= malloc(sizeof(*tmplist
));
4429 tmpmap
= malloc(sizeof(*tmpmap
));
4435 memset(tmpmap
, 0, sizeof(*tmpmap
));
4436 memcpy(tmpmap
, cur
->elem
, sizeof(*tmpmap
));
4437 tmplist
->elem
= tmpmap
;
4439 lxc_list_add_tail(idmap
, tmplist
);
4443 if (map
->idtype
== ID_TYPE_UID
)
4444 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
4447 if (map
->idtype
== ID_TYPE_GID
)
4448 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
4454 if (map
->idtype
== ID_TYPE_UID
)
4455 if (container_root_uid
== NULL
)
4456 container_root_uid
= map
;
4458 if (map
->idtype
== ID_TYPE_GID
)
4459 if (container_root_gid
== NULL
)
4460 container_root_gid
= map
;
4463 if (!container_root_uid
|| !container_root_gid
) {
4464 ERROR("No mapping for container root found");
4468 /* Check whether the {g,u}id of the user has a mapping. */
4470 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4472 host_uid_map
= container_root_uid
;
4475 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4477 host_gid_map
= container_root_gid
;
4479 if (!host_uid_map
) {
4480 DEBUG("Failed to find mapping for uid %d", euid
);
4484 if (!host_gid_map
) {
4485 DEBUG("Failed to find mapping for gid %d", egid
);
4489 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4490 /* Add container root to the map. */
4491 tmplist
= malloc(sizeof(*tmplist
));
4494 lxc_list_add_elem(tmplist
, host_uid_map
);
4495 lxc_list_add_tail(idmap
, tmplist
);
4497 /* idmap will now keep track of that memory. */
4498 host_uid_map
= NULL
;
4500 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4501 tmplist
= malloc(sizeof(*tmplist
));
4504 lxc_list_add_elem(tmplist
, host_gid_map
);
4505 lxc_list_add_tail(idmap
, tmplist
);
4507 /* idmap will now keep track of that memory. */
4508 host_gid_map
= NULL
;
4510 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4511 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4512 lxc_list_for_each (cur
, idmap
) {
4514 TRACE("establishing %cid mapping for \"%d\" in new "
4515 "user namespace: nsuid %lu - hostid %lu - range "
4517 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4518 map
->nsid
, map
->hostid
, map
->range
);
4522 /* Set up {g,u}id mapping for user namespace of child process. */
4523 ret
= lxc_map_ids(idmap
, pid
);
4525 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid
);
4529 /* Tell child to proceed. */
4530 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4531 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4540 /* Wait for child to finish. */
4542 ret
= wait_for_pid(pid
);
4545 lxc_free_idmap(idmap
);
4549 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
4551 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
4557 /* not thread-safe, do not use from api without first forking */
4558 static char *getuname(void)
4560 __do_free
char *buf
= NULL
;
4561 struct passwd pwent
;
4562 struct passwd
*pwentp
= NULL
;
4566 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
4570 buf
= malloc(bufsize
);
4574 ret
= getpwuid_r(geteuid(), &pwent
, buf
, bufsize
, &pwentp
);
4577 WARN("Could not find matched password record.");
4579 ERROR("Failed to get password record - %u", geteuid());
4583 return strdup(pwent
.pw_name
);
4586 /* not thread-safe, do not use from api without first forking */
4587 static char *getgname(void)
4589 __do_free
char *buf
= NULL
;
4591 struct group
*grentp
= NULL
;
4595 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
4599 buf
= malloc(bufsize
);
4603 ret
= getgrgid_r(getegid(), &grent
, buf
, bufsize
, &grentp
);
4606 WARN("Could not find matched group record");
4608 ERROR("Failed to get group record - %u", getegid());
4612 return strdup(grent
.gr_name
);
4615 /* not thread-safe, do not use from api without first forking */
4616 void suggest_default_idmap(void)
4618 __do_free
char *gname
= NULL
, *line
= NULL
, *uname
= NULL
;
4619 __do_fclose
FILE *subuid_f
= NULL
, *subgid_f
= NULL
;
4620 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
4631 subuid_f
= fopen(subuidfile
, "r");
4633 ERROR("Your system is not configured with subuids");
4637 while (getline(&line
, &len
, subuid_f
) != -1) {
4639 size_t no_newline
= 0;
4641 p
= strchr(line
, ':');
4649 if (strcmp(line
, uname
))
4652 p2
= strchr(p
, ':');
4659 no_newline
= strcspn(p2
, "\n");
4660 p2
[no_newline
] = '\0';
4662 if (lxc_safe_uint(p
, &uid
) < 0)
4663 WARN("Could not parse UID");
4664 if (lxc_safe_uint(p2
, &urange
) < 0)
4665 WARN("Could not parse UID range");
4668 subgid_f
= fopen(subgidfile
, "r");
4670 ERROR("Your system is not configured with subgids");
4674 while (getline(&line
, &len
, subgid_f
) != -1) {
4676 size_t no_newline
= 0;
4678 p
= strchr(line
, ':');
4686 if (strcmp(line
, uname
))
4689 p2
= strchr(p
, ':');
4696 no_newline
= strcspn(p2
, "\n");
4697 p2
[no_newline
] = '\0';
4699 if (lxc_safe_uint(p
, &gid
) < 0)
4700 WARN("Could not parse GID");
4701 if (lxc_safe_uint(p2
, &grange
) < 0)
4702 WARN("Could not parse GID range");
4705 if (!urange
|| !grange
) {
4706 ERROR("You do not have subuids or subgids allocated");
4707 ERROR("Unprivileged containers require subuids and subgids");
4711 ERROR("You must either run as root, or define uid mappings");
4712 ERROR("To pass uid mappings to lxc-create, you could create");
4713 ERROR("~/.config/lxc/default.conf:");
4714 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
4715 ERROR("lxc.idmap = u 0 %u %u", uid
, urange
);
4716 ERROR("lxc.idmap = g 0 %u %u", gid
, grange
);
4719 static void free_cgroup_settings(struct lxc_list
*result
)
4721 struct lxc_list
*iterator
, *next
;
4723 lxc_list_for_each_safe (iterator
, result
, next
) {
4724 lxc_list_del(iterator
);
4730 /* Return the list of cgroup_settings sorted according to the following rules
4731 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4733 struct lxc_list
*sort_cgroup_settings(struct lxc_list
*cgroup_settings
)
4735 struct lxc_list
*result
;
4736 struct lxc_cgroup
*cg
= NULL
;
4737 struct lxc_list
*it
= NULL
, *item
= NULL
, *memsw_limit
= NULL
;
4739 result
= malloc(sizeof(*result
));
4742 lxc_list_init(result
);
4744 /* Iterate over the cgroup settings and copy them to the output list. */
4745 lxc_list_for_each (it
, cgroup_settings
) {
4746 item
= malloc(sizeof(*item
));
4748 free_cgroup_settings(result
);
4752 item
->elem
= it
->elem
;
4754 if (strcmp(cg
->subsystem
, "memory.memsw.limit_in_bytes") == 0) {
4755 /* Store the memsw_limit location */
4757 } else if (strcmp(cg
->subsystem
, "memory.limit_in_bytes") == 0 &&
4758 memsw_limit
!= NULL
) {
4759 /* lxc.cgroup.memory.memsw.limit_in_bytes is found
4760 * before lxc.cgroup.memory.limit_in_bytes, swap these
4762 item
->elem
= memsw_limit
->elem
;
4763 memsw_limit
->elem
= it
->elem
;
4765 lxc_list_add_tail(result
, item
);