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
)
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
);
333 SYSERROR("Script exited with error");
335 } else if (WIFEXITED(ret
) && WEXITSTATUS(ret
) != 0) {
336 ERROR("Script exited with status %d", WEXITSTATUS(ret
));
338 } else if (WIFSIGNALED(ret
)) {
339 ERROR("Script terminated by signal %d", WTERMSIG(ret
));
346 int run_script_argv(const char *name
, unsigned int hook_version
,
347 const char *section
, const char *script
,
348 const char *hookname
, char **argv
)
355 if (hook_version
== 0)
356 INFO("Executing script \"%s\" for container \"%s\", config "
357 "section \"%s\"", script
, name
, section
);
359 INFO("Executing script \"%s\" for container \"%s\"", script
, name
);
361 for (i
= 0; argv
&& argv
[i
]; i
++)
362 size
+= strlen(argv
[i
]) + 1;
364 size
+= STRLITERALLEN("exec");
366 size
+= strlen(script
);
372 if (hook_version
== 0) {
373 size
+= strlen(hookname
);
376 size
+= strlen(name
);
379 size
+= strlen(section
);
386 buffer
= malloc(size
);
390 if (hook_version
== 0)
391 buf_pos
= snprintf(buffer
, size
, "exec %s %s %s %s", script
, name
, section
, hookname
);
393 buf_pos
= snprintf(buffer
, size
, "exec %s", script
);
394 if (buf_pos
< 0 || (size_t)buf_pos
>= size
) {
395 ERROR("Failed to create command line for script \"%s\"", script
);
399 if (hook_version
== 1) {
400 ret
= setenv("LXC_HOOK_TYPE", hookname
, 1);
402 SYSERROR("Failed to set environment variable: "
403 "LXC_HOOK_TYPE=%s", hookname
);
406 TRACE("Set environment variable: LXC_HOOK_TYPE=%s", hookname
);
408 ret
= setenv("LXC_HOOK_SECTION", section
, 1);
410 SYSERROR("Failed to set environment variable: "
411 "LXC_HOOK_SECTION=%s", section
);
414 TRACE("Set environment variable: LXC_HOOK_SECTION=%s", section
);
416 if (strcmp(section
, "net") == 0) {
419 if (!argv
|| !argv
[0])
422 ret
= setenv("LXC_NET_TYPE", argv
[0], 1);
424 SYSERROR("Failed to set environment variable: "
425 "LXC_NET_TYPE=%s", argv
[0]);
428 TRACE("Set environment variable: LXC_NET_TYPE=%s", argv
[0]);
430 parent
= argv
[1] ? argv
[1] : "";
432 if (strcmp(argv
[0], "macvlan") == 0) {
433 ret
= setenv("LXC_NET_PARENT", parent
, 1);
435 SYSERROR("Failed to set environment "
436 "variable: LXC_NET_PARENT=%s", parent
);
439 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
440 } else if (strcmp(argv
[0], "phys") == 0) {
441 ret
= setenv("LXC_NET_PARENT", parent
, 1);
443 SYSERROR("Failed to set environment "
444 "variable: LXC_NET_PARENT=%s", parent
);
447 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
448 } else if (strcmp(argv
[0], "veth") == 0) {
449 char *peer
= argv
[2] ? argv
[2] : "";
451 ret
= setenv("LXC_NET_PEER", peer
, 1);
453 SYSERROR("Failed to set environment "
454 "variable: LXC_NET_PEER=%s", peer
);
457 TRACE("Set environment variable: LXC_NET_PEER=%s", peer
);
459 ret
= setenv("LXC_NET_PARENT", parent
, 1);
461 SYSERROR("Failed to set environment "
462 "variable: LXC_NET_PARENT=%s", parent
);
465 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
470 for (i
= 0; argv
&& argv
[i
]; i
++) {
471 size_t len
= size
- buf_pos
;
473 ret
= snprintf(buffer
+ buf_pos
, len
, " %s", argv
[i
]);
474 if (ret
< 0 || (size_t)ret
>= len
) {
475 ERROR("Failed to create command line for script \"%s\"", script
);
481 fret
= run_buffer(buffer
);
488 int run_script(const char *name
, const char *section
, const char *script
, ...)
490 __do_free
char *buffer
= NULL
;
496 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
497 script
, name
, section
);
499 va_start(ap
, script
);
500 while ((p
= va_arg(ap
, char *)))
501 size
+= strlen(p
) + 1;
504 size
+= STRLITERALLEN("exec");
505 size
+= strlen(script
);
506 size
+= strlen(name
);
507 size
+= strlen(section
);
513 buffer
= must_realloc(NULL
, size
);
514 ret
= snprintf(buffer
, size
, "exec %s %s %s", script
, name
, section
);
515 if (ret
< 0 || ret
>= size
)
518 va_start(ap
, script
);
519 while ((p
= va_arg(ap
, char *))) {
520 int len
= size
- ret
;
522 rc
= snprintf(buffer
+ ret
, len
, " %s", p
);
523 if (rc
< 0 || rc
>= len
) {
531 return run_buffer(buffer
);
535 * if rootfs is a directory, then open ${rootfs}/.lxc-keep for writing for
536 * the duration of the container run, to prevent the container from marking
537 * the underlying fs readonly on shutdown. unlink the file immediately so
538 * no name pollution is happens.
539 * don't unlink on NFS to avoid random named stale handles.
540 * return -1 on error.
541 * return -2 if nothing needed to be pinned.
542 * return an open fd (>=0) if we pinned it.
544 int pin_rootfs(const char *rootfs
)
547 char absrootfspin
[PATH_MAX
];
552 if (rootfs
== NULL
|| strlen(rootfs
) == 0)
555 absrootfs
= realpath(rootfs
, NULL
);
559 ret
= stat(absrootfs
, &s
);
565 if (!S_ISDIR(s
.st_mode
)) {
570 ret
= snprintf(absrootfspin
, PATH_MAX
, "%s/.lxc-keep", absrootfs
);
572 if (ret
< 0 || ret
>= PATH_MAX
)
575 fd
= open(absrootfspin
, O_CREAT
| O_RDWR
, S_IWUSR
| S_IRUSR
);
579 ret
= fstatfs (fd
, &sfs
);
583 if (sfs
.f_type
== NFS_SUPER_MAGIC
) {
584 DEBUG("Rootfs on NFS, not unlinking pin file \"%s\"", absrootfspin
);
588 (void)unlink(absrootfspin
);
593 /* If we are asking to remount something, make sure that any NOEXEC etc are
596 unsigned long add_required_remount_flags(const char *s
, const char *d
,
602 unsigned long required_flags
= 0;
610 ret
= statvfs(s
, &sb
);
614 if (flags
& MS_REMOUNT
) {
615 if (sb
.f_flag
& MS_NOSUID
)
616 required_flags
|= MS_NOSUID
;
617 if (sb
.f_flag
& MS_NODEV
)
618 required_flags
|= MS_NODEV
;
619 if (sb
.f_flag
& MS_RDONLY
)
620 required_flags
|= MS_RDONLY
;
621 if (sb
.f_flag
& MS_NOEXEC
)
622 required_flags
|= MS_NOEXEC
;
625 if (sb
.f_flag
& MS_NOATIME
)
626 required_flags
|= MS_NOATIME
;
627 if (sb
.f_flag
& MS_NODIRATIME
)
628 required_flags
|= MS_NODIRATIME
;
629 if (sb
.f_flag
& MS_LAZYTIME
)
630 required_flags
|= MS_LAZYTIME
;
631 if (sb
.f_flag
& MS_RELATIME
)
632 required_flags
|= MS_RELATIME
;
633 if (sb
.f_flag
& MS_STRICTATIME
)
634 required_flags
|= MS_STRICTATIME
;
636 return flags
| required_flags
;
642 static int add_shmount_to_list(struct lxc_conf
*conf
)
644 char new_mount
[PATH_MAX
];
645 /* Offset for the leading '/' since the path_cont
646 * is absolute inside the container.
648 int offset
= 1, ret
= -1;
650 ret
= snprintf(new_mount
, sizeof(new_mount
),
651 "%s %s none bind,create=dir 0 0", conf
->shmount
.path_host
,
652 conf
->shmount
.path_cont
+ offset
);
653 if (ret
< 0 || (size_t)ret
>= sizeof(new_mount
))
656 return add_elem_to_mount_list(new_mount
, conf
);
659 static int lxc_mount_auto_mounts(struct lxc_conf
*conf
, int flags
, struct lxc_handler
*handler
)
666 const char *destination
;
670 } default_mounts
[] = {
671 /* Read-only bind-mounting... In older kernels, doing that
672 * required to do one MS_BIND mount and then
673 * MS_REMOUNT|MS_RDONLY the same one. According to mount(2)
674 * manpage, MS_BIND honors MS_RDONLY from kernel 2.6.26
675 * onwards. However, this apparently does not work on kernel
676 * 3.8. Unfortunately, on that very same kernel, doing the same
677 * trick as above doesn't seem to work either, there one needs
678 * to ALSO specify MS_BIND for the remount, otherwise the
679 * entire fs is remounted read-only or the mount fails because
680 * it's busy... MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for
681 * kernels as low as 2.6.32...
683 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
684 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
685 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys/net", "%r/proc/tty", NULL
, MS_BIND
, NULL
},
686 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys", "%r/proc/sys", NULL
, MS_BIND
, NULL
},
687 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
688 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/tty", "%r/proc/sys/net", NULL
, MS_MOVE
, NULL
},
689 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL
, MS_BIND
, NULL
},
690 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sysrq-trigger", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
691 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_RW
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
692 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RW
, "sysfs", "%r/sys", "sysfs", 0, NULL
},
693 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RO
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
, NULL
},
694 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys", "sysfs", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
695 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/sys", "%r/sys", NULL
, MS_BIND
, NULL
},
696 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, NULL
, "%r/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
697 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys/devices/virtual/net", "sysfs", 0, NULL
},
698 { 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
},
699 { 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
},
700 { 0, 0, NULL
, NULL
, NULL
, 0, NULL
}
703 for (i
= 0; default_mounts
[i
].match_mask
; i
++) {
705 unsigned long mflags
;
706 char *destination
= NULL
;
708 if ((flags
& default_mounts
[i
].match_mask
) != default_mounts
[i
].match_flag
)
711 if (default_mounts
[i
].source
) {
712 /* will act like strdup if %r is not present */
713 source
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].source
);
718 if (!default_mounts
[i
].destination
) {
719 ERROR("BUG: auto mounts destination %d was NULL", i
);
724 /* will act like strdup if %r is not present */
725 destination
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].destination
);
733 mflags
= add_required_remount_flags(source
, destination
,
734 default_mounts
[i
].flags
);
735 r
= safe_mount(source
, destination
, default_mounts
[i
].fstype
,
736 mflags
, default_mounts
[i
].options
,
737 conf
->rootfs
.path
? conf
->rootfs
.mount
: NULL
);
739 if (r
< 0 && errno
== ENOENT
) {
740 INFO("Mount source or target for \"%s\" on \"%s\" does "
741 "not exist. Skipping", source
, destination
);
744 SYSERROR("Failed to mount \"%s\" on \"%s\" with flags %lu", source
, destination
, mflags
);
755 if (flags
& LXC_AUTO_CGROUP_MASK
) {
758 cg_flags
= flags
& (LXC_AUTO_CGROUP_MASK
& ~LXC_AUTO_CGROUP_FORCE
);
759 /* If the type of cgroup mount was not specified, it depends on
760 * the container's capabilities as to what makes sense: if we
761 * have CAP_SYS_ADMIN, the read-only part can be remounted
762 * read-write anyway, so we may as well default to read-write;
763 * then the admin will not be given a false sense of security.
764 * (And if they really want mixed r/o r/w, then they can
765 * explicitly specify :mixed.) OTOH, if the container lacks
766 * CAP_SYS_ADMIN, do only default to :mixed, because then the
767 * container can't remount it read-write.
769 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
|| cg_flags
== LXC_AUTO_CGROUP_FULL_NOSPEC
) {
770 int has_sys_admin
= 0;
772 if (!lxc_list_empty(&conf
->keepcaps
))
773 has_sys_admin
= in_caplist(CAP_SYS_ADMIN
, &conf
->keepcaps
);
775 has_sys_admin
= !in_caplist(CAP_SYS_ADMIN
, &conf
->caps
);
777 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
778 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_RW
: LXC_AUTO_CGROUP_MIXED
;
780 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_FULL_RW
: LXC_AUTO_CGROUP_FULL_MIXED
;
783 if (flags
& LXC_AUTO_CGROUP_FORCE
)
784 cg_flags
|= LXC_AUTO_CGROUP_FORCE
;
786 if (!handler
->cgroup_ops
->mount(handler
->cgroup_ops
,
788 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
790 SYSERROR("Failed to mount \"/sys/fs/cgroup\"");
795 if (flags
& LXC_AUTO_SHMOUNTS_MASK
) {
796 int ret
= add_shmount_to_list(conf
);
798 ERROR("Failed to add shmount entry to container config");
806 static int setup_utsname(struct utsname
*utsname
)
813 ret
= sethostname(utsname
->nodename
, strlen(utsname
->nodename
));
815 SYSERROR("Failed to set the hostname to \"%s\"", utsname
->nodename
);
819 INFO("Set hostname to \"%s\"", utsname
->nodename
);
824 struct dev_symlinks
{
829 static const struct dev_symlinks dev_symlinks
[] = {
830 { "/proc/self/fd", "fd" },
831 { "/proc/self/fd/0", "stdin" },
832 { "/proc/self/fd/1", "stdout" },
833 { "/proc/self/fd/2", "stderr" },
836 static int lxc_setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
842 for (i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
843 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
845 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s",
846 rootfs
->path
? rootfs
->mount
: "", d
->name
);
847 if (ret
< 0 || ret
>= PATH_MAX
)
850 /* Stat the path first. If we don't get an error accept it as
851 * is and don't try to create it
853 ret
= stat(path
, &s
);
857 ret
= symlink(d
->oldpath
, path
);
858 if (ret
&& errno
!= EEXIST
) {
859 if (errno
== EROFS
) {
860 WARN("Failed to create \"%s\". Read-only filesystem", path
);
862 SYSERROR("Failed to create \"%s\"", path
);
871 /* Build a space-separate list of ptys to pass to systemd. */
872 static bool append_ttyname(char **pp
, char *name
)
878 *pp
= malloc(strlen(name
) + strlen("container_ttys=") + 1);
882 sprintf(*pp
, "container_ttys=%s", name
);
886 size
= strlen(*pp
) + strlen(name
) + 2;
887 p
= realloc(*pp
, size
);
892 (void)strlcat(p
, " ", size
);
893 (void)strlcat(p
, name
, size
);
898 static int lxc_setup_ttys(struct lxc_conf
*conf
)
901 const struct lxc_tty_info
*ttys
= &conf
->ttys
;
902 char *ttydir
= ttys
->dir
;
903 char path
[PATH_MAX
], lxcpath
[PATH_MAX
];
905 if (!conf
->rootfs
.path
)
908 for (i
= 0; i
< ttys
->max
; i
++) {
909 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
911 ret
= snprintf(path
, sizeof(path
), "/dev/tty%d", i
+ 1);
912 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
916 /* create dev/lxc/tty%d" */
917 ret
= snprintf(lxcpath
, sizeof(lxcpath
),
918 "/dev/%s/tty%d", ttydir
, i
+ 1);
919 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
922 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
923 if (ret
< 0 && errno
!= EEXIST
) {
924 SYSERROR("Failed to create \"%s\"", lxcpath
);
929 if (ret
< 0 && errno
!= ENOENT
) {
930 SYSERROR("Failed to unlink \"%s\"", path
);
934 ret
= mount(tty
->name
, lxcpath
, "none", MS_BIND
, 0);
936 SYSWARN("Failed to bind mount \"%s\" onto \"%s\"",
940 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
,
943 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/tty%d",
945 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
948 ret
= symlink(lxcpath
, path
);
950 SYSERROR("Failed to create symlink \"%s\" -> \"%s\"",
955 /* If we populated /dev, then we need to create
958 ret
= mknod(path
, S_IFREG
| 0000, 0);
959 if (ret
< 0) /* this isn't fatal, continue */
960 SYSERROR("Failed to create \"%s\"", path
);
962 ret
= mount(tty
->name
, path
, "none", MS_BIND
, 0);
964 SYSERROR("Failed to mount '%s'->'%s'", tty
->name
, path
);
968 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, path
);
971 if (!append_ttyname(&conf
->ttys
.tty_names
, tty
->name
)) {
972 ERROR("Error setting up container_ttys string");
977 INFO("Finished setting up %zu /dev/tty<N> device(s)", ttys
->max
);
981 int lxc_allocate_ttys(struct lxc_conf
*conf
)
985 struct lxc_tty_info
*ttys
= &conf
->ttys
;
987 /* no tty in the configuration */
991 ttys
->tty
= malloc(sizeof(*ttys
->tty
) * ttys
->max
);
995 for (i
= 0; i
< ttys
->max
; i
++) {
996 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
998 tty
->master
= -EBADF
;
1000 ret
= openpty(&tty
->master
, &tty
->slave
, NULL
, NULL
, NULL
);
1002 SYSERROR("Failed to create tty %zu", i
);
1004 lxc_delete_tty(ttys
);
1008 ret
= ttyname_r(tty
->slave
, tty
->name
, sizeof(tty
->name
));
1010 SYSERROR("Failed to retrieve name of tty %zu slave", i
);
1012 lxc_delete_tty(ttys
);
1016 DEBUG("Created tty \"%s\" with master fd %d and slave fd %d",
1017 tty
->name
, tty
->master
, tty
->slave
);
1019 /* Prevent leaking the file descriptors to the container */
1020 ret
= fd_cloexec(tty
->master
, true);
1022 SYSWARN("Failed to set FD_CLOEXEC flag on master fd %d of "
1023 "tty device \"%s\"", tty
->master
, tty
->name
);
1025 ret
= fd_cloexec(tty
->slave
, true);
1027 SYSWARN("Failed to set FD_CLOEXEC flag on slave fd %d of "
1028 "tty device \"%s\"", tty
->slave
, tty
->name
);
1033 INFO("Finished creating %zu tty devices", ttys
->max
);
1037 void lxc_delete_tty(struct lxc_tty_info
*ttys
)
1044 for (i
= 0; i
< ttys
->max
; i
++) {
1045 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1047 if (tty
->master
>= 0) {
1049 tty
->master
= -EBADF
;
1052 if (tty
->slave
>= 0) {
1054 tty
->slave
= -EBADF
;
1062 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
1066 struct lxc_conf
*conf
= handler
->conf
;
1067 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1068 int sock
= handler
->data_sock
[0];
1073 for (i
= 0; i
< ttys
->max
; i
++) {
1075 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1077 ttyfds
[0] = tty
->master
;
1078 ttyfds
[1] = tty
->slave
;
1080 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, 2, NULL
, 0);
1084 TRACE("Sent tty \"%s\" with master fd %d and slave fd %d to "
1085 "parent", tty
->name
, tty
->master
, tty
->slave
);
1089 SYSERROR("Failed to send %zu ttys to parent", ttys
->max
);
1091 TRACE("Sent %zu ttys to parent", ttys
->max
);
1096 static int lxc_create_ttys(struct lxc_handler
*handler
)
1099 struct lxc_conf
*conf
= handler
->conf
;
1101 ret
= lxc_allocate_ttys(conf
);
1103 ERROR("Failed to allocate ttys");
1107 ret
= lxc_send_ttys_to_parent(handler
);
1109 ERROR("Failed to send ttys to parent");
1113 if (!conf
->is_execute
) {
1114 ret
= lxc_setup_ttys(conf
);
1116 ERROR("Failed to setup ttys");
1121 if (conf
->ttys
.tty_names
) {
1122 ret
= setenv("container_ttys", conf
->ttys
.tty_names
, 1);
1124 SYSERROR("Failed to set \"container_ttys=%s\"", conf
->ttys
.tty_names
);
1130 lxc_delete_tty(&conf
->ttys
);
1135 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1136 * error, log it but don't fail yet.
1138 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
,
1139 const char *lxcpath
)
1141 __do_free
char *path
= NULL
;
1146 INFO("Preparing \"/dev\"");
1148 /* $(rootfs->mount) + "/dev/pts" + '\0' */
1149 clen
= (rootfs
->path
? strlen(rootfs
->mount
) : 0) + 9;
1150 path
= must_realloc(NULL
, clen
);
1152 ret
= snprintf(path
, clen
, "%s/dev", rootfs
->path
? rootfs
->mount
: "");
1153 if (ret
< 0 || (size_t)ret
>= clen
)
1156 cur_mask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1157 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1158 if (ret
< 0 && errno
!= EEXIST
) {
1159 SYSERROR("Failed to create \"/dev\" directory");
1164 ret
= safe_mount("none", path
, "tmpfs", 0, "size=500000,mode=755",
1165 rootfs
->path
? rootfs
->mount
: NULL
);
1167 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1170 TRACE("Mounted tmpfs on \"%s\"", path
);
1172 ret
= snprintf(path
, clen
, "%s/dev/pts", rootfs
->path
? rootfs
->mount
: "");
1173 if (ret
< 0 || (size_t)ret
>= clen
) {
1178 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1179 * If not, then create it and exit if that fails...
1181 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1182 if (ret
< 0 && errno
!= EEXIST
) {
1183 SYSERROR("Failed to create directory \"%s\"", path
);
1191 (void)umask(cur_mask
);
1193 INFO("Prepared \"/dev\"");
1197 struct lxc_device_node
{
1204 static const struct lxc_device_node lxc_devices
[] = {
1205 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1206 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1207 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1208 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1209 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1210 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1217 LXC_DEVNODE_PARTIAL
,
1221 static int lxc_fill_autodev(const struct lxc_rootfs
*rootfs
)
1224 char path
[PATH_MAX
];
1226 int use_mknod
= LXC_DEVNODE_MKNOD
;
1228 ret
= snprintf(path
, PATH_MAX
, "%s/dev",
1229 rootfs
->path
? rootfs
->mount
: "");
1230 if (ret
< 0 || ret
>= PATH_MAX
)
1233 /* ignore, just don't try to fill in */
1234 if (!dir_exists(path
))
1237 INFO("Populating \"/dev\"");
1239 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1240 for (i
= 0; i
< sizeof(lxc_devices
) / sizeof(lxc_devices
[0]); i
++) {
1241 char hostpath
[PATH_MAX
];
1242 const struct lxc_device_node
*device
= &lxc_devices
[i
];
1244 ret
= snprintf(path
, PATH_MAX
, "%s/dev/%s",
1245 rootfs
->path
? rootfs
->mount
: "", device
->name
);
1246 if (ret
< 0 || ret
>= PATH_MAX
)
1249 if (use_mknod
>= LXC_DEVNODE_MKNOD
) {
1250 ret
= mknod(path
, device
->mode
, makedev(device
->maj
, device
->min
));
1251 if (ret
== 0 || (ret
< 0 && errno
== EEXIST
)) {
1252 DEBUG("Created device node \"%s\"", path
);
1253 } else if (ret
< 0) {
1254 if (errno
!= EPERM
) {
1255 SYSERROR("Failed to create device node \"%s\"", path
);
1259 use_mknod
= LXC_DEVNODE_BIND
;
1262 /* Device nodes are fully useable. */
1263 if (use_mknod
== LXC_DEVNODE_OPEN
)
1266 if (use_mknod
== LXC_DEVNODE_MKNOD
) {
1268 * - https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=55956b59df336f6738da916dbb520b6e37df9fbd
1269 * - https://lists.linuxfoundation.org/pipermail/containers/2018-June/039176.html
1271 ret
= open(path
, O_RDONLY
| O_CLOEXEC
);
1274 /* Device nodes are fully useable. */
1275 use_mknod
= LXC_DEVNODE_OPEN
;
1279 SYSTRACE("Failed to open \"%s\" device", path
);
1280 /* Device nodes are only partially useable. */
1281 use_mknod
= LXC_DEVNODE_PARTIAL
;
1285 if (use_mknod
!= LXC_DEVNODE_PARTIAL
) {
1286 /* If we are dealing with partially functional device
1287 * nodes the prio mknod() call will have created the
1288 * device node so we can use it as a bind-mount target.
1290 ret
= mknod(path
, S_IFREG
| 0000, 0);
1291 if (ret
< 0 && errno
!= EEXIST
) {
1292 SYSERROR("Failed to create file \"%s\"", path
);
1297 /* Fallback to bind-mounting the device from the host. */
1298 ret
= snprintf(hostpath
, PATH_MAX
, "/dev/%s", device
->name
);
1299 if (ret
< 0 || ret
>= PATH_MAX
)
1302 ret
= safe_mount(hostpath
, path
, 0, MS_BIND
, NULL
,
1303 rootfs
->path
? rootfs
->mount
: NULL
);
1305 SYSERROR("Failed to bind mount host device node \"%s\" "
1306 "onto \"%s\"", hostpath
, path
);
1309 DEBUG("Bind mounted host device node \"%s\" onto \"%s\"",
1314 INFO("Populated \"/dev\"");
1318 static int lxc_mount_rootfs(struct lxc_conf
*conf
)
1321 struct lxc_storage
*bdev
;
1322 const struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
1324 if (!rootfs
->path
) {
1325 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
1327 SYSERROR("Failed to remount \"/\" MS_REC | MS_SLAVE");
1334 ret
= access(rootfs
->mount
, F_OK
);
1336 SYSERROR("Failed to access to \"%s\". Check it is present",
1341 bdev
= storage_init(conf
);
1343 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1344 rootfs
->path
, rootfs
->mount
,
1345 rootfs
->options
? rootfs
->options
: "(null)");
1349 ret
= bdev
->ops
->mount(bdev
);
1352 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1353 rootfs
->path
, rootfs
->mount
,
1354 rootfs
->options
? rootfs
->options
: "(null)");
1358 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
1359 rootfs
->path
, rootfs
->mount
,
1360 rootfs
->options
? rootfs
->options
: "(null)");
1365 int lxc_chroot(const struct lxc_rootfs
*rootfs
)
1369 char buf
[LXC_LINELEN
];
1372 char *root
= rootfs
->mount
;
1374 nroot
= realpath(root
, NULL
);
1376 SYSERROR("Failed to resolve \"%s\"", root
);
1386 /* We could use here MS_MOVE, but in userns this mount is locked and
1389 ret
= mount(nroot
, "/", NULL
, MS_REC
| MS_BIND
, NULL
);
1391 SYSERROR("Failed to mount \"%s\" onto \"/\" as MS_REC | MS_BIND", nroot
);
1397 ret
= mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
);
1399 SYSERROR("Failed to remount \"/\"");
1403 /* The following code cleans up inherited mounts which are not required
1406 * The mountinfo file shows not all mounts, if a few points have been
1407 * unmounted between read operations from the mountinfo. So we need to
1408 * read mountinfo a few times.
1410 * This loop can be skipped if a container uses userns, because all
1411 * inherited mounts are locked and we should live with all this trash.
1416 f
= fopen("./proc/self/mountinfo", "r");
1418 SYSERROR("Failed to open \"/proc/self/mountinfo\"");
1422 while (fgets(buf
, LXC_LINELEN
, f
)) {
1423 for (p
= buf
, i
=0; p
&& i
< 4; i
++)
1424 p
= strchr(p
+1, ' ');
1429 p2
= strchr(p
+1, ' ');
1436 if (strcmp(p
+ 1, "/") == 0)
1439 if (strcmp(p
+ 1, "/proc") == 0)
1442 ret
= umount2(p
, MNT_DETACH
);
1453 /* This also can be skipped if a container uses userns. */
1454 (void)umount2("./proc", MNT_DETACH
);
1456 /* It is weird, but chdir("..") moves us in a new root */
1459 SYSERROR("Failed to chdir(\"..\")");
1465 SYSERROR("Failed to chroot(\".\")");
1472 /* (The following explanation is copied verbatim from the kernel.)
1474 * pivot_root Semantics:
1475 * Moves the root file system of the current process to the directory put_old,
1476 * makes new_root as the new root file system of the current process, and sets
1477 * root/cwd of all processes which had them on the current root to new_root.
1480 * The new_root and put_old must be directories, and must not be on the
1481 * same file system as the current process root. The put_old must be
1482 * underneath new_root, i.e. adding a non-zero number of /.. to the string
1483 * pointed to by put_old must yield the same directory as new_root. No other
1484 * file system may be mounted on put_old. After all, new_root is a mountpoint.
1486 * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
1487 * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
1488 * in this situation.
1491 * - we don't move root/cwd if they are not at the root (reason: if something
1492 * cared enough to change them, it's probably wrong to force them elsewhere)
1493 * - it's okay to pick a root that isn't the root of a file system, e.g.
1494 * /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
1495 * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
1498 static int lxc_pivot_root(const char *rootfs
)
1501 int newroot
= -1, ret
= -1;
1503 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1505 SYSERROR("Failed to open old root directory");
1509 newroot
= open(rootfs
, O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1511 SYSERROR("Failed to open new root directory");
1515 /* change into new root fs */
1516 ret
= fchdir(newroot
);
1519 SYSERROR("Failed to change to new rootfs \"%s\"", rootfs
);
1523 /* pivot_root into our new root fs */
1524 ret
= pivot_root(".", ".");
1527 SYSERROR("Failed to pivot_root()");
1531 /* At this point the old-root is mounted on top of our new-root. To
1532 * unmounted it we must not be chdir'd into it, so escape back to
1535 ret
= fchdir(oldroot
);
1538 SYSERROR("Failed to enter old root directory");
1542 /* Make oldroot rslave to make sure our umounts don't propagate to the
1545 ret
= mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
);
1548 SYSERROR("Failed to make oldroot rslave");
1552 ret
= umount2(".", MNT_DETACH
);
1555 SYSERROR("Failed to detach old root directory");
1559 ret
= fchdir(newroot
);
1562 SYSERROR("Failed to re-enter new root directory");
1568 TRACE("pivot_root(\"%s\") successful", rootfs
);
1579 static int lxc_setup_rootfs_switch_root(const struct lxc_rootfs
*rootfs
)
1581 if (!rootfs
->path
) {
1582 DEBUG("Container does not have a rootfs");
1586 if (detect_ramfs_rootfs())
1587 return lxc_chroot(rootfs
);
1589 return lxc_pivot_root(rootfs
->mount
);
1592 static const struct id_map
*find_mapped_nsid_entry(struct lxc_conf
*conf
,
1596 struct lxc_list
*it
;
1598 struct id_map
*retmap
= NULL
;
1600 /* Shortcut for container's root mappings. */
1602 if (idtype
== ID_TYPE_UID
)
1603 return conf
->root_nsuid_map
;
1605 if (idtype
== ID_TYPE_GID
)
1606 return conf
->root_nsgid_map
;
1609 lxc_list_for_each(it
, &conf
->id_map
) {
1611 if (map
->idtype
!= idtype
)
1614 if (id
>= map
->nsid
&& id
< map
->nsid
+ map
->range
) {
1623 static int lxc_setup_devpts(struct lxc_conf
*conf
)
1627 char devpts_mntopts
[256];
1628 char *mntopt_sets
[5];
1629 char default_devpts_mntopts
[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
1631 if (conf
->pty_max
<= 0) {
1632 DEBUG("No new devpts instance will be mounted since no pts "
1633 "devices are requested");
1637 ret
= snprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%zu",
1638 default_devpts_mntopts
, conf
->pty_max
);
1639 if (ret
< 0 || (size_t)ret
>= sizeof(devpts_mntopts
))
1642 (void)umount2("/dev/pts", MNT_DETACH
);
1644 /* Create mountpoint for devpts instance. */
1645 ret
= mkdir("/dev/pts", 0755);
1646 if (ret
< 0 && errno
!= EEXIST
) {
1647 SYSERROR("Failed to create \"/dev/pts\" directory");
1652 mntopt_sets
[0] = devpts_mntopts
;
1654 /* !gid=5 && max= */
1655 mntopt_sets
[1] = devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1657 /* gid=5 && !max= */
1658 mntopt_sets
[2] = default_devpts_mntopts
;
1660 /* !gid=5 && !max= */
1661 mntopt_sets
[3] = default_devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1664 mntopt_sets
[4] = NULL
;
1666 for (ret
= -1, opts
= mntopt_sets
; opts
&& *opts
; opts
++) {
1667 /* mount new devpts instance */
1668 ret
= mount("devpts", "/dev/pts", "devpts", MS_NOSUID
| MS_NOEXEC
, *opts
);
1674 SYSERROR("Failed to mount new devpts instance");
1677 DEBUG("Mount new devpts instance with options \"%s\"", *opts
);
1679 /* Remove any pre-existing /dev/ptmx file. */
1680 ret
= remove("/dev/ptmx");
1682 if (errno
!= ENOENT
) {
1683 SYSERROR("Failed to remove existing \"/dev/ptmx\" file");
1687 DEBUG("Removed existing \"/dev/ptmx\" file");
1690 /* Create dummy /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1691 ret
= mknod("/dev/ptmx", S_IFREG
| 0000, 0);
1692 if (ret
< 0 && errno
!= EEXIST
) {
1693 SYSERROR("Failed to create dummy \"/dev/ptmx\" file as bind mount target");
1696 DEBUG("Created dummy \"/dev/ptmx\" file as bind mount target");
1698 /* Fallback option: create symlink /dev/ptmx -> /dev/pts/ptmx */
1699 ret
= mount("/dev/pts/ptmx", "/dev/ptmx", NULL
, MS_BIND
, NULL
);
1701 DEBUG("Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1704 /* Fallthrough and try to create a symlink. */
1705 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1708 /* Remove the dummy /dev/ptmx file we created above. */
1709 ret
= remove("/dev/ptmx");
1711 SYSERROR("Failed to remove existing \"/dev/ptmx\"");
1715 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1716 ret
= symlink("/dev/pts/ptmx", "/dev/ptmx");
1718 SYSERROR("Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1721 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1726 static int setup_personality(int persona
)
1730 #if HAVE_SYS_PERSONALITY_H
1734 ret
= personality(persona
);
1736 SYSERROR("Failed to set personality to \"0x%x\"", persona
);
1740 INFO("Set personality to \"0x%x\"", persona
);
1746 static int lxc_setup_dev_console(const struct lxc_rootfs
*rootfs
,
1747 const struct lxc_terminal
*console
)
1750 char path
[PATH_MAX
];
1751 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1753 if (console
->path
&& !strcmp(console
->path
, "none"))
1756 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1757 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1760 /* When we are asked to setup a console we remove any previous
1761 * /dev/console bind-mounts.
1763 if (file_exists(path
)) {
1764 ret
= lxc_unstack_mountpoint(path
, false);
1766 SYSERROR("Failed to unmount \"%s\"", path
);
1769 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1773 /* For unprivileged containers autodev or automounts will already have
1774 * taken care of creating /dev/console.
1776 ret
= mknod(path
, S_IFREG
| 0000, 0);
1777 if (ret
< 0 && errno
!= EEXIST
) {
1778 SYSERROR("Failed to create console");
1782 ret
= fchmod(console
->slave
, S_IXUSR
| S_IXGRP
);
1784 SYSERROR("Failed to set mode \"0%o\" to \"%s\"",
1785 S_IXUSR
| S_IXGRP
, console
->name
);
1789 ret
= safe_mount(console
->name
, path
, "none", MS_BIND
, 0, rootfs_path
);
1791 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, path
);
1795 DEBUG("Mounted pts device \"%s\" onto \"%s\"", console
->name
, path
);
1799 static int lxc_setup_ttydir_console(const struct lxc_rootfs
*rootfs
,
1800 const struct lxc_terminal
*console
,
1804 char path
[PATH_MAX
], lxcpath
[PATH_MAX
];
1805 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1807 if (console
->path
&& !strcmp(console
->path
, "none"))
1810 /* create rootfs/dev/<ttydir> directory */
1811 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs_path
, ttydir
);
1812 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1815 ret
= mkdir(path
, 0755);
1816 if (ret
&& errno
!= EEXIST
) {
1817 SYSERROR("Failed to create \"%s\"", path
);
1820 DEBUG("Created directory for console and tty devices at \"%s\"", path
);
1822 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/dev/%s/console", rootfs_path
, ttydir
);
1823 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1826 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
1827 if (ret
< 0 && errno
!= EEXIST
) {
1828 SYSERROR("Failed to create \"%s\"", lxcpath
);
1832 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1833 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1836 if (file_exists(path
)) {
1837 ret
= lxc_unstack_mountpoint(path
, false);
1839 SYSERROR("Failed to unmount \"%s\"", path
);
1842 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1846 ret
= mknod(path
, S_IFREG
| 0000, 0);
1847 if (ret
< 0 && errno
!= EEXIST
) {
1848 SYSERROR("Failed to create console");
1852 ret
= fchmod(console
->slave
, S_IXUSR
| S_IXGRP
);
1854 SYSERROR("Failed to set mode \"0%o\" to \"%s\"",
1855 S_IXUSR
| S_IXGRP
, console
->name
);
1859 /* bind mount console->name to '/dev/<ttydir>/console' */
1860 ret
= safe_mount(console
->name
, lxcpath
, "none", MS_BIND
, 0, rootfs_path
);
1862 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1865 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1867 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
1868 ret
= safe_mount(lxcpath
, path
, "none", MS_BIND
, 0, rootfs_path
);
1870 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1873 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1875 DEBUG("Console has been setup under \"%s\" and mounted to \"%s\"", lxcpath
, path
);
1879 static int lxc_setup_console(const struct lxc_rootfs
*rootfs
,
1880 const struct lxc_terminal
*console
, char *ttydir
)
1884 return lxc_setup_dev_console(rootfs
, console
);
1886 return lxc_setup_ttydir_console(rootfs
, console
, ttydir
);
1889 static void parse_mntopt(char *opt
, unsigned long *flags
, char **data
, size_t size
)
1891 struct mount_opt
*mo
;
1893 /* If opt is found in mount_opt, set or clear flags.
1894 * Otherwise append it to data. */
1896 for (mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
1897 if (strncmp(opt
, mo
->name
, strlen(mo
->name
)) == 0) {
1899 *flags
&= ~mo
->flag
;
1907 (void)strlcat(*data
, ",", size
);
1909 (void)strlcat(*data
, opt
, size
);
1912 int parse_mntopts(const char *mntopts
, unsigned long *mntflags
, char **mntdata
)
1923 s
= strdup(mntopts
);
1927 size
= strlen(s
) + 1;
1928 data
= malloc(size
);
1935 lxc_iterate_parts(p
, s
, ",")
1936 parse_mntopt(p
, mntflags
, &data
, size
);
1947 static void parse_propagationopt(char *opt
, unsigned long *flags
)
1949 struct mount_opt
*mo
;
1951 /* If opt is found in propagation_opt, set or clear flags. */
1952 for (mo
= &propagation_opt
[0]; mo
->name
!= NULL
; mo
++) {
1953 if (strncmp(opt
, mo
->name
, strlen(mo
->name
)) != 0)
1957 *flags
&= ~mo
->flag
;
1965 int parse_propagationopts(const char *mntopts
, unsigned long *pflags
)
1972 s
= strdup(mntopts
);
1974 SYSERROR("Failed to allocate memory");
1979 lxc_iterate_parts(p
, s
, ",")
1980 parse_propagationopt(p
, pflags
);
1986 static void null_endofword(char *word
)
1988 while (*word
&& *word
!= ' ' && *word
!= '\t')
1993 /* skip @nfields spaces in @src */
1994 static char *get_field(char *src
, int nfields
)
1999 for (i
= 0; i
< nfields
; i
++) {
2000 while (*p
&& *p
!= ' ' && *p
!= '\t')
2012 static int mount_entry(const char *fsname
, const char *target
,
2013 const char *fstype
, unsigned long mountflags
,
2014 unsigned long pflags
, const char *data
, bool optional
,
2015 bool dev
, bool relative
, const char *rootfs
)
2018 char srcbuf
[PATH_MAX
];
2019 const char *srcpath
= fsname
;
2025 ret
= snprintf(srcbuf
, PATH_MAX
, "%s/%s", rootfs
? rootfs
: "/", fsname
? fsname
: "");
2026 if (ret
< 0 || ret
>= PATH_MAX
) {
2027 ERROR("source path is too long");
2033 ret
= safe_mount(srcpath
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
2037 SYSINFO("Failed to mount \"%s\" on \"%s\" (optional)",
2038 srcpath
? srcpath
: "(null)", target
);
2042 SYSERROR("Failed to mount \"%s\" on \"%s\"",
2043 srcpath
? srcpath
: "(null)", target
);
2047 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
2048 unsigned long rqd_flags
= 0;
2050 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount "
2051 "options", srcpath
? srcpath
: "(none)", target
? target
: "(none)");
2053 if (mountflags
& MS_RDONLY
)
2054 rqd_flags
|= MS_RDONLY
;
2056 if (srcpath
&& statvfs(srcpath
, &sb
) == 0) {
2057 unsigned long required_flags
= rqd_flags
;
2059 if (sb
.f_flag
& MS_NOSUID
)
2060 required_flags
|= MS_NOSUID
;
2062 if (sb
.f_flag
& MS_NODEV
&& !dev
)
2063 required_flags
|= MS_NODEV
;
2065 if (sb
.f_flag
& MS_RDONLY
)
2066 required_flags
|= MS_RDONLY
;
2068 if (sb
.f_flag
& MS_NOEXEC
)
2069 required_flags
|= MS_NOEXEC
;
2071 DEBUG("Flags for \"%s\" were %lu, required extra flags "
2072 "are %lu", srcpath
, sb
.f_flag
, required_flags
);
2074 /* If this was a bind mount request, and required_flags
2075 * does not have any flags which are not already in
2076 * mountflags, then skip the remount.
2078 if (!(mountflags
& MS_REMOUNT
)) {
2079 if (!(required_flags
& ~mountflags
) &&
2081 DEBUG("Mountflags already were %lu, "
2082 "skipping remount", mountflags
);
2087 mountflags
|= required_flags
;
2091 ret
= mount(srcpath
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
2094 SYSINFO("Failed to mount \"%s\" on \"%s\" (optional)",
2095 srcpath
? srcpath
: "(null)", target
);
2099 SYSERROR("Failed to mount \"%s\" on \"%s\"",
2100 srcpath
? srcpath
: "(null)", target
);
2109 ret
= mount(NULL
, target
, NULL
, pflags
, NULL
);
2112 SYSINFO("Failed to change mount propagation "
2113 "for \"%s\" (optional)", target
);
2116 SYSERROR("Failed to change mount propagation "
2117 "for \"%s\" (optional)", target
);
2121 DEBUG("Changed mount propagation for \"%s\"", target
);
2124 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
2125 srcpath
? srcpath
: "(null)", target
, fstype
);
2130 /* Remove "optional", "create=dir", and "create=file" from mntopt */
2131 static void cull_mntent_opt(struct mntent
*mntent
)
2142 for (i
= 0; list
[i
]; i
++) {
2145 p
= strstr(mntent
->mnt_opts
, list
[i
]);
2149 p2
= strchr(p
, ',');
2151 /* no more mntopts, so just chop it here */
2156 memmove(p
, p2
+ 1, strlen(p2
+ 1) + 1);
2160 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
2162 const struct lxc_rootfs
*rootfs
,
2163 const char *lxc_name
, const char *lxc_path
)
2168 if (strncmp(mntent
->mnt_type
, "overlay", 7) == 0) {
2169 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
2174 if (hasmntopt(mntent
, "create=dir")) {
2175 ret
= mkdir_p(path
, 0755);
2176 if (ret
< 0 && errno
!= EEXIST
) {
2177 SYSERROR("Failed to create directory \"%s\"", path
);
2182 if (!hasmntopt(mntent
, "create=file"))
2185 ret
= access(path
, F_OK
);
2195 ret
= mkdir_p(p2
, 0755);
2197 if (ret
< 0 && errno
!= EEXIST
) {
2198 SYSERROR("Failed to create directory \"%s\"", path
);
2202 ret
= mknod(path
, S_IFREG
| 0000, 0);
2203 if (ret
< 0 && errno
!= EEXIST
)
2209 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2210 * without a rootfs. */
2211 static inline int mount_entry_on_generic(struct mntent
*mntent
,
2213 const struct lxc_rootfs
*rootfs
,
2214 const char *lxc_name
,
2215 const char *lxc_path
)
2218 unsigned long mntflags
;
2220 bool dev
, optional
, relative
;
2221 unsigned long pflags
= 0;
2222 char *rootfs_path
= NULL
;
2224 optional
= hasmntopt(mntent
, "optional") != NULL
;
2225 dev
= hasmntopt(mntent
, "dev") != NULL
;
2226 relative
= hasmntopt(mntent
, "relative") != NULL
;
2228 if (rootfs
&& rootfs
->path
)
2229 rootfs_path
= rootfs
->mount
;
2231 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
2239 cull_mntent_opt(mntent
);
2241 ret
= parse_propagationopts(mntent
->mnt_opts
, &pflags
);
2245 ret
= parse_mntopts(mntent
->mnt_opts
, &mntflags
, &mntdata
);
2249 ret
= mount_entry(mntent
->mnt_fsname
, path
, mntent
->mnt_type
, mntflags
,
2250 pflags
, mntdata
, optional
, dev
, relative
, rootfs_path
);
2256 static inline int mount_entry_on_systemfs(struct mntent
*mntent
)
2259 char path
[PATH_MAX
];
2261 /* For containers created without a rootfs all mounts are treated as
2262 * absolute paths starting at / on the host.
2264 if (mntent
->mnt_dir
[0] != '/')
2265 ret
= snprintf(path
, sizeof(path
), "/%s", mntent
->mnt_dir
);
2267 ret
= snprintf(path
, sizeof(path
), "%s", mntent
->mnt_dir
);
2268 if (ret
< 0 || ret
>= sizeof(path
))
2271 return mount_entry_on_generic(mntent
, path
, NULL
, NULL
, NULL
);
2274 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
2275 const struct lxc_rootfs
*rootfs
,
2276 const char *lxc_name
,
2277 const char *lxc_path
)
2281 const char *lxcpath
;
2282 char path
[PATH_MAX
];
2285 lxcpath
= lxc_global_config_value("lxc.lxcpath");
2289 /* If rootfs->path is a blockdev path, allow container fstab to use
2290 * <lxcpath>/<name>/rootfs" as the target prefix.
2292 ret
= snprintf(path
, PATH_MAX
, "%s/%s/rootfs", lxcpath
, lxc_name
);
2293 if (ret
< 0 || ret
>= PATH_MAX
)
2296 aux
= strstr(mntent
->mnt_dir
, path
);
2298 offset
= strlen(path
);
2303 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
2305 WARN("Ignoring mount point \"%s\"", mntent
->mnt_dir
);
2308 offset
= strlen(rootfs
->path
);
2311 ret
= snprintf(path
, PATH_MAX
, "%s/%s", rootfs
->mount
, aux
+ offset
);
2312 if (ret
< 0 || ret
>= PATH_MAX
)
2315 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2318 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
2319 const struct lxc_rootfs
*rootfs
,
2320 const char *lxc_name
,
2321 const char *lxc_path
)
2324 char path
[PATH_MAX
];
2326 /* relative to root mount point */
2327 ret
= snprintf(path
, sizeof(path
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2328 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
2331 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2334 static int mount_file_entries(const struct lxc_conf
*conf
,
2335 const struct lxc_rootfs
*rootfs
, FILE *file
,
2336 const char *lxc_name
, const char *lxc_path
)
2339 struct mntent mntent
;
2341 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2345 ret
= mount_entry_on_systemfs(&mntent
);
2346 else if (mntent
.mnt_dir
[0] != '/')
2347 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2348 lxc_name
, lxc_path
);
2350 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2351 lxc_name
, lxc_path
);
2356 if (!feof(file
) || ferror(file
)) {
2357 ERROR("Failed to parse mount entries");
2364 static int setup_mount(const struct lxc_conf
*conf
,
2365 const struct lxc_rootfs
*rootfs
, const char *fstab
,
2366 const char *lxc_name
, const char *lxc_path
)
2374 f
= setmntent(fstab
, "r");
2376 SYSERROR("Failed to open \"%s\"", fstab
);
2380 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2382 ERROR("Failed to set up mount entries");
2389 * In order for nested containers to be able to mount /proc and /sys they need
2390 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2392 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2393 * apparmor rule to deny access to them. This is mostly for convenience: The
2394 * container's root user can mount them anyway and thus has access to the two
2395 * file systems. But a non-root user in the container should not be allowed to
2396 * access them as a side effect without explicitly allowing it.
2398 static const char nesting_helpers
[] =
2399 "proc dev/.lxc/proc proc create=dir,optional 0 0\n"
2400 "sys dev/.lxc/sys sysfs create=dir,optional 0 0\n";
2402 FILE *make_anonymous_mount_file(struct lxc_list
*mount
,
2403 bool include_nesting_helpers
)
2407 struct lxc_list
*iterator
;
2410 fd
= memfd_create(".lxc_mount_file", MFD_CLOEXEC
);
2412 char template[] = P_tmpdir
"/.lxc_mount_file_XXXXXX";
2414 if (errno
!= ENOSYS
)
2417 fd
= lxc_make_tmpfile(template, true);
2419 SYSERROR("Could not create temporary mount file");
2423 TRACE("Created temporary mount file");
2426 lxc_list_for_each (iterator
, mount
) {
2429 mount_entry
= iterator
->elem
;
2430 len
= strlen(mount_entry
);
2432 ret
= lxc_write_nointr(fd
, mount_entry
, len
);
2436 ret
= lxc_write_nointr(fd
, "\n", 1);
2441 if (include_nesting_helpers
) {
2442 ret
= lxc_write_nointr(fd
, nesting_helpers
,
2443 STRARRAYLEN(nesting_helpers
));
2444 if (ret
!= STRARRAYLEN(nesting_helpers
))
2448 ret
= lseek(fd
, 0, SEEK_SET
);
2452 return fdopen(fd
, "r+");
2455 SYSERROR("Failed to write mount entry to temporary mount file");
2460 static int setup_mount_entries(const struct lxc_conf
*conf
,
2461 const struct lxc_rootfs
*rootfs
,
2462 struct lxc_list
*mount
, const char *lxc_name
,
2463 const char *lxc_path
)
2468 f
= make_anonymous_mount_file(mount
, conf
->lsm_aa_allow_nesting
);
2472 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2478 static int parse_cap(const char *cap
)
2482 size_t end
= sizeof(caps_opt
) / sizeof(caps_opt
[0]);
2485 if (strcmp(cap
, "none") == 0)
2488 for (i
= 0; i
< end
; i
++) {
2489 if (strcmp(cap
, caps_opt
[i
].name
))
2492 capid
= caps_opt
[i
].value
;
2497 /* Try to see if it's numeric, so the user may specify
2498 * capabilities that the running kernel knows about but we
2502 capid
= strtol(cap
, &ptr
, 10);
2503 if (!ptr
|| *ptr
!= '\0' || errno
!= 0)
2504 /* not a valid number */
2506 else if (capid
> lxc_caps_last_cap())
2507 /* we have a number but it's not a valid
2515 int in_caplist(int cap
, struct lxc_list
*caps
)
2518 struct lxc_list
*iterator
;
2520 lxc_list_for_each (iterator
, caps
) {
2521 capid
= parse_cap(iterator
->elem
);
2529 static int setup_caps(struct lxc_list
*caps
)
2533 struct lxc_list
*iterator
;
2535 lxc_list_for_each (iterator
, caps
) {
2538 drop_entry
= iterator
->elem
;
2540 capid
= parse_cap(drop_entry
);
2542 ERROR("unknown capability %s", drop_entry
);
2546 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(capid
), prctl_arg(0),
2547 prctl_arg(0), prctl_arg(0));
2549 SYSERROR("Failed to remove %s capability", drop_entry
);
2552 DEBUG("Dropped %s (%d) capability", drop_entry
, capid
);
2555 DEBUG("Capabilities have been setup");
2559 static int dropcaps_except(struct lxc_list
*caps
)
2561 __do_free
int *caplist
= NULL
;
2562 int i
, capid
, numcaps
;
2564 struct lxc_list
*iterator
;
2566 numcaps
= lxc_caps_last_cap() + 1;
2567 if (numcaps
<= 0 || numcaps
> 200)
2569 TRACE("Found %d capabilities", numcaps
);
2571 /* caplist[i] is 1 if we keep capability i */
2572 caplist
= must_realloc(NULL
, numcaps
* sizeof(int));
2573 memset(caplist
, 0, numcaps
* sizeof(int));
2575 lxc_list_for_each (iterator
, caps
) {
2576 keep_entry
= iterator
->elem
;
2578 capid
= parse_cap(keep_entry
);
2583 ERROR("Unknown capability %s", keep_entry
);
2587 DEBUG("Keep capability %s (%d)", keep_entry
, capid
);
2591 for (i
= 0; i
< numcaps
; i
++) {
2597 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(i
), prctl_arg(0),
2598 prctl_arg(0), prctl_arg(0));
2600 SYSERROR("Failed to remove capability %d", i
);
2605 DEBUG("Capabilities have been setup");
2609 static int parse_resource(const char *res
)
2615 for (i
= 0; i
< sizeof(limit_opt
) / sizeof(limit_opt
[0]); ++i
)
2616 if (strcmp(res
, limit_opt
[i
].name
) == 0)
2617 return limit_opt
[i
].value
;
2619 /* Try to see if it's numeric, so the user may specify
2620 * resources that the running kernel knows about but
2623 ret
= lxc_safe_int(res
, &resid
);
2630 int setup_resource_limits(struct lxc_list
*limits
, pid_t pid
)
2633 struct lxc_list
*it
;
2634 struct lxc_limit
*lim
;
2636 lxc_list_for_each (it
, limits
) {
2639 resid
= parse_resource(lim
->resource
);
2641 ERROR("Unknown resource %s", lim
->resource
);
2645 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
2646 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0) {
2647 SYSERROR("Failed to set limit %s", lim
->resource
);
2651 TRACE("Setup \"%s\" limit", lim
->resource
);
2653 ERROR("Cannot set limit \"%s\" as prlimit is missing", lim
->resource
);
2661 int setup_sysctl_parameters(struct lxc_list
*sysctls
)
2663 struct lxc_list
*it
;
2664 struct lxc_sysctl
*elem
;
2667 char filename
[PATH_MAX
] = {0};
2669 lxc_list_for_each (it
, sysctls
) {
2671 tmp
= lxc_string_replace(".", "/", elem
->key
);
2673 ERROR("Failed to replace key %s", elem
->key
);
2677 ret
= snprintf(filename
, sizeof(filename
), "/proc/sys/%s", tmp
);
2679 if (ret
< 0 || (size_t)ret
>= sizeof(filename
)) {
2680 ERROR("Error setting up sysctl parameters path");
2684 ret
= lxc_write_to_file(filename
, elem
->value
,
2685 strlen(elem
->value
), false, 0666);
2687 SYSERROR("Failed to setup sysctl parameters %s to %s",
2688 elem
->key
, elem
->value
);
2696 int setup_proc_filesystem(struct lxc_list
*procs
, pid_t pid
)
2698 struct lxc_list
*it
;
2699 struct lxc_proc
*elem
;
2702 char filename
[PATH_MAX
] = {0};
2704 lxc_list_for_each (it
, procs
) {
2706 tmp
= lxc_string_replace(".", "/", elem
->filename
);
2708 ERROR("Failed to replace key %s", elem
->filename
);
2712 ret
= snprintf(filename
, sizeof(filename
), "/proc/%d/%s", pid
, tmp
);
2714 if (ret
< 0 || (size_t)ret
>= sizeof(filename
)) {
2715 ERROR("Error setting up proc filesystem path");
2719 ret
= lxc_write_to_file(filename
, elem
->value
,
2720 strlen(elem
->value
), false, 0666);
2722 SYSERROR("Failed to setup proc filesystem %s to %s",
2723 elem
->filename
, elem
->value
);
2731 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
2733 struct lxc_conf
*lxc_conf_init(void)
2736 struct lxc_conf
*new;
2738 new = malloc(sizeof(*new));
2741 memset(new, 0, sizeof(*new));
2743 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
2744 new->personality
= -1;
2746 new->console
.buffer_size
= 0;
2747 new->console
.log_path
= NULL
;
2748 new->console
.log_fd
= -1;
2749 new->console
.log_size
= 0;
2750 new->console
.path
= NULL
;
2751 new->console
.peer
= -1;
2752 new->console
.proxy
.busy
= -1;
2753 new->console
.proxy
.master
= -1;
2754 new->console
.proxy
.slave
= -1;
2755 new->console
.master
= -1;
2756 new->console
.slave
= -1;
2757 new->console
.name
[0] = '\0';
2758 memset(&new->console
.ringbuf
, 0, sizeof(struct lxc_ringbuf
));
2759 new->maincmd_fd
= -1;
2760 new->monitor_signal_pdeath
= SIGKILL
;
2762 new->rootfs
.mount
= strdup(default_rootfs_mount
);
2763 if (!new->rootfs
.mount
) {
2767 new->rootfs
.managed
= true;
2769 lxc_list_init(&new->cgroup
);
2770 lxc_list_init(&new->cgroup2
);
2771 lxc_list_init(&new->network
);
2772 lxc_list_init(&new->mount_list
);
2773 lxc_list_init(&new->caps
);
2774 lxc_list_init(&new->keepcaps
);
2775 lxc_list_init(&new->id_map
);
2776 new->root_nsuid_map
= NULL
;
2777 new->root_nsgid_map
= NULL
;
2778 lxc_list_init(&new->includes
);
2779 lxc_list_init(&new->aliens
);
2780 lxc_list_init(&new->environment
);
2781 lxc_list_init(&new->limits
);
2782 lxc_list_init(&new->sysctls
);
2783 lxc_list_init(&new->procs
);
2784 new->hooks_version
= 0;
2785 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++)
2786 lxc_list_init(&new->hooks
[i
]);
2787 lxc_list_init(&new->groups
);
2788 lxc_list_init(&new->state_clients
);
2789 new->lsm_aa_profile
= NULL
;
2790 lxc_list_init(&new->lsm_aa_raw
);
2791 new->lsm_se_context
= NULL
;
2792 new->tmp_umount_proc
= false;
2793 new->tmp_umount_proc
= 0;
2794 new->shmount
.path_host
= NULL
;
2795 new->shmount
.path_cont
= NULL
;
2797 /* if running in a new user namespace, init and COMMAND
2798 * default to running as UID/GID 0 when using lxc-execute */
2801 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
2802 memset(&new->ns_share
, 0, sizeof(char *) * LXC_NS_MAX
);
2807 int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
2811 char path
[PATH_MAX
];
2813 if (geteuid() != 0 && idtype
== ID_TYPE_GID
) {
2816 ret
= snprintf(path
, PATH_MAX
, "/proc/%d/setgroups", pid
);
2817 if (ret
< 0 || ret
>= PATH_MAX
)
2820 fd
= open(path
, O_WRONLY
);
2821 if (fd
< 0 && errno
!= ENOENT
) {
2822 SYSERROR("Failed to open \"%s\"", path
);
2827 buflen
= STRLITERALLEN("deny\n");
2829 ret
= lxc_write_nointr(fd
, "deny\n", buflen
);
2831 if (ret
!= buflen
) {
2832 SYSERROR("Failed to write \"deny\" to "
2833 "\"/proc/%d/setgroups\"", pid
);
2836 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid
);
2840 ret
= snprintf(path
, PATH_MAX
, "/proc/%d/%cid_map", pid
,
2841 idtype
== ID_TYPE_UID
? 'u' : 'g');
2842 if (ret
< 0 || ret
>= PATH_MAX
)
2845 fd
= open(path
, O_WRONLY
);
2847 SYSERROR("Failed to open \"%s\"", path
);
2852 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
2854 if (ret
!= buf_size
) {
2855 SYSERROR("Failed to write %cid mapping to \"%s\"",
2856 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
2863 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2865 * @return 1 if functional binary was found
2866 * @return 0 if binary exists but is lacking privilege
2867 * @return -ENOENT if binary does not exist
2868 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2870 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
2877 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
2880 path
= on_path(binary
, NULL
);
2884 ret
= stat(path
, &st
);
2890 /* Check if the binary is setuid. */
2891 if (st
.st_mode
& S_ISUID
) {
2892 DEBUG("The binary \"%s\" does have the setuid bit set", path
);
2897 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
2898 /* Check if it has the CAP_SETUID capability. */
2899 if ((cap
& CAP_SETUID
) &&
2900 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
2901 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
)) {
2902 DEBUG("The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE "
2903 "and CAP_PERMITTED sets", path
);
2908 /* Check if it has the CAP_SETGID capability. */
2909 if ((cap
& CAP_SETGID
) &&
2910 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
2911 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
)) {
2912 DEBUG("The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE "
2913 "and CAP_PERMITTED sets", path
);
2918 /* If we cannot check for file capabilities we need to give the benefit
2919 * of the doubt. Otherwise we might fail even though all the necessary
2920 * file capabilities are set.
2922 DEBUG("Cannot check for file capabilities as full capability support is "
2923 "missing. Manual intervention needed");
2932 int lxc_map_ids_exec_wrapper(void *args
)
2934 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
2938 int lxc_map_ids(struct lxc_list
*idmap
, pid_t pid
)
2943 char cmd_output
[PATH_MAX
];
2945 struct lxc_list
*iterator
;
2947 /* strlen("new@idmap") = 9
2951 * INTTYPE_TO_STRLEN(uint32_t)
2955 * We add some additional space to make sure that we really have
2956 * LXC_IDMAPLEN bytes available for our the {g,u]id mapping.
2958 int ret
= 0, gidmap
= 0, uidmap
= 0;
2959 char mapbuf
[9 + 1 + INTTYPE_TO_STRLEN(uint32_t) + 1 + LXC_IDMAPLEN
] = {0};
2960 bool had_entry
= false, use_shadow
= false;
2961 int hostuid
, hostgid
;
2963 hostuid
= geteuid();
2964 hostgid
= getegid();
2966 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2967 * ranges, then insist that root also reserve ranges in subuid. This
2968 * will protected it by preventing another user from being handed the
2971 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
2972 if (uidmap
== -ENOENT
)
2973 WARN("newuidmap binary is missing");
2975 WARN("newuidmap is lacking necessary privileges");
2977 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
2978 if (gidmap
== -ENOENT
)
2979 WARN("newgidmap binary is missing");
2981 WARN("newgidmap is lacking necessary privileges");
2983 if (uidmap
> 0 && gidmap
> 0) {
2984 DEBUG("Functional newuidmap and newgidmap binary found");
2987 /* In case unprivileged users run application containers via
2988 * execute() or a start*() there are valid cases where they may
2989 * only want to map their own {g,u}id. Let's not block them from
2990 * doing so by requiring geteuid() == 0.
2992 DEBUG("No newuidmap and newgidmap binary found. Trying to "
2993 "write directly with euid %d", hostuid
);
2996 /* Check if we really need to use newuidmap and newgidmap.
2997 * If the user is only remapping his own {g,u}id, we don't need it.
2999 if (use_shadow
&& lxc_list_len(idmap
) == 2) {
3001 lxc_list_for_each(iterator
, idmap
) {
3002 map
= iterator
->elem
;
3003 if (map
->idtype
== ID_TYPE_UID
&& map
->range
== 1 &&
3004 map
->nsid
== hostuid
&& map
->hostid
== hostuid
)
3006 if (map
->idtype
== ID_TYPE_GID
&& map
->range
== 1 &&
3007 map
->nsid
== hostgid
&& map
->hostid
== hostgid
)
3014 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
3015 type
++, u_or_g
= 'g') {
3019 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
3021 lxc_list_for_each(iterator
, idmap
) {
3022 map
= iterator
->elem
;
3023 if (map
->idtype
!= type
)
3028 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
3029 fill
= snprintf(pos
, left
, "%s%lu %lu %lu%s",
3030 use_shadow
? " " : "", map
->nsid
,
3031 map
->hostid
, map
->range
,
3032 use_shadow
? "" : "\n");
3033 if (fill
<= 0 || fill
>= left
) {
3034 /* The kernel only takes <= 4k for writes to
3035 * /proc/<pid>/{g,u}id_map
3037 SYSERROR("Too many %cid mappings defined", u_or_g
);
3046 /* Try to catch the output of new{g,u}idmap to make debugging
3050 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3051 lxc_map_ids_exec_wrapper
,
3054 ERROR("new%cidmap failed to write mapping \"%s\": %s",
3055 u_or_g
, cmd_output
, mapbuf
);
3058 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g
, mapbuf
);
3060 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
3062 ERROR("Failed to write mapping: %s", mapbuf
);
3065 TRACE("Wrote mapping \"%s\"", mapbuf
);
3068 memset(mapbuf
, 0, sizeof(mapbuf
));
3074 /* Return the host uid/gid to which the container root is mapped in val.
3075 * Return true if id was found, false otherwise.
3077 bool get_mapped_rootid(struct lxc_conf
*conf
, enum idtype idtype
,
3082 struct lxc_list
*it
;
3084 if (idtype
== ID_TYPE_UID
)
3085 nsid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
3087 nsid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
3089 lxc_list_for_each (it
, &conf
->id_map
) {
3091 if (map
->idtype
!= idtype
)
3093 if (map
->nsid
!= nsid
)
3102 int mapped_hostid(unsigned id
, struct lxc_conf
*conf
, enum idtype idtype
)
3105 struct lxc_list
*it
;
3107 lxc_list_for_each (it
, &conf
->id_map
) {
3109 if (map
->idtype
!= idtype
)
3112 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
3113 return (id
- map
->hostid
) + map
->nsid
;
3119 int find_unmapped_nsid(struct lxc_conf
*conf
, enum idtype idtype
)
3122 struct lxc_list
*it
;
3123 unsigned int freeid
= 0;
3126 lxc_list_for_each (it
, &conf
->id_map
) {
3128 if (map
->idtype
!= idtype
)
3131 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
3132 freeid
= map
->nsid
+ map
->range
;
3140 int chown_mapped_root_exec_wrapper(void *args
)
3142 execvp("lxc-usernsexec", args
);
3146 /* chown_mapped_root: for an unprivileged user with uid/gid X to
3147 * chown a dir to subuid/subgid Y, he needs to run chown as root
3148 * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and
3149 * nsid Y is mapped to hostuid/hostgid X. That way, the container
3150 * root is privileged with respect to hostuid/hostgid X, allowing
3151 * him to do the chown.
3153 int chown_mapped_root(const char *path
, struct lxc_conf
*conf
)
3155 uid_t rootuid
, rootgid
;
3157 int hostuid
, hostgid
, ret
;
3159 char map1
[100], map2
[100], map3
[100], map4
[100], map5
[100];
3161 const char *args1
[] = {"lxc-usernsexec",
3166 "--", "chown", ugid
, path
,
3168 const char *args2
[] = {"lxc-usernsexec",
3174 "--", "chown", ugid
, path
,
3176 char cmd_output
[PATH_MAX
];
3178 hostuid
= geteuid();
3179 hostgid
= getegid();
3181 if (!get_mapped_rootid(conf
, ID_TYPE_UID
, &val
)) {
3182 ERROR("No uid mapping for container root");
3185 rootuid
= (uid_t
)val
;
3187 if (!get_mapped_rootid(conf
, ID_TYPE_GID
, &val
)) {
3188 ERROR("No gid mapping for container root");
3191 rootgid
= (gid_t
)val
;
3194 if (chown(path
, rootuid
, rootgid
) < 0) {
3195 ERROR("Error chowning %s", path
);
3202 if (rootuid
== hostuid
) {
3204 INFO("Container root is our uid; no need to chown");
3208 /* save the current gid of "path" */
3209 if (stat(path
, &sb
) < 0) {
3210 ERROR("Error stat %s", path
);
3214 /* Update the path argument in case this was overlayfs. */
3215 args1
[sizeof(args1
) / sizeof(args1
[0]) - 2] = path
;
3216 args2
[sizeof(args2
) / sizeof(args2
[0]) - 2] = path
;
3219 * A file has to be group-owned by a gid mapped into the
3220 * container, or the container won't be privileged over it.
3222 DEBUG("trying to chown \"%s\" to %d", path
, hostgid
);
3223 if (sb
.st_uid
== hostuid
&&
3224 mapped_hostid(sb
.st_gid
, conf
, ID_TYPE_GID
) < 0 &&
3225 chown(path
, -1, hostgid
) < 0) {
3226 ERROR("Failed chgrping %s", path
);
3230 /* "u:0:rootuid:1" */
3231 ret
= snprintf(map1
, 100, "u:0:%d:1", rootuid
);
3232 if (ret
< 0 || ret
>= 100) {
3233 ERROR("Error uid printing map string");
3237 /* "u:hostuid:hostuid:1" */
3238 ret
= snprintf(map2
, 100, "u:%d:%d:1", hostuid
, hostuid
);
3239 if (ret
< 0 || ret
>= 100) {
3240 ERROR("Error uid printing map string");
3244 /* "g:0:rootgid:1" */
3245 ret
= snprintf(map3
, 100, "g:0:%d:1", rootgid
);
3246 if (ret
< 0 || ret
>= 100) {
3247 ERROR("Error gid printing map string");
3251 /* "g:pathgid:rootgid+pathgid:1" */
3252 ret
= snprintf(map4
, 100, "g:%d:%d:1", (gid_t
)sb
.st_gid
,
3253 rootgid
+ (gid_t
)sb
.st_gid
);
3254 if (ret
< 0 || ret
>= 100) {
3255 ERROR("Error gid printing map string");
3259 /* "g:hostgid:hostgid:1" */
3260 ret
= snprintf(map5
, 100, "g:%d:%d:1", hostgid
, hostgid
);
3261 if (ret
< 0 || ret
>= 100) {
3262 ERROR("Error gid printing map string");
3266 /* "0:pathgid" (chown) */
3267 ret
= snprintf(ugid
, 100, "0:%d", (gid_t
)sb
.st_gid
);
3268 if (ret
< 0 || ret
>= 100) {
3269 ERROR("Error owner printing format string for chown");
3273 if (hostgid
== sb
.st_gid
)
3274 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3275 chown_mapped_root_exec_wrapper
,
3278 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3279 chown_mapped_root_exec_wrapper
,
3282 ERROR("lxc-usernsexec failed: %s", cmd_output
);
3287 /* NOTE: Must not be called from inside the container namespace! */
3288 int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
3292 mounted
= lxc_mount_proc_if_needed(conf
->rootfs
.path
? conf
->rootfs
.mount
: "");
3293 if (mounted
== -1) {
3294 SYSERROR("Failed to mount proc in the container");
3295 /* continue only if there is no rootfs */
3296 if (conf
->rootfs
.path
)
3298 } else if (mounted
== 1) {
3299 conf
->tmp_umount_proc
= true;
3305 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
3307 if (!lxc_conf
->tmp_umount_proc
)
3310 (void)umount2("/proc", MNT_DETACH
);
3311 lxc_conf
->tmp_umount_proc
= false;
3314 /* Walk /proc/mounts and change any shared entries to slave. */
3315 void remount_all_slave(void)
3317 int memfd
, mntinfo_fd
, ret
;
3323 mntinfo_fd
= open("/proc/self/mountinfo", O_RDONLY
| O_CLOEXEC
);
3324 if (mntinfo_fd
< 0) {
3325 SYSERROR("Failed to open \"/proc/self/mountinfo\"");
3329 memfd
= memfd_create(".lxc_mountinfo", MFD_CLOEXEC
);
3331 char template[] = P_tmpdir
"/.lxc_mountinfo_XXXXXX";
3333 if (errno
!= ENOSYS
) {
3334 SYSERROR("Failed to create temporary in-memory file");
3339 memfd
= lxc_make_tmpfile(template, true);
3342 WARN("Failed to create temporary file");
3348 copied
= lxc_sendfile_nointr(memfd
, mntinfo_fd
, NULL
, LXC_SENDFILE_MAX
);
3353 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
3360 /* After a successful fdopen() memfd will be closed when calling
3361 * fclose(f). Calling close(memfd) afterwards is undefined.
3363 ret
= lseek(memfd
, 0, SEEK_SET
);
3365 SYSERROR("Failed to reset file descriptor offset");
3370 f
= fdopen(memfd
, "r");
3372 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark "
3373 "all shared. Continuing");
3378 while (getline(&line
, &len
, f
) != -1) {
3379 char *opts
, *target
;
3381 target
= get_field(line
, 4);
3385 opts
= get_field(target
, 2);
3389 null_endofword(opts
);
3390 if (!strstr(opts
, "shared"))
3393 null_endofword(target
);
3394 ret
= mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
);
3396 SYSERROR("Failed to make \"%s\" MS_SLAVE", target
);
3397 ERROR("Continuing...");
3400 TRACE("Remounted \"%s\" as MS_SLAVE", target
);
3404 TRACE("Remounted all mount table entries as MS_SLAVE");
3407 static int lxc_execute_bind_init(struct lxc_handler
*handler
)
3411 char path
[PATH_MAX
], destpath
[PATH_MAX
];
3412 struct lxc_conf
*conf
= handler
->conf
;
3414 /* If init exists in the container, don't bind mount a static one */
3415 p
= choose_init(conf
->rootfs
.mount
);
3419 p
= strdup(old
+ strlen(conf
->rootfs
.mount
));
3424 INFO("Found existing init at \"%s\"", p
);
3428 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3429 if (ret
< 0 || ret
>= PATH_MAX
)
3432 if (!file_exists(path
)) {
3433 ERROR("The file \"%s\" does not exist on host", path
);
3437 ret
= snprintf(destpath
, PATH_MAX
, "%s" P_tmpdir
"%s", conf
->rootfs
.mount
, "/.lxc-init");
3438 if (ret
< 0 || ret
>= PATH_MAX
)
3441 if (!file_exists(destpath
)) {
3442 ret
= mknod(destpath
, S_IFREG
| 0000, 0);
3443 if (ret
< 0 && errno
!= EEXIST
) {
3444 SYSERROR("Failed to create dummy \"%s\" file as bind mount target", destpath
);
3449 ret
= safe_mount(path
, destpath
, "none", MS_BIND
, NULL
, conf
->rootfs
.mount
);
3451 SYSERROR("Failed to bind mount lxc.init.static into container");
3455 p
= strdup(destpath
+ strlen(conf
->rootfs
.mount
));
3459 INFO("Bind mounted lxc.init.static into container at \"%s\"", path
);
3461 ((struct execute_args
*)handler
->data
)->init_fd
= -1;
3462 ((struct execute_args
*)handler
->data
)->init_path
= p
;
3466 /* This does the work of remounting / if it is shared, calling the container
3467 * pre-mount hooks, and mounting the rootfs.
3469 int lxc_setup_rootfs_prepare_root(struct lxc_conf
*conf
, const char *name
,
3470 const char *lxcpath
)
3474 if (conf
->rootfs_setup
) {
3475 const char *path
= conf
->rootfs
.mount
;
3477 /* The rootfs was set up in another namespace. bind-mount it to
3478 * give us a mount in our own ns so we can pivot_root to it
3480 ret
= mount(path
, path
, "rootfs", MS_BIND
, NULL
);
3482 ERROR("Failed to bind mount container / onto itself");
3486 TRACE("Bind mounted container / onto itself");
3490 remount_all_slave();
3492 ret
= run_lxc_hooks(name
, "pre-mount", conf
, NULL
);
3494 ERROR("Failed to run pre-mount hooks");
3498 ret
= lxc_mount_rootfs(conf
);
3500 ERROR("Failed to setup rootfs for");
3504 conf
->rootfs_setup
= true;
3508 static bool verify_start_hooks(struct lxc_conf
*conf
)
3510 char path
[PATH_MAX
];
3511 struct lxc_list
*it
;
3513 lxc_list_for_each (it
, &conf
->hooks
[LXCHOOK_START
]) {
3515 char *hookname
= it
->elem
;
3517 ret
= snprintf(path
, PATH_MAX
, "%s%s",
3518 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
3520 if (ret
< 0 || ret
>= PATH_MAX
)
3523 ret
= access(path
, X_OK
);
3525 SYSERROR("Start hook \"%s\" not found in container",
3536 static bool execveat_supported(void)
3538 lxc_raw_execveat(-1, "", NULL
, NULL
, AT_EMPTY_PATH
);
3539 if (errno
== ENOSYS
)
3545 int lxc_setup(struct lxc_handler
*handler
)
3548 const char *lxcpath
= handler
->lxcpath
, *name
= handler
->name
;
3549 struct lxc_conf
*lxc_conf
= handler
->conf
;
3551 ret
= lxc_setup_rootfs_prepare_root(lxc_conf
, name
, lxcpath
);
3553 ERROR("Failed to setup rootfs");
3557 if (handler
->nsfd
[LXC_NS_UTS
] == -1) {
3558 ret
= setup_utsname(lxc_conf
->utsname
);
3560 ERROR("Failed to setup the utsname %s", name
);
3565 ret
= lxc_setup_keyring();
3569 ret
= lxc_setup_network_in_child_namespaces(lxc_conf
, &lxc_conf
->network
);
3571 ERROR("Failed to setup network");
3575 ret
= lxc_network_send_name_and_ifindex_to_parent(handler
);
3577 ERROR("Failed to send network device names and ifindices to parent");
3581 if (lxc_conf
->autodev
> 0) {
3582 ret
= mount_autodev(name
, &lxc_conf
->rootfs
, lxcpath
);
3584 ERROR("Failed to mount \"/dev\"");
3589 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
3590 * need to wait until other stuff has finished.
3592 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
, handler
);
3594 ERROR("Failed to setup first automatic mounts");
3598 ret
= setup_mount(lxc_conf
, &lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
);
3600 ERROR("Failed to setup mounts");
3604 if (lxc_conf
->is_execute
) {
3605 if (execveat_supported()) {
3607 char path
[PATH_MAX
];
3609 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3610 if (ret
< 0 || ret
>= PATH_MAX
) {
3611 ERROR("Path to init.lxc.static too long");
3615 fd
= open(path
, O_PATH
| O_CLOEXEC
);
3617 SYSERROR("Unable to open lxc.init.static");
3621 ((struct execute_args
*)handler
->data
)->init_fd
= fd
;
3622 ((struct execute_args
*)handler
->data
)->init_path
= NULL
;
3624 ret
= lxc_execute_bind_init(handler
);
3626 ERROR("Failed to bind-mount the lxc init system");
3632 /* Now mount only cgroups, if wanted. Before, /sys could not have been
3633 * mounted. It is guaranteed to be mounted now either through
3634 * automatically or via fstab entries.
3636 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
, handler
);
3638 ERROR("Failed to setup remaining automatic mounts");
3642 ret
= run_lxc_hooks(name
, "mount", lxc_conf
, NULL
);
3644 ERROR("Failed to run mount hooks");
3648 if (lxc_conf
->autodev
> 0) {
3649 ret
= run_lxc_hooks(name
, "autodev", lxc_conf
, NULL
);
3651 ERROR("Failed to run autodev hooks");
3655 ret
= lxc_fill_autodev(&lxc_conf
->rootfs
);
3657 ERROR("Failed to populate \"/dev\"");
3662 if (!lxc_list_empty(&lxc_conf
->mount_list
)) {
3663 ret
= setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
,
3664 &lxc_conf
->mount_list
, name
, lxcpath
);
3666 ERROR("Failed to setup mount entries");
3671 /* Make sure any start hooks are in the container */
3672 if (!verify_start_hooks(lxc_conf
)) {
3673 ERROR("Failed to verify start hooks");
3677 ret
= lxc_setup_console(&lxc_conf
->rootfs
, &lxc_conf
->console
,
3678 lxc_conf
->ttys
.dir
);
3680 ERROR("Failed to setup console");
3684 ret
= lxc_setup_dev_symlinks(&lxc_conf
->rootfs
);
3686 ERROR("Failed to setup \"/dev\" symlinks");
3690 ret
= lxc_create_tmp_proc_mount(lxc_conf
);
3692 ERROR("Failed to \"/proc\" LSMs");
3696 ret
= lxc_setup_rootfs_switch_root(&lxc_conf
->rootfs
);
3698 ERROR("Failed to pivot root into rootfs");
3702 ret
= lxc_setup_devpts(lxc_conf
);
3704 ERROR("Failed to setup new devpts instance");
3708 ret
= lxc_create_ttys(handler
);
3712 ret
= setup_personality(lxc_conf
->personality
);
3714 ERROR("Failed to set personality");
3718 /* Set sysctl value to a path under /proc/sys as determined from the
3719 * key. For e.g. net.ipv4.ip_forward translated to
3720 * /proc/sys/net/ipv4/ip_forward.
3722 if (!lxc_list_empty(&lxc_conf
->sysctls
)) {
3723 ret
= setup_sysctl_parameters(&lxc_conf
->sysctls
);
3725 ERROR("Failed to setup sysctl parameters");
3730 if (!lxc_list_empty(&lxc_conf
->keepcaps
)) {
3731 if (!lxc_list_empty(&lxc_conf
->caps
)) {
3732 ERROR("Container requests lxc.cap.drop and "
3733 "lxc.cap.keep: either use lxc.cap.drop or "
3734 "lxc.cap.keep, not both");
3738 if (dropcaps_except(&lxc_conf
->keepcaps
)) {
3739 ERROR("Failed to keep capabilities");
3742 } else if (setup_caps(&lxc_conf
->caps
)) {
3743 ERROR("Failed to drop capabilities");
3747 NOTICE("The container \"%s\" is set up", name
);
3752 int run_lxc_hooks(const char *name
, char *hookname
, struct lxc_conf
*conf
,
3755 struct lxc_list
*it
;
3758 if (strcmp(hookname
, "pre-start") == 0)
3759 which
= LXCHOOK_PRESTART
;
3760 else if (strcmp(hookname
, "start-host") == 0)
3761 which
= LXCHOOK_START_HOST
;
3762 else if (strcmp(hookname
, "pre-mount") == 0)
3763 which
= LXCHOOK_PREMOUNT
;
3764 else if (strcmp(hookname
, "mount") == 0)
3765 which
= LXCHOOK_MOUNT
;
3766 else if (strcmp(hookname
, "autodev") == 0)
3767 which
= LXCHOOK_AUTODEV
;
3768 else if (strcmp(hookname
, "start") == 0)
3769 which
= LXCHOOK_START
;
3770 else if (strcmp(hookname
, "stop") == 0)
3771 which
= LXCHOOK_STOP
;
3772 else if (strcmp(hookname
, "post-stop") == 0)
3773 which
= LXCHOOK_POSTSTOP
;
3774 else if (strcmp(hookname
, "clone") == 0)
3775 which
= LXCHOOK_CLONE
;
3776 else if (strcmp(hookname
, "destroy") == 0)
3777 which
= LXCHOOK_DESTROY
;
3781 lxc_list_for_each (it
, &conf
->hooks
[which
]) {
3783 char *hook
= it
->elem
;
3785 ret
= run_script_argv(name
, conf
->hooks_version
, "lxc", hook
,
3794 int lxc_clear_config_caps(struct lxc_conf
*c
)
3796 struct lxc_list
*it
, *next
;
3798 lxc_list_for_each_safe (it
, &c
->caps
, next
) {
3807 static int lxc_free_idmap(struct lxc_list
*id_map
)
3809 struct lxc_list
*it
, *next
;
3811 lxc_list_for_each_safe (it
, id_map
, next
) {
3820 int lxc_clear_idmaps(struct lxc_conf
*c
)
3822 return lxc_free_idmap(&c
->id_map
);
3825 int lxc_clear_config_keepcaps(struct lxc_conf
*c
)
3827 struct lxc_list
*it
, *next
;
3829 lxc_list_for_each_safe (it
, &c
->keepcaps
, next
) {
3838 int lxc_clear_namespace(struct lxc_conf
*c
)
3841 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
3842 free(c
->ns_share
[i
]);
3843 c
->ns_share
[i
] = NULL
;
3848 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
, int version
)
3850 char *global_token
, *namespaced_token
;
3851 size_t namespaced_token_len
;
3852 struct lxc_list
*it
, *next
, *list
;
3853 const char *k
= key
;
3856 if (version
== CGROUP2_SUPER_MAGIC
) {
3857 global_token
= "lxc.cgroup2";
3858 namespaced_token
= "lxc.cgroup2.";
3859 namespaced_token_len
= STRLITERALLEN("lxc.cgroup2.");
3861 } else if (version
== CGROUP_SUPER_MAGIC
) {
3862 global_token
= "lxc.cgroup";
3863 namespaced_token
= "lxc.cgroup.";
3864 namespaced_token_len
= STRLITERALLEN("lxc.cgroup.");
3870 if (strcmp(key
, global_token
) == 0)
3872 else if (strncmp(key
, namespaced_token
, namespaced_token_len
) == 0)
3873 k
+= namespaced_token_len
;
3877 lxc_list_for_each_safe (it
, list
, next
) {
3878 struct lxc_cgroup
*cg
= it
->elem
;
3880 if (!all
&& strcmp(cg
->subsystem
, k
) != 0)
3884 free(cg
->subsystem
);
3893 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
3895 struct lxc_list
*it
, *next
;
3896 const char *k
= NULL
;
3899 if (strcmp(key
, "lxc.limit") == 0 || strcmp(key
, "lxc.prlimit") == 0)
3901 else if (strncmp(key
, "lxc.limit.", STRLITERALLEN("lxc.limit.")) == 0)
3902 k
= key
+ STRLITERALLEN("lxc.limit.");
3903 else if (strncmp(key
, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")) == 0)
3904 k
= key
+ STRLITERALLEN("lxc.prlimit.");
3908 lxc_list_for_each_safe (it
, &c
->limits
, next
) {
3909 struct lxc_limit
*lim
= it
->elem
;
3911 if (!all
&& strcmp(lim
->resource
, k
) != 0)
3915 free(lim
->resource
);
3923 int lxc_clear_sysctls(struct lxc_conf
*c
, const char *key
)
3925 struct lxc_list
*it
, *next
;
3926 const char *k
= NULL
;
3929 if (strcmp(key
, "lxc.sysctl") == 0)
3931 else if (strncmp(key
, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")) == 0)
3932 k
= key
+ STRLITERALLEN("lxc.sysctl.");
3936 lxc_list_for_each_safe (it
, &c
->sysctls
, next
) {
3937 struct lxc_sysctl
*elem
= it
->elem
;
3939 if (!all
&& strcmp(elem
->key
, k
) != 0)
3952 int lxc_clear_procs(struct lxc_conf
*c
, const char *key
)
3954 struct lxc_list
*it
, *next
;
3955 const char *k
= NULL
;
3958 if (strcmp(key
, "lxc.proc") == 0)
3960 else if (strncmp(key
, "lxc.proc.", STRLITERALLEN("lxc.proc.")) == 0)
3961 k
= key
+ STRLITERALLEN("lxc.proc.");
3965 lxc_list_for_each_safe (it
, &c
->procs
, next
) {
3966 struct lxc_proc
*proc
= it
->elem
;
3968 if (!all
&& strcmp(proc
->filename
, k
) != 0)
3972 free(proc
->filename
);
3981 int lxc_clear_groups(struct lxc_conf
*c
)
3983 struct lxc_list
*it
, *next
;
3985 lxc_list_for_each_safe (it
, &c
->groups
, next
) {
3994 int lxc_clear_environment(struct lxc_conf
*c
)
3996 struct lxc_list
*it
, *next
;
3998 lxc_list_for_each_safe (it
, &c
->environment
, next
) {
4007 int lxc_clear_mount_entries(struct lxc_conf
*c
)
4009 struct lxc_list
*it
, *next
;
4011 lxc_list_for_each_safe (it
, &c
->mount_list
, next
) {
4020 int lxc_clear_automounts(struct lxc_conf
*c
)
4026 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
4029 struct lxc_list
*it
, *next
;
4030 const char *k
= NULL
;
4031 bool all
= false, done
= false;
4033 if (strcmp(key
, "lxc.hook") == 0)
4035 else if (strncmp(key
, "lxc.hook.", STRLITERALLEN("lxc.hook.")) == 0)
4036 k
= key
+ STRLITERALLEN("lxc.hook.");
4040 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++) {
4041 if (all
|| strcmp(k
, lxchook_names
[i
]) == 0) {
4042 lxc_list_for_each_safe (it
, &c
->hooks
[i
], next
) {
4053 ERROR("Invalid hook key: %s", key
);
4060 static inline void lxc_clear_aliens(struct lxc_conf
*conf
)
4062 struct lxc_list
*it
, *next
;
4064 lxc_list_for_each_safe (it
, &conf
->aliens
, next
) {
4071 void lxc_clear_includes(struct lxc_conf
*conf
)
4073 struct lxc_list
*it
, *next
;
4075 lxc_list_for_each_safe (it
, &conf
->includes
, next
) {
4082 int lxc_clear_apparmor_raw(struct lxc_conf
*c
)
4084 struct lxc_list
*it
, *next
;
4086 lxc_list_for_each_safe (it
, &c
->lsm_aa_raw
, next
) {
4095 void lxc_conf_free(struct lxc_conf
*conf
)
4100 if (current_config
== conf
)
4101 current_config
= NULL
;
4102 lxc_terminal_conf_free(&conf
->console
);
4103 free(conf
->rootfs
.mount
);
4104 free(conf
->rootfs
.bdev_type
);
4105 free(conf
->rootfs
.options
);
4106 free(conf
->rootfs
.path
);
4107 free(conf
->logfile
);
4108 if (conf
->logfd
!= -1)
4110 free(conf
->utsname
);
4111 free(conf
->ttys
.dir
);
4112 free(conf
->ttys
.tty_names
);
4115 free(conf
->execute_cmd
);
4116 free(conf
->init_cmd
);
4117 free(conf
->init_cwd
);
4118 free(conf
->unexpanded_config
);
4120 lxc_free_networks(&conf
->network
);
4121 free(conf
->lsm_aa_profile
);
4122 free(conf
->lsm_aa_profile_computed
);
4123 free(conf
->lsm_se_context
);
4124 lxc_seccomp_free(conf
);
4125 lxc_clear_config_caps(conf
);
4126 lxc_clear_config_keepcaps(conf
);
4127 lxc_clear_cgroups(conf
, "lxc.cgroup", CGROUP_SUPER_MAGIC
);
4128 lxc_clear_cgroups(conf
, "lxc.cgroup2", CGROUP2_SUPER_MAGIC
);
4129 lxc_clear_hooks(conf
, "lxc.hook");
4130 lxc_clear_mount_entries(conf
);
4131 lxc_clear_idmaps(conf
);
4132 lxc_clear_groups(conf
);
4133 lxc_clear_includes(conf
);
4134 lxc_clear_aliens(conf
);
4135 lxc_clear_environment(conf
);
4136 lxc_clear_limits(conf
, "lxc.prlimit");
4137 lxc_clear_sysctls(conf
, "lxc.sysctl");
4138 lxc_clear_procs(conf
, "lxc.proc");
4139 lxc_clear_apparmor_raw(conf
);
4140 lxc_clear_namespace(conf
);
4141 free(conf
->cgroup_meta
.dir
);
4142 free(conf
->cgroup_meta
.controllers
);
4143 free(conf
->shmount
.path_host
);
4144 free(conf
->shmount
.path_cont
);
4148 struct userns_fn_data
{
4150 const char *fn_name
;
4155 static int run_userns_fn(void *data
)
4159 struct userns_fn_data
*d
= data
;
4161 /* Close write end of the pipe. */
4164 /* Wait for parent to finish establishing a new mapping in the user
4165 * namespace we are executing in.
4167 ret
= lxc_read_nointr(d
->p
[0], &c
, 1);
4168 /* Close read end of the pipe. */
4174 TRACE("Calling function \"%s\"", d
->fn_name
);
4176 /* Call function to run. */
4177 return d
->fn(d
->arg
);
4180 static struct id_map
*mapped_nsid_add(struct lxc_conf
*conf
, unsigned id
,
4183 const struct id_map
*map
;
4184 struct id_map
*retmap
;
4186 map
= find_mapped_nsid_entry(conf
, id
, idtype
);
4190 retmap
= malloc(sizeof(*retmap
));
4194 memcpy(retmap
, map
, sizeof(*retmap
));
4198 static struct id_map
*find_mapped_hostid_entry(struct lxc_conf
*conf
,
4199 unsigned id
, enum idtype idtype
)
4202 struct lxc_list
*it
;
4203 struct id_map
*retmap
= NULL
;
4205 lxc_list_for_each (it
, &conf
->id_map
) {
4207 if (map
->idtype
!= idtype
)
4210 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
4219 /* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
4220 * existing one or establish a new one.
4222 static struct id_map
*mapped_hostid_add(struct lxc_conf
*conf
, uid_t id
,
4226 struct id_map
*entry
= NULL
, *tmp
= NULL
;
4228 entry
= malloc(sizeof(*entry
));
4232 /* Reuse existing mapping. */
4233 tmp
= find_mapped_hostid_entry(conf
, id
, type
);
4235 return memcpy(entry
, tmp
, sizeof(*entry
));
4237 /* Find new mapping. */
4238 hostid_mapped
= find_unmapped_nsid(conf
, type
);
4239 if (hostid_mapped
< 0) {
4240 DEBUG("Failed to find free mapping for id %d", id
);
4245 entry
->idtype
= type
;
4246 entry
->nsid
= hostid_mapped
;
4247 entry
->hostid
= (unsigned long)id
;
4253 struct lxc_list
*get_minimal_idmap(struct lxc_conf
*conf
)
4256 uid_t nsuid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
4257 gid_t nsgid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
4258 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
4259 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
4260 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4262 /* Find container root mappings. */
4263 container_root_uid
= mapped_nsid_add(conf
, nsuid
, ID_TYPE_UID
);
4264 if (!container_root_uid
) {
4265 DEBUG("Failed to find mapping for namespace uid %d", 0);
4269 if (euid
>= container_root_uid
->hostid
&&
4270 euid
< (container_root_uid
->hostid
+ container_root_uid
->range
))
4271 host_uid_map
= container_root_uid
;
4273 container_root_gid
= mapped_nsid_add(conf
, nsgid
, ID_TYPE_GID
);
4274 if (!container_root_gid
) {
4275 DEBUG("Failed to find mapping for namespace gid %d", 0);
4279 if (egid
>= container_root_gid
->hostid
&&
4280 egid
< (container_root_gid
->hostid
+ container_root_gid
->range
))
4281 host_gid_map
= container_root_gid
;
4283 /* Check whether the {g,u}id of the user has a mapping. */
4285 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4286 if (!host_uid_map
) {
4287 DEBUG("Failed to find mapping for uid %d", euid
);
4292 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4293 if (!host_gid_map
) {
4294 DEBUG("Failed to find mapping for gid %d", egid
);
4298 /* Allocate new {g,u}id map list. */
4299 idmap
= malloc(sizeof(*idmap
));
4302 lxc_list_init(idmap
);
4304 /* Add container root to the map. */
4305 tmplist
= malloc(sizeof(*tmplist
));
4308 lxc_list_add_elem(tmplist
, container_root_uid
);
4309 lxc_list_add_tail(idmap
, tmplist
);
4311 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4312 /* idmap will now keep track of that memory. */
4313 container_root_uid
= NULL
;
4315 /* Add container root to the map. */
4316 tmplist
= malloc(sizeof(*tmplist
));
4319 lxc_list_add_elem(tmplist
, host_uid_map
);
4320 lxc_list_add_tail(idmap
, tmplist
);
4322 /* idmap will now keep track of that memory. */
4323 container_root_uid
= NULL
;
4324 /* idmap will now keep track of that memory. */
4325 host_uid_map
= NULL
;
4327 tmplist
= malloc(sizeof(*tmplist
));
4330 lxc_list_add_elem(tmplist
, container_root_gid
);
4331 lxc_list_add_tail(idmap
, tmplist
);
4333 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4334 /* idmap will now keep track of that memory. */
4335 container_root_gid
= NULL
;
4337 tmplist
= malloc(sizeof(*tmplist
));
4340 lxc_list_add_elem(tmplist
, host_gid_map
);
4341 lxc_list_add_tail(idmap
, tmplist
);
4343 /* idmap will now keep track of that memory. */
4344 container_root_gid
= NULL
;
4345 /* idmap will now keep track of that memory. */
4346 host_gid_map
= NULL
;
4348 TRACE("Allocated minimal idmapping");
4353 lxc_free_idmap(idmap
);
4356 if (container_root_uid
)
4357 free(container_root_uid
);
4358 if (container_root_gid
)
4359 free(container_root_gid
);
4360 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
4362 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
4368 /* Run a function in a new user namespace.
4369 * The caller's euid/egid will be mapped if it is not already.
4370 * Afaict, userns_exec_1() is only used to operate based on privileges for the
4371 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
4372 * This means we require only to establish a mapping from:
4373 * - the container root {g,u}id as seen from the host > user's host {g,u}id
4374 * - the container root -> some sub{g,u}id
4375 * The former we add, if the user did not specify a mapping. The latter we
4376 * retrieve from the container's configured {g,u}id mappings as it must have been
4377 * there to start the container in the first place.
4379 int userns_exec_1(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4380 const char *fn_name
)
4384 struct userns_fn_data d
;
4385 struct lxc_list
*idmap
;
4386 int ret
= -1, status
= -1;
4392 idmap
= get_minimal_idmap(conf
);
4396 ret
= pipe2(p
, O_CLOEXEC
);
4398 SYSERROR("Failed to create pipe");
4402 d
.fn_name
= fn_name
;
4407 /* Clone child in new user namespace. */
4408 pid
= lxc_raw_clone_cb(run_userns_fn
, &d
, CLONE_NEWUSER
);
4410 ERROR("Failed to clone process in new user namespace");
4417 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4418 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4420 struct lxc_list
*it
;
4422 lxc_list_for_each (it
, idmap
) {
4424 TRACE("Establishing %cid mapping for \"%d\" in new "
4425 "user namespace: nsuid %lu - hostid %lu - range "
4427 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4428 map
->nsid
, map
->hostid
, map
->range
);
4432 /* Set up {g,u}id mapping for user namespace of child process. */
4433 ret
= lxc_map_ids(idmap
, pid
);
4435 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
4439 /* Tell child to proceed. */
4440 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4441 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4450 /* Wait for child to finish. */
4452 status
= wait_for_pid(pid
);
4460 int userns_exec_full(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4461 const char *fn_name
)
4467 struct lxc_list
*cur
;
4468 struct userns_fn_data d
;
4471 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
4472 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
4473 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4478 ret
= pipe2(p
, O_CLOEXEC
);
4480 SYSERROR("opening pipe");
4484 d
.fn_name
= fn_name
;
4489 /* Clone child in new user namespace. */
4490 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
);
4492 ERROR("Failed to clone process in new user namespace");
4502 /* Allocate new {g,u}id map list. */
4503 idmap
= malloc(sizeof(*idmap
));
4506 lxc_list_init(idmap
);
4508 /* Find container root. */
4509 lxc_list_for_each (cur
, &conf
->id_map
) {
4510 struct id_map
*tmpmap
;
4512 tmplist
= malloc(sizeof(*tmplist
));
4516 tmpmap
= malloc(sizeof(*tmpmap
));
4522 memset(tmpmap
, 0, sizeof(*tmpmap
));
4523 memcpy(tmpmap
, cur
->elem
, sizeof(*tmpmap
));
4524 tmplist
->elem
= tmpmap
;
4526 lxc_list_add_tail(idmap
, tmplist
);
4530 if (map
->idtype
== ID_TYPE_UID
)
4531 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
4534 if (map
->idtype
== ID_TYPE_GID
)
4535 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
4541 if (map
->idtype
== ID_TYPE_UID
)
4542 if (container_root_uid
== NULL
)
4543 container_root_uid
= map
;
4545 if (map
->idtype
== ID_TYPE_GID
)
4546 if (container_root_gid
== NULL
)
4547 container_root_gid
= map
;
4550 if (!container_root_uid
|| !container_root_gid
) {
4551 ERROR("No mapping for container root found");
4555 /* Check whether the {g,u}id of the user has a mapping. */
4557 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4559 host_uid_map
= container_root_uid
;
4562 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4564 host_gid_map
= container_root_gid
;
4566 if (!host_uid_map
) {
4567 DEBUG("Failed to find mapping for uid %d", euid
);
4571 if (!host_gid_map
) {
4572 DEBUG("Failed to find mapping for gid %d", egid
);
4576 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4577 /* Add container root to the map. */
4578 tmplist
= malloc(sizeof(*tmplist
));
4581 lxc_list_add_elem(tmplist
, host_uid_map
);
4582 lxc_list_add_tail(idmap
, tmplist
);
4584 /* idmap will now keep track of that memory. */
4585 host_uid_map
= NULL
;
4587 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4588 tmplist
= malloc(sizeof(*tmplist
));
4591 lxc_list_add_elem(tmplist
, host_gid_map
);
4592 lxc_list_add_tail(idmap
, tmplist
);
4594 /* idmap will now keep track of that memory. */
4595 host_gid_map
= NULL
;
4597 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4598 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4599 lxc_list_for_each (cur
, idmap
) {
4601 TRACE("establishing %cid mapping for \"%d\" in new "
4602 "user namespace: nsuid %lu - hostid %lu - range "
4604 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4605 map
->nsid
, map
->hostid
, map
->range
);
4609 /* Set up {g,u}id mapping for user namespace of child process. */
4610 ret
= lxc_map_ids(idmap
, pid
);
4612 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid
);
4616 /* Tell child to proceed. */
4617 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4618 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4627 /* Wait for child to finish. */
4629 ret
= wait_for_pid(pid
);
4632 lxc_free_idmap(idmap
);
4636 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
4638 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
4644 /* not thread-safe, do not use from api without first forking */
4645 static char *getuname(void)
4647 struct passwd pwent
;
4648 struct passwd
*pwentp
= NULL
;
4654 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
4658 buf
= malloc(bufsize
);
4662 ret
= getpwuid_r(geteuid(), &pwent
, buf
, bufsize
, &pwentp
);
4665 WARN("Could not find matched password record.");
4667 ERROR("Failed to get password record - %u", geteuid());
4672 username
= strdup(pwent
.pw_name
);
4678 /* not thread-safe, do not use from api without first forking */
4679 static char *getgname(void)
4682 struct group
*grentp
= NULL
;
4688 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
4692 buf
= malloc(bufsize
);
4696 ret
= getgrgid_r(getegid(), &grent
, buf
, bufsize
, &grentp
);
4699 WARN("Could not find matched group record");
4701 ERROR("Failed to get group record - %u", getegid());
4706 grname
= strdup(grent
.gr_name
);
4712 /* not thread-safe, do not use from api without first forking */
4713 void suggest_default_idmap(void)
4715 char *uname
, *gname
;
4717 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
4731 f
= fopen(subuidfile
, "r");
4733 ERROR("Your system is not configured with subuids");
4739 while (getline(&line
, &len
, f
) != -1) {
4741 size_t no_newline
= 0;
4743 p
= strchr(line
, ':');
4751 if (strcmp(line
, uname
))
4754 p2
= strchr(p
, ':');
4761 no_newline
= strcspn(p2
, "\n");
4762 p2
[no_newline
] = '\0';
4764 if (lxc_safe_uint(p
, &uid
) < 0)
4765 WARN("Could not parse UID");
4766 if (lxc_safe_uint(p2
, &urange
) < 0)
4767 WARN("Could not parse UID range");
4771 f
= fopen(subgidfile
, "r");
4773 ERROR("Your system is not configured with subgids");
4779 while (getline(&line
, &len
, f
) != -1) {
4781 size_t no_newline
= 0;
4783 p
= strchr(line
, ':');
4791 if (strcmp(line
, uname
))
4794 p2
= strchr(p
, ':');
4801 no_newline
= strcspn(p2
, "\n");
4802 p2
[no_newline
] = '\0';
4804 if (lxc_safe_uint(p
, &gid
) < 0)
4805 WARN("Could not parse GID");
4806 if (lxc_safe_uint(p2
, &grange
) < 0)
4807 WARN("Could not parse GID range");
4813 if (!urange
|| !grange
) {
4814 ERROR("You do not have subuids or subgids allocated");
4815 ERROR("Unprivileged containers require subuids and subgids");
4821 ERROR("You must either run as root, or define uid mappings");
4822 ERROR("To pass uid mappings to lxc-create, you could create");
4823 ERROR("~/.config/lxc/default.conf:");
4824 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
4825 ERROR("lxc.idmap = u 0 %u %u", uid
, urange
);
4826 ERROR("lxc.idmap = g 0 %u %u", gid
, grange
);
4832 static void free_cgroup_settings(struct lxc_list
*result
)
4834 struct lxc_list
*iterator
, *next
;
4836 lxc_list_for_each_safe (iterator
, result
, next
) {
4837 lxc_list_del(iterator
);
4843 /* Return the list of cgroup_settings sorted according to the following rules
4844 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4846 struct lxc_list
*sort_cgroup_settings(struct lxc_list
*cgroup_settings
)
4848 struct lxc_list
*result
;
4849 struct lxc_cgroup
*cg
= NULL
;
4850 struct lxc_list
*it
= NULL
, *item
= NULL
, *memsw_limit
= NULL
;
4852 result
= malloc(sizeof(*result
));
4855 lxc_list_init(result
);
4857 /* Iterate over the cgroup settings and copy them to the output list. */
4858 lxc_list_for_each (it
, cgroup_settings
) {
4859 item
= malloc(sizeof(*item
));
4861 free_cgroup_settings(result
);
4865 item
->elem
= it
->elem
;
4867 if (strcmp(cg
->subsystem
, "memory.memsw.limit_in_bytes") == 0) {
4868 /* Store the memsw_limit location */
4870 } else if (strcmp(cg
->subsystem
, "memory.limit_in_bytes") == 0 &&
4871 memsw_limit
!= NULL
) {
4872 /* lxc.cgroup.memory.memsw.limit_in_bytes is found
4873 * before lxc.cgroup.memory.limit_in_bytes, swap these
4875 item
->elem
= memsw_limit
->elem
;
4876 memsw_limit
->elem
= it
->elem
;
4878 lxc_list_add_tail(result
, item
);