1 /* SPDX-License-Identifier: LGPL-2.1+ */
13 #include <linux/loop.h>
15 #include <netinet/in.h>
22 #include <sys/mount.h>
23 #include <sys/param.h>
24 #include <sys/prctl.h>
25 #include <sys/sendfile.h>
26 #include <sys/socket.h>
28 #include <sys/syscall.h>
29 #include <sys/sysmacros.h>
30 #include <sys/types.h>
31 #include <sys/utsname.h>
39 #include "cgroup2_devices.h"
43 #include "confile_utils.h"
48 #include "lxcseccomp.h"
50 #include "memory_utils.h"
51 #include "namespace.h"
54 #include "raw_syscalls.h"
58 #include "storage/overlay.h"
59 #include "syscall_wrappers.h"
65 #include <sys/mkdev.h>
69 #include <sys/statvfs.h>
75 #include <../include/openpty.h>
79 #include <sys/capability.h>
82 #if HAVE_SYS_PERSONALITY_H
83 #include <sys/personality.h>
87 #include "include/strlcat.h"
91 #include <../include/lxcmntent.h>
96 #if !defined(HAVE_PRLIMIT) && defined(HAVE_PRLIMIT64)
97 #include <../include/prlimit.h>
100 lxc_log_define(conf
, lxc
);
102 /* The lxc_conf of the container currently being worked on in an API call.
103 * This is used in the error calls.
106 thread_local
struct lxc_conf
*current_config
;
108 struct lxc_conf
*current_config
;
111 char *lxchook_names
[NUM_LXC_HOOKS
] = {
140 static struct mount_opt mount_opt
[] = {
141 { "async", 1, MS_SYNCHRONOUS
},
142 { "atime", 1, MS_NOATIME
},
143 { "bind", 0, MS_BIND
},
144 { "defaults", 0, 0 },
145 { "dev", 1, MS_NODEV
},
146 { "diratime", 1, MS_NODIRATIME
},
147 { "dirsync", 0, MS_DIRSYNC
},
148 { "exec", 1, MS_NOEXEC
},
149 { "lazytime", 0, MS_LAZYTIME
},
150 { "mand", 0, MS_MANDLOCK
},
151 { "noatime", 0, MS_NOATIME
},
152 { "nodev", 0, MS_NODEV
},
153 { "nodiratime", 0, MS_NODIRATIME
},
154 { "noexec", 0, MS_NOEXEC
},
155 { "nomand", 1, MS_MANDLOCK
},
156 { "norelatime", 1, MS_RELATIME
},
157 { "nostrictatime", 1, MS_STRICTATIME
},
158 { "nosuid", 0, MS_NOSUID
},
159 { "rbind", 0, MS_BIND
|MS_REC
},
160 { "relatime", 0, MS_RELATIME
},
161 { "remount", 0, MS_REMOUNT
},
162 { "ro", 0, MS_RDONLY
},
163 { "rw", 1, MS_RDONLY
},
164 { "strictatime", 0, MS_STRICTATIME
},
165 { "suid", 1, MS_NOSUID
},
166 { "sync", 0, MS_SYNCHRONOUS
},
170 static struct mount_opt propagation_opt
[] = {
171 { "private", 0, MS_PRIVATE
},
172 { "shared", 0, MS_SHARED
},
173 { "slave", 0, MS_SLAVE
},
174 { "unbindable", 0, MS_UNBINDABLE
},
175 { "rprivate", 0, MS_PRIVATE
|MS_REC
},
176 { "rshared", 0, MS_SHARED
|MS_REC
},
177 { "rslave", 0, MS_SLAVE
|MS_REC
},
178 { "runbindable", 0, MS_UNBINDABLE
|MS_REC
},
182 static struct caps_opt caps_opt
[] = {
184 { "chown", CAP_CHOWN
},
185 { "dac_override", CAP_DAC_OVERRIDE
},
186 { "dac_read_search", CAP_DAC_READ_SEARCH
},
187 { "fowner", CAP_FOWNER
},
188 { "fsetid", CAP_FSETID
},
189 { "kill", CAP_KILL
},
190 { "setgid", CAP_SETGID
},
191 { "setuid", CAP_SETUID
},
192 { "setpcap", CAP_SETPCAP
},
193 { "linux_immutable", CAP_LINUX_IMMUTABLE
},
194 { "net_bind_service", CAP_NET_BIND_SERVICE
},
195 { "net_broadcast", CAP_NET_BROADCAST
},
196 { "net_admin", CAP_NET_ADMIN
},
197 { "net_raw", CAP_NET_RAW
},
198 { "ipc_lock", CAP_IPC_LOCK
},
199 { "ipc_owner", CAP_IPC_OWNER
},
200 { "sys_module", CAP_SYS_MODULE
},
201 { "sys_rawio", CAP_SYS_RAWIO
},
202 { "sys_chroot", CAP_SYS_CHROOT
},
203 { "sys_ptrace", CAP_SYS_PTRACE
},
204 { "sys_pacct", CAP_SYS_PACCT
},
205 { "sys_admin", CAP_SYS_ADMIN
},
206 { "sys_boot", CAP_SYS_BOOT
},
207 { "sys_nice", CAP_SYS_NICE
},
208 { "sys_resource", CAP_SYS_RESOURCE
},
209 { "sys_time", CAP_SYS_TIME
},
210 { "sys_tty_config", CAP_SYS_TTY_CONFIG
},
211 { "mknod", CAP_MKNOD
},
212 { "lease", CAP_LEASE
},
213 #ifdef CAP_AUDIT_READ
214 { "audit_read", CAP_AUDIT_READ
},
216 #ifdef CAP_AUDIT_WRITE
217 { "audit_write", CAP_AUDIT_WRITE
},
219 #ifdef CAP_AUDIT_CONTROL
220 { "audit_control", CAP_AUDIT_CONTROL
},
222 { "setfcap", CAP_SETFCAP
},
223 { "mac_override", CAP_MAC_OVERRIDE
},
224 { "mac_admin", CAP_MAC_ADMIN
},
226 { "syslog", CAP_SYSLOG
},
228 #ifdef CAP_WAKE_ALARM
229 { "wake_alarm", CAP_WAKE_ALARM
},
231 #ifdef CAP_BLOCK_SUSPEND
232 { "block_suspend", CAP_BLOCK_SUSPEND
},
237 static struct limit_opt limit_opt
[] = {
242 { "core", RLIMIT_CORE
},
245 { "cpu", RLIMIT_CPU
},
248 { "data", RLIMIT_DATA
},
251 { "fsize", RLIMIT_FSIZE
},
254 { "locks", RLIMIT_LOCKS
},
256 #ifdef RLIMIT_MEMLOCK
257 { "memlock", RLIMIT_MEMLOCK
},
259 #ifdef RLIMIT_MSGQUEUE
260 { "msgqueue", RLIMIT_MSGQUEUE
},
263 { "nice", RLIMIT_NICE
},
266 { "nofile", RLIMIT_NOFILE
},
269 { "nproc", RLIMIT_NPROC
},
272 { "rss", RLIMIT_RSS
},
275 { "rtprio", RLIMIT_RTPRIO
},
278 { "rttime", RLIMIT_RTTIME
},
280 #ifdef RLIMIT_SIGPENDING
281 { "sigpending", RLIMIT_SIGPENDING
},
284 { "stack", RLIMIT_STACK
},
288 static int run_buffer(char *buffer
)
290 __do_free
char *output
= NULL
;
291 __do_lxc_pclose
struct lxc_popen_FILE
*f
= NULL
;
294 f
= lxc_popen(buffer
);
296 return log_error_errno(-1, errno
, "Failed to popen() %s", buffer
);
298 output
= malloc(LXC_LOG_BUFFER_SIZE
);
300 return log_error_errno(-1, ENOMEM
, "Failed to allocate memory for %s", buffer
);
304 return log_error_errno(-1, errno
, "Failed to retrieve underlying file descriptor");
306 for (int i
= 0; i
< 10; i
++) {
309 bytes_read
= lxc_read_nointr(fd
, output
, LXC_LOG_BUFFER_SIZE
- 1);
310 if (bytes_read
> 0) {
311 output
[bytes_read
] = '\0';
312 DEBUG("Script %s produced output: %s", buffer
, output
);
319 ret
= lxc_pclose(move_ptr(f
));
321 return log_error_errno(-1, errno
, "Script exited with error");
322 else if (WIFEXITED(ret
) && WEXITSTATUS(ret
) != 0)
323 return log_error(-1, "Script exited with status %d", WEXITSTATUS(ret
));
324 else if (WIFSIGNALED(ret
))
325 return log_error(-1, "Script terminated by signal %d", WTERMSIG(ret
));
330 int run_script_argv(const char *name
, unsigned int hook_version
,
331 const char *section
, const char *script
,
332 const char *hookname
, char **argv
)
334 __do_free
char *buffer
= NULL
;
338 if (hook_version
== 0)
339 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
340 script
, name
, section
);
342 INFO("Executing script \"%s\" for container \"%s\"", script
, name
);
344 for (i
= 0; argv
&& argv
[i
]; i
++)
345 size
+= strlen(argv
[i
]) + 1;
347 size
+= STRLITERALLEN("exec");
349 size
+= strlen(script
);
355 if (hook_version
== 0) {
356 size
+= strlen(hookname
);
359 size
+= strlen(name
);
362 size
+= strlen(section
);
369 buffer
= malloc(size
);
373 if (hook_version
== 0)
374 buf_pos
= snprintf(buffer
, size
, "exec %s %s %s %s", script
, name
, section
, hookname
);
376 buf_pos
= snprintf(buffer
, size
, "exec %s", script
);
377 if (buf_pos
< 0 || (size_t)buf_pos
>= size
)
378 return log_error_errno(-1, errno
, "Failed to create command line for script \"%s\"", script
);
380 if (hook_version
== 1) {
381 ret
= setenv("LXC_HOOK_TYPE", hookname
, 1);
383 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_HOOK_TYPE=%s", hookname
);
385 TRACE("Set environment variable: LXC_HOOK_TYPE=%s", hookname
);
387 ret
= setenv("LXC_HOOK_SECTION", section
, 1);
389 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_HOOK_SECTION=%s", section
);
390 TRACE("Set environment variable: LXC_HOOK_SECTION=%s", section
);
392 if (strcmp(section
, "net") == 0) {
395 if (!argv
|| !argv
[0])
398 ret
= setenv("LXC_NET_TYPE", argv
[0], 1);
400 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_TYPE=%s", argv
[0]);
401 TRACE("Set environment variable: LXC_NET_TYPE=%s", argv
[0]);
403 parent
= argv
[1] ? argv
[1] : "";
405 if (strcmp(argv
[0], "macvlan") == 0) {
406 ret
= setenv("LXC_NET_PARENT", parent
, 1);
408 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
409 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
410 } else if (strcmp(argv
[0], "phys") == 0) {
411 ret
= setenv("LXC_NET_PARENT", parent
, 1);
413 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
414 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
415 } else if (strcmp(argv
[0], "veth") == 0) {
416 char *peer
= argv
[2] ? argv
[2] : "";
418 ret
= setenv("LXC_NET_PEER", peer
, 1);
420 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PEER=%s", peer
);
421 TRACE("Set environment variable: LXC_NET_PEER=%s", peer
);
423 ret
= setenv("LXC_NET_PARENT", parent
, 1);
425 return log_error_errno(-1, errno
, "Failed to set environment variable: LXC_NET_PARENT=%s", parent
);
426 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
431 for (i
= 0; argv
&& argv
[i
]; i
++) {
432 size_t len
= size
- buf_pos
;
434 ret
= snprintf(buffer
+ buf_pos
, len
, " %s", argv
[i
]);
435 if (ret
< 0 || (size_t)ret
>= len
)
436 return log_error_errno(-1, errno
, "Failed to create command line for script \"%s\"", script
);
440 return run_buffer(buffer
);
443 int run_script(const char *name
, const char *section
, const char *script
, ...)
445 __do_free
char *buffer
= NULL
;
451 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
452 script
, name
, section
);
454 va_start(ap
, script
);
455 while ((p
= va_arg(ap
, char *)))
456 size
+= strlen(p
) + 1;
459 size
+= STRLITERALLEN("exec");
460 size
+= strlen(script
);
461 size
+= strlen(name
);
462 size
+= strlen(section
);
468 buffer
= must_realloc(NULL
, size
);
469 ret
= snprintf(buffer
, size
, "exec %s %s %s", script
, name
, section
);
470 if (ret
< 0 || ret
>= size
)
473 va_start(ap
, script
);
474 while ((p
= va_arg(ap
, char *))) {
475 int len
= size
- ret
;
477 rc
= snprintf(buffer
+ ret
, len
, " %s", p
);
478 if (rc
< 0 || rc
>= len
) {
486 return run_buffer(buffer
);
490 * if rootfs is a directory, then open ${rootfs}/.lxc-keep for writing for
491 * the duration of the container run, to prevent the container from marking
492 * the underlying fs readonly on shutdown. unlink the file immediately so
493 * no name pollution is happens.
494 * don't unlink on NFS to avoid random named stale handles.
495 * return -1 on error.
496 * return -2 if nothing needed to be pinned.
497 * return an open fd (>=0) if we pinned it.
499 int pin_rootfs(const char *rootfs
)
501 __do_free
char *absrootfs
= NULL
;
503 char absrootfspin
[PATH_MAX
];
507 if (rootfs
== NULL
|| strlen(rootfs
) == 0)
510 absrootfs
= realpath(rootfs
, NULL
);
514 ret
= stat(absrootfs
, &s
);
518 if (!S_ISDIR(s
.st_mode
))
521 ret
= snprintf(absrootfspin
, sizeof(absrootfspin
), "%s/.lxc-keep", absrootfs
);
522 if (ret
< 0 || (size_t)ret
>= sizeof(absrootfspin
))
525 fd
= open(absrootfspin
, O_CREAT
| O_RDWR
, S_IWUSR
| S_IRUSR
| O_CLOEXEC
);
529 ret
= fstatfs (fd
, &sfs
);
533 if (sfs
.f_type
== NFS_SUPER_MAGIC
)
534 return log_debug(fd
, "Rootfs on NFS, not unlinking pin file \"%s\"", absrootfspin
);
536 (void)unlink(absrootfspin
);
541 /* If we are asking to remount something, make sure that any NOEXEC etc are
544 unsigned long add_required_remount_flags(const char *s
, const char *d
,
550 unsigned long required_flags
= 0;
558 ret
= statvfs(s
, &sb
);
562 if (flags
& MS_REMOUNT
) {
563 if (sb
.f_flag
& MS_NOSUID
)
564 required_flags
|= MS_NOSUID
;
565 if (sb
.f_flag
& MS_NODEV
)
566 required_flags
|= MS_NODEV
;
567 if (sb
.f_flag
& MS_RDONLY
)
568 required_flags
|= MS_RDONLY
;
569 if (sb
.f_flag
& MS_NOEXEC
)
570 required_flags
|= MS_NOEXEC
;
573 if (sb
.f_flag
& MS_NOATIME
)
574 required_flags
|= MS_NOATIME
;
575 if (sb
.f_flag
& MS_NODIRATIME
)
576 required_flags
|= MS_NODIRATIME
;
577 if (sb
.f_flag
& MS_LAZYTIME
)
578 required_flags
|= MS_LAZYTIME
;
579 if (sb
.f_flag
& MS_RELATIME
)
580 required_flags
|= MS_RELATIME
;
581 if (sb
.f_flag
& MS_STRICTATIME
)
582 required_flags
|= MS_STRICTATIME
;
584 return flags
| required_flags
;
590 static int add_shmount_to_list(struct lxc_conf
*conf
)
592 char new_mount
[PATH_MAX
];
593 /* Offset for the leading '/' since the path_cont
594 * is absolute inside the container.
596 int offset
= 1, ret
= -1;
598 ret
= snprintf(new_mount
, sizeof(new_mount
),
599 "%s %s none bind,create=dir 0 0", conf
->shmount
.path_host
,
600 conf
->shmount
.path_cont
+ offset
);
601 if (ret
< 0 || (size_t)ret
>= sizeof(new_mount
))
604 return add_elem_to_mount_list(new_mount
, conf
);
607 static int lxc_mount_auto_mounts(struct lxc_conf
*conf
, int flags
, struct lxc_handler
*handler
)
614 const char *destination
;
618 } default_mounts
[] = {
619 /* Read-only bind-mounting... In older kernels, doing that
620 * required to do one MS_BIND mount and then
621 * MS_REMOUNT|MS_RDONLY the same one. According to mount(2)
622 * manpage, MS_BIND honors MS_RDONLY from kernel 2.6.26
623 * onwards. However, this apparently does not work on kernel
624 * 3.8. Unfortunately, on that very same kernel, doing the same
625 * trick as above doesn't seem to work either, there one needs
626 * to ALSO specify MS_BIND for the remount, otherwise the
627 * entire fs is remounted read-only or the mount fails because
628 * it's busy... MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for
629 * kernels as low as 2.6.32...
631 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
632 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
633 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys/net", "%r/proc/tty", NULL
, MS_BIND
, NULL
},
634 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys", "%r/proc/sys", NULL
, MS_BIND
, NULL
},
635 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
636 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/tty", "%r/proc/sys/net", NULL
, MS_MOVE
, NULL
},
637 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL
, MS_BIND
, NULL
},
638 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sysrq-trigger", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
639 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_RW
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
640 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RW
, "sysfs", "%r/sys", "sysfs", 0, NULL
},
641 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RO
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
, NULL
},
642 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys", "sysfs", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
643 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/sys", "%r/sys", NULL
, MS_BIND
, NULL
},
644 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, NULL
, "%r/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
645 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys/devices/virtual/net", "sysfs", 0, NULL
},
646 { 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
},
647 { 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
},
648 { 0, 0, NULL
, NULL
, NULL
, 0, NULL
}
651 for (i
= 0; default_mounts
[i
].match_mask
; i
++) {
652 __do_free
char *destination
= NULL
, *source
= NULL
;
654 unsigned long mflags
;
655 if ((flags
& default_mounts
[i
].match_mask
) != default_mounts
[i
].match_flag
)
658 if (default_mounts
[i
].source
) {
659 /* will act like strdup if %r is not present */
660 source
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].source
);
665 if (!default_mounts
[i
].destination
)
666 return log_error(-1, "BUG: auto mounts destination %d was NULL", i
);
668 /* will act like strdup if %r is not present */
669 destination
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].destination
);
673 mflags
= add_required_remount_flags(source
, destination
,
674 default_mounts
[i
].flags
);
675 r
= safe_mount(source
, destination
, default_mounts
[i
].fstype
,
676 mflags
, default_mounts
[i
].options
,
677 conf
->rootfs
.path
? conf
->rootfs
.mount
: NULL
);
679 if (r
< 0 && errno
== ENOENT
) {
680 INFO("Mount source or target for \"%s\" on \"%s\" does not exist. Skipping", source
, destination
);
683 SYSERROR("Failed to mount \"%s\" on \"%s\" with flags %lu", source
, destination
, mflags
);
692 if (flags
& LXC_AUTO_CGROUP_MASK
) {
695 cg_flags
= flags
& (LXC_AUTO_CGROUP_MASK
& ~LXC_AUTO_CGROUP_FORCE
);
696 /* If the type of cgroup mount was not specified, it depends on
697 * the container's capabilities as to what makes sense: if we
698 * have CAP_SYS_ADMIN, the read-only part can be remounted
699 * read-write anyway, so we may as well default to read-write;
700 * then the admin will not be given a false sense of security.
701 * (And if they really want mixed r/o r/w, then they can
702 * explicitly specify :mixed.) OTOH, if the container lacks
703 * CAP_SYS_ADMIN, do only default to :mixed, because then the
704 * container can't remount it read-write.
706 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
|| cg_flags
== LXC_AUTO_CGROUP_FULL_NOSPEC
) {
707 int has_sys_admin
= 0;
709 if (!lxc_list_empty(&conf
->keepcaps
))
710 has_sys_admin
= in_caplist(CAP_SYS_ADMIN
, &conf
->keepcaps
);
712 has_sys_admin
= !in_caplist(CAP_SYS_ADMIN
, &conf
->caps
);
714 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
715 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_RW
: LXC_AUTO_CGROUP_MIXED
;
717 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_FULL_RW
: LXC_AUTO_CGROUP_FULL_MIXED
;
720 if (flags
& LXC_AUTO_CGROUP_FORCE
)
721 cg_flags
|= LXC_AUTO_CGROUP_FORCE
;
723 if (!handler
->cgroup_ops
->mount(handler
->cgroup_ops
,
725 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
727 return log_error_errno(-1, errno
, "Failed to mount \"/sys/fs/cgroup\"");
730 if (flags
& LXC_AUTO_SHMOUNTS_MASK
) {
731 int ret
= add_shmount_to_list(conf
);
733 return log_error(-1, "Failed to add shmount entry to container config");
739 static int setup_utsname(struct utsname
*utsname
)
746 ret
= sethostname(utsname
->nodename
, strlen(utsname
->nodename
));
748 return log_error_errno(-1, errno
, "Failed to set the hostname to \"%s\"",
751 INFO("Set hostname to \"%s\"", utsname
->nodename
);
756 struct dev_symlinks
{
761 static const struct dev_symlinks dev_symlinks
[] = {
762 { "/proc/self/fd", "fd" },
763 { "/proc/self/fd/0", "stdin" },
764 { "/proc/self/fd/1", "stdout" },
765 { "/proc/self/fd/2", "stderr" },
768 static int lxc_setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
774 for (i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
775 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
777 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s",
778 rootfs
->path
? rootfs
->mount
: "", d
->name
);
779 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
782 /* Stat the path first. If we don't get an error accept it as
783 * is and don't try to create it
785 ret
= stat(path
, &s
);
789 ret
= symlink(d
->oldpath
, path
);
790 if (ret
&& errno
!= EEXIST
) {
792 WARN("Failed to create \"%s\". Read-only filesystem", path
);
794 return log_error_errno(-1, errno
, "Failed to create \"%s\"", path
);
801 /* Build a space-separate list of ptys to pass to systemd. */
802 static bool append_ttyname(char **pp
, char *name
)
808 *pp
= malloc(strlen(name
) + strlen("container_ttys=") + 1);
812 sprintf(*pp
, "container_ttys=%s", name
);
816 size
= strlen(*pp
) + strlen(name
) + 2;
817 p
= realloc(*pp
, size
);
822 (void)strlcat(p
, " ", size
);
823 (void)strlcat(p
, name
, size
);
828 static int lxc_setup_ttys(struct lxc_conf
*conf
)
831 const struct lxc_tty_info
*ttys
= &conf
->ttys
;
832 char *ttydir
= ttys
->dir
;
833 char path
[PATH_MAX
], lxcpath
[PATH_MAX
];
835 if (!conf
->rootfs
.path
)
838 for (i
= 0; i
< ttys
->max
; i
++) {
839 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
841 ret
= snprintf(path
, sizeof(path
), "/dev/tty%d", i
+ 1);
842 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
846 /* create dev/lxc/tty%d" */
847 ret
= snprintf(lxcpath
, sizeof(lxcpath
),
848 "/dev/%s/tty%d", ttydir
, i
+ 1);
849 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
852 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
853 if (ret
< 0 && errno
!= EEXIST
) {
854 SYSERROR("Failed to create \"%s\"", lxcpath
);
859 if (ret
< 0 && errno
!= ENOENT
) {
860 SYSERROR("Failed to unlink \"%s\"", path
);
864 ret
= mount(tty
->name
, lxcpath
, "none", MS_BIND
, 0);
866 SYSWARN("Failed to bind mount \"%s\" onto \"%s\"", tty
->name
, lxcpath
);
869 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, lxcpath
);
871 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/tty%d",
873 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
876 ret
= symlink(lxcpath
, path
);
878 return log_error_errno(-1, errno
, "Failed to create symlink \"%s\" -> \"%s\"", path
, lxcpath
);
880 /* If we populated /dev, then we need to create
883 ret
= mknod(path
, S_IFREG
| 0000, 0);
884 if (ret
< 0) /* this isn't fatal, continue */
885 SYSERROR("Failed to create \"%s\"", path
);
887 ret
= mount(tty
->name
, path
, "none", MS_BIND
, 0);
889 SYSERROR("Failed to mount '%s'->'%s'", tty
->name
, path
);
893 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, path
);
896 if (!append_ttyname(&conf
->ttys
.tty_names
, tty
->name
))
897 return log_error(-1, "Error setting up container_ttys string");
900 INFO("Finished setting up %zu /dev/tty<N> device(s)", ttys
->max
);
904 int lxc_allocate_ttys(struct lxc_conf
*conf
)
906 __do_free
struct lxc_terminal_info
*tty_new
= NULL
;
908 struct lxc_tty_info
*ttys
= &conf
->ttys
;
910 /* no tty in the configuration */
914 tty_new
= malloc(sizeof(struct lxc_terminal_info
) * ttys
->max
);
919 for (size_t i
= 0; i
< ttys
->max
; i
++) {
920 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
922 tty
->master
= -EBADF
;
924 ret
= openpty(&tty
->master
, &tty
->slave
, NULL
, NULL
, NULL
);
927 lxc_delete_tty(ttys
);
928 return log_error_errno(-ENOTTY
, ENOTTY
, "Failed to create tty %zu", i
);
931 ret
= ttyname_r(tty
->slave
, tty
->name
, sizeof(tty
->name
));
934 lxc_delete_tty(ttys
);
935 return log_error_errno(-ENOTTY
, ENOTTY
, "Failed to retrieve name of tty %zu slave", i
);
938 DEBUG("Created tty \"%s\" with master fd %d and slave fd %d",
939 tty
->name
, tty
->master
, tty
->slave
);
941 /* Prevent leaking the file descriptors to the container */
942 ret
= fd_cloexec(tty
->master
, true);
944 SYSWARN("Failed to set FD_CLOEXEC flag on master fd %d of tty device \"%s\"",
945 tty
->master
, tty
->name
);
947 ret
= fd_cloexec(tty
->slave
, true);
949 SYSWARN("Failed to set FD_CLOEXEC flag on slave fd %d of tty device \"%s\"",
950 tty
->slave
, tty
->name
);
955 INFO("Finished creating %zu tty devices", ttys
->max
);
956 ttys
->tty
= move_ptr(tty_new
);
960 void lxc_delete_tty(struct lxc_tty_info
*ttys
)
965 for (int i
= 0; i
< ttys
->max
; i
++) {
966 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
967 close_prot_errno_disarm(tty
->master
);
968 close_prot_errno_disarm(tty
->slave
);
971 free_disarm(ttys
->tty
);
974 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
978 struct lxc_conf
*conf
= handler
->conf
;
979 struct lxc_tty_info
*ttys
= &conf
->ttys
;
980 int sock
= handler
->data_sock
[0];
985 for (i
= 0; i
< ttys
->max
; i
++) {
987 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
989 ttyfds
[0] = tty
->master
;
990 ttyfds
[1] = tty
->slave
;
992 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, 2, NULL
, 0);
996 TRACE("Sent tty \"%s\" with master fd %d and slave fd %d to parent",
997 tty
->name
, tty
->master
, tty
->slave
);
1001 SYSERROR("Failed to send %zu ttys to parent", ttys
->max
);
1003 TRACE("Sent %zu ttys to parent", ttys
->max
);
1008 static int lxc_create_ttys(struct lxc_handler
*handler
)
1011 struct lxc_conf
*conf
= handler
->conf
;
1013 ret
= lxc_allocate_ttys(conf
);
1015 ERROR("Failed to allocate ttys");
1019 ret
= lxc_send_ttys_to_parent(handler
);
1021 ERROR("Failed to send ttys to parent");
1025 if (!conf
->is_execute
) {
1026 ret
= lxc_setup_ttys(conf
);
1028 ERROR("Failed to setup ttys");
1033 if (conf
->ttys
.tty_names
) {
1034 ret
= setenv("container_ttys", conf
->ttys
.tty_names
, 1);
1036 SYSERROR("Failed to set \"container_ttys=%s\"", conf
->ttys
.tty_names
);
1042 lxc_delete_tty(&conf
->ttys
);
1047 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1048 * error, log it but don't fail yet.
1050 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
,
1051 int autodevtmpfssize
, const char *lxcpath
)
1053 __do_free
char *path
= NULL
;
1057 char mount_options
[128];
1059 INFO("Preparing \"/dev\"");
1061 /* $(rootfs->mount) + "/dev/pts" + '\0' */
1062 clen
= (rootfs
->path
? strlen(rootfs
->mount
) : 0) + 9;
1063 path
= must_realloc(NULL
, clen
);
1064 sprintf(mount_options
, "size=%d,mode=755", (autodevtmpfssize
!= 0) ? autodevtmpfssize
: 500000);
1065 DEBUG("Using mount options: %s", mount_options
);
1067 ret
= snprintf(path
, clen
, "%s/dev", rootfs
->path
? rootfs
->mount
: "");
1068 if (ret
< 0 || (size_t)ret
>= clen
)
1071 cur_mask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1072 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1073 if (ret
< 0 && errno
!= EEXIST
) {
1074 SYSERROR("Failed to create \"/dev\" directory");
1079 ret
= safe_mount("none", path
, "tmpfs", 0, mount_options
,
1080 rootfs
->path
? rootfs
->mount
: NULL
);
1082 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1085 TRACE("Mounted tmpfs on \"%s\"", path
);
1087 ret
= snprintf(path
, clen
, "%s/dev/pts", rootfs
->path
? rootfs
->mount
: "");
1088 if (ret
< 0 || (size_t)ret
>= clen
) {
1093 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1094 * If not, then create it and exit if that fails...
1096 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1097 if (ret
< 0 && errno
!= EEXIST
) {
1098 SYSERROR("Failed to create directory \"%s\"", path
);
1106 (void)umask(cur_mask
);
1108 INFO("Prepared \"/dev\"");
1112 struct lxc_device_node
{
1119 static const struct lxc_device_node lxc_devices
[] = {
1120 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1121 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1122 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1123 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1124 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1125 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1132 LXC_DEVNODE_PARTIAL
,
1136 static int lxc_fill_autodev(const struct lxc_rootfs
*rootfs
)
1139 char path
[PATH_MAX
];
1141 int use_mknod
= LXC_DEVNODE_MKNOD
;
1143 ret
= snprintf(path
, PATH_MAX
, "%s/dev",
1144 rootfs
->path
? rootfs
->mount
: "");
1145 if (ret
< 0 || ret
>= PATH_MAX
)
1148 /* ignore, just don't try to fill in */
1149 if (!dir_exists(path
))
1152 INFO("Populating \"/dev\"");
1154 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1155 for (i
= 0; i
< sizeof(lxc_devices
) / sizeof(lxc_devices
[0]); i
++) {
1156 char hostpath
[PATH_MAX
];
1157 const struct lxc_device_node
*device
= &lxc_devices
[i
];
1159 ret
= snprintf(path
, PATH_MAX
, "%s/dev/%s",
1160 rootfs
->path
? rootfs
->mount
: "", device
->name
);
1161 if (ret
< 0 || ret
>= PATH_MAX
)
1164 if (use_mknod
>= LXC_DEVNODE_MKNOD
) {
1165 ret
= mknod(path
, device
->mode
, makedev(device
->maj
, device
->min
));
1166 if (ret
== 0 || (ret
< 0 && errno
== EEXIST
)) {
1167 DEBUG("Created device node \"%s\"", path
);
1168 } else if (ret
< 0) {
1170 return log_error_errno(-1, errno
, "Failed to create device node \"%s\"", path
);
1172 use_mknod
= LXC_DEVNODE_BIND
;
1175 /* Device nodes are fully useable. */
1176 if (use_mknod
== LXC_DEVNODE_OPEN
)
1179 if (use_mknod
== LXC_DEVNODE_MKNOD
) {
1181 * - https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=55956b59df336f6738da916dbb520b6e37df9fbd
1182 * - https://lists.linuxfoundation.org/pipermail/containers/2018-June/039176.html
1184 ret
= open(path
, O_RDONLY
| O_CLOEXEC
);
1186 close_prot_errno_disarm(ret
);
1187 /* Device nodes are fully useable. */
1188 use_mknod
= LXC_DEVNODE_OPEN
;
1192 SYSTRACE("Failed to open \"%s\" device", path
);
1193 /* Device nodes are only partially useable. */
1194 use_mknod
= LXC_DEVNODE_PARTIAL
;
1198 if (use_mknod
!= LXC_DEVNODE_PARTIAL
) {
1199 /* If we are dealing with partially functional device
1200 * nodes the prio mknod() call will have created the
1201 * device node so we can use it as a bind-mount target.
1203 ret
= mknod(path
, S_IFREG
| 0000, 0);
1204 if (ret
< 0 && errno
!= EEXIST
)
1205 return log_error_errno(-1, errno
, "Failed to create file \"%s\"", path
);
1208 /* Fallback to bind-mounting the device from the host. */
1209 ret
= snprintf(hostpath
, PATH_MAX
, "/dev/%s", device
->name
);
1210 if (ret
< 0 || ret
>= PATH_MAX
)
1213 ret
= safe_mount(hostpath
, path
, 0, MS_BIND
, NULL
,
1214 rootfs
->path
? rootfs
->mount
: NULL
);
1216 return log_error_errno(-1, errno
, "Failed to bind mount host device node \"%s\" onto \"%s\"",
1218 DEBUG("Bind mounted host device node \"%s\" onto \"%s\"", hostpath
, path
);
1222 INFO("Populated \"/dev\"");
1226 static int lxc_mount_rootfs(struct lxc_conf
*conf
)
1229 struct lxc_storage
*bdev
;
1230 const struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
1232 if (!rootfs
->path
) {
1233 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
1235 return log_error_errno(-1, errno
, "Failed to remount \"/\" MS_REC | MS_SLAVE");
1240 ret
= access(rootfs
->mount
, F_OK
);
1242 return log_error_errno(-1, errno
, "Failed to access to \"%s\". Check it is present",
1245 bdev
= storage_init(conf
);
1247 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1248 rootfs
->path
, rootfs
->mount
,
1249 rootfs
->options
? rootfs
->options
: "(null)");
1251 ret
= bdev
->ops
->mount(bdev
);
1254 return log_error(-1, "Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1255 rootfs
->path
, rootfs
->mount
,
1256 rootfs
->options
? rootfs
->options
: "(null)");
1258 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
1259 rootfs
->path
, rootfs
->mount
,
1260 rootfs
->options
? rootfs
->options
: "(null)");
1265 int lxc_chroot(const struct lxc_rootfs
*rootfs
)
1267 __do_free
char *nroot
= NULL
;
1269 char *root
= rootfs
->mount
;
1271 nroot
= realpath(root
, NULL
);
1273 return log_error_errno(-1, errno
, "Failed to resolve \"%s\"", root
);
1279 /* We could use here MS_MOVE, but in userns this mount is locked and
1282 ret
= mount(nroot
, "/", NULL
, MS_REC
| MS_BIND
, NULL
);
1284 return log_error_errno(-1, errno
, "Failed to mount \"%s\" onto \"/\" as MS_REC | MS_BIND", nroot
);
1286 ret
= mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
);
1288 return log_error_errno(-1, errno
, "Failed to remount \"/\"");
1290 /* The following code cleans up inherited mounts which are not required
1293 * The mountinfo file shows not all mounts, if a few points have been
1294 * unmounted between read operations from the mountinfo. So we need to
1295 * read mountinfo a few times.
1297 * This loop can be skipped if a container uses userns, because all
1298 * inherited mounts are locked and we should live with all this trash.
1301 __do_fclose
FILE *f
= NULL
;
1302 __do_free
char *line
= NULL
;
1303 char *slider1
, *slider2
;
1307 f
= fopen("./proc/self/mountinfo", "re");
1309 return log_error_errno(-1, errno
, "Failed to open \"/proc/self/mountinfo\"");
1311 while (getline(&line
, &len
, f
) > 0) {
1312 for (slider1
= line
, i
= 0; slider1
&& i
< 4; i
++)
1313 slider1
= strchr(slider1
+ 1, ' ');
1318 slider2
= strchr(slider1
+ 1, ' ');
1325 if (strcmp(slider1
+ 1, "/") == 0)
1328 if (strcmp(slider1
+ 1, "/proc") == 0)
1331 ret
= umount2(slider1
, MNT_DETACH
);
1340 /* This also can be skipped if a container uses userns. */
1341 (void)umount2("./proc", MNT_DETACH
);
1343 /* It is weird, but chdir("..") moves us in a new root */
1346 return log_error_errno(-1, errno
, "Failed to chdir(\"..\")");
1350 return log_error_errno(-1, errno
, "Failed to chroot(\".\")");
1355 /* (The following explanation is copied verbatim from the kernel.)
1357 * pivot_root Semantics:
1358 * Moves the root file system of the current process to the directory put_old,
1359 * makes new_root as the new root file system of the current process, and sets
1360 * root/cwd of all processes which had them on the current root to new_root.
1363 * The new_root and put_old must be directories, and must not be on the
1364 * same file system as the current process root. The put_old must be
1365 * underneath new_root, i.e. adding a non-zero number of /.. to the string
1366 * pointed to by put_old must yield the same directory as new_root. No other
1367 * file system may be mounted on put_old. After all, new_root is a mountpoint.
1369 * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
1370 * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
1371 * in this situation.
1374 * - we don't move root/cwd if they are not at the root (reason: if something
1375 * cared enough to change them, it's probably wrong to force them elsewhere)
1376 * - it's okay to pick a root that isn't the root of a file system, e.g.
1377 * /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
1378 * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
1381 static int lxc_pivot_root(const char *rootfs
)
1383 __do_close
int oldroot
= -EBADF
, newroot
= -EBADF
;
1386 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1388 return log_error_errno(-1, errno
, "Failed to open old root directory");
1390 newroot
= open(rootfs
, O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1392 return log_error_errno(-1, errno
, "Failed to open new root directory");
1394 /* change into new root fs */
1395 ret
= fchdir(newroot
);
1397 return log_error_errno(-1, errno
, "Failed to change to new rootfs \"%s\"", rootfs
);
1399 /* pivot_root into our new root fs */
1400 ret
= pivot_root(".", ".");
1402 return log_error_errno(-1, errno
, "Failed to pivot_root()");
1404 /* At this point the old-root is mounted on top of our new-root. To
1405 * unmounted it we must not be chdir'd into it, so escape back to
1408 ret
= fchdir(oldroot
);
1410 return log_error_errno(-1, errno
, "Failed to enter old root directory");
1412 /* Make oldroot rslave to make sure our umounts don't propagate to the
1415 ret
= mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
);
1417 return log_error_errno(-1, errno
, "Failed to make oldroot rslave");
1419 ret
= umount2(".", MNT_DETACH
);
1421 return log_error_errno(-1, errno
, "Failed to detach old root directory");
1423 ret
= fchdir(newroot
);
1425 return log_error_errno(-1, errno
, "Failed to re-enter new root directory");
1427 TRACE("pivot_root(\"%s\") successful", rootfs
);
1432 static int lxc_setup_rootfs_switch_root(const struct lxc_rootfs
*rootfs
)
1435 return log_debug(0, "Container does not have a rootfs");
1437 if (detect_ramfs_rootfs())
1438 return lxc_chroot(rootfs
);
1440 return lxc_pivot_root(rootfs
->mount
);
1443 static const struct id_map
*find_mapped_nsid_entry(struct lxc_conf
*conf
,
1447 struct lxc_list
*it
;
1449 struct id_map
*retmap
= NULL
;
1451 /* Shortcut for container's root mappings. */
1453 if (idtype
== ID_TYPE_UID
)
1454 return conf
->root_nsuid_map
;
1456 if (idtype
== ID_TYPE_GID
)
1457 return conf
->root_nsgid_map
;
1460 lxc_list_for_each(it
, &conf
->id_map
) {
1462 if (map
->idtype
!= idtype
)
1465 if (id
>= map
->nsid
&& id
< map
->nsid
+ map
->range
) {
1474 static int lxc_setup_devpts(struct lxc_conf
*conf
)
1478 char devpts_mntopts
[256];
1479 char *mntopt_sets
[5];
1480 char default_devpts_mntopts
[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
1482 if (conf
->pty_max
<= 0)
1483 return log_debug(0, "No new devpts instance will be mounted since no pts devices are requested");
1485 ret
= snprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%zu",
1486 default_devpts_mntopts
, conf
->pty_max
);
1487 if (ret
< 0 || (size_t)ret
>= sizeof(devpts_mntopts
))
1490 (void)umount2("/dev/pts", MNT_DETACH
);
1492 /* Create mountpoint for devpts instance. */
1493 ret
= mkdir("/dev/pts", 0755);
1494 if (ret
< 0 && errno
!= EEXIST
)
1495 return log_error_errno(-1, errno
, "Failed to create \"/dev/pts\" directory");
1498 mntopt_sets
[0] = devpts_mntopts
;
1500 /* !gid=5 && max= */
1501 mntopt_sets
[1] = devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1503 /* gid=5 && !max= */
1504 mntopt_sets
[2] = default_devpts_mntopts
;
1506 /* !gid=5 && !max= */
1507 mntopt_sets
[3] = default_devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1510 mntopt_sets
[4] = NULL
;
1512 for (ret
= -1, opts
= mntopt_sets
; opts
&& *opts
; opts
++) {
1513 /* mount new devpts instance */
1514 ret
= mount("devpts", "/dev/pts", "devpts", MS_NOSUID
| MS_NOEXEC
, *opts
);
1520 return log_error_errno(-1, errno
, "Failed to mount new devpts instance");
1521 DEBUG("Mount new devpts instance with options \"%s\"", *opts
);
1523 /* Remove any pre-existing /dev/ptmx file. */
1524 ret
= remove("/dev/ptmx");
1526 if (errno
!= ENOENT
)
1527 return log_error_errno(-1, errno
, "Failed to remove existing \"/dev/ptmx\" file");
1529 DEBUG("Removed existing \"/dev/ptmx\" file");
1532 /* Create dummy /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1533 ret
= mknod("/dev/ptmx", S_IFREG
| 0000, 0);
1534 if (ret
< 0 && errno
!= EEXIST
)
1535 return log_error_errno(-1, errno
, "Failed to create dummy \"/dev/ptmx\" file as bind mount target");
1536 DEBUG("Created dummy \"/dev/ptmx\" file as bind mount target");
1538 /* Fallback option: create symlink /dev/ptmx -> /dev/pts/ptmx */
1539 ret
= mount("/dev/pts/ptmx", "/dev/ptmx", NULL
, MS_BIND
, NULL
);
1541 return log_debug(0, "Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1543 /* Fallthrough and try to create a symlink. */
1544 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1546 /* Remove the dummy /dev/ptmx file we created above. */
1547 ret
= remove("/dev/ptmx");
1549 return log_error_errno(-1, errno
, "Failed to remove existing \"/dev/ptmx\"");
1551 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1552 ret
= symlink("/dev/pts/ptmx", "/dev/ptmx");
1554 return log_error_errno(-1, errno
, "Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1555 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1560 static int setup_personality(int persona
)
1564 #if HAVE_SYS_PERSONALITY_H
1568 ret
= personality(persona
);
1570 return log_error_errno(-1, errno
, "Failed to set personality to \"0x%x\"", persona
);
1572 INFO("Set personality to \"0x%x\"", persona
);
1578 static int lxc_setup_dev_console(const struct lxc_rootfs
*rootfs
,
1579 const struct lxc_terminal
*console
)
1582 char path
[PATH_MAX
];
1583 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1585 if (console
->path
&& !strcmp(console
->path
, "none"))
1588 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1589 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1592 /* When we are asked to setup a console we remove any previous
1593 * /dev/console bind-mounts.
1595 if (file_exists(path
)) {
1596 ret
= lxc_unstack_mountpoint(path
, false);
1598 return log_error_errno(-ret
, errno
, "Failed to unmount \"%s\"", path
);
1600 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1603 /* For unprivileged containers autodev or automounts will already have
1604 * taken care of creating /dev/console.
1606 ret
= mknod(path
, S_IFREG
| 0000, 0);
1607 if (ret
< 0 && errno
!= EEXIST
)
1608 return log_error_errno(-errno
, errno
, "Failed to create console");
1610 ret
= fchmod(console
->slave
, S_IXUSR
| S_IXGRP
);
1612 return log_error_errno(-errno
, errno
, "Failed to set mode \"0%o\" to \"%s\"", S_IXUSR
| S_IXGRP
, console
->name
);
1614 ret
= safe_mount(console
->name
, path
, "none", MS_BIND
, 0, rootfs_path
);
1616 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"", console
->name
, path
);
1618 DEBUG("Mounted pts device \"%s\" onto \"%s\"", console
->name
, path
);
1622 static int lxc_setup_ttydir_console(const struct lxc_rootfs
*rootfs
,
1623 const struct lxc_terminal
*console
,
1627 char path
[PATH_MAX
], lxcpath
[PATH_MAX
];
1628 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1630 if (console
->path
&& !strcmp(console
->path
, "none"))
1633 /* create rootfs/dev/<ttydir> directory */
1634 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs_path
, ttydir
);
1635 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1638 ret
= mkdir(path
, 0755);
1639 if (ret
&& errno
!= EEXIST
)
1640 return log_error_errno(-errno
, errno
, "Failed to create \"%s\"", path
);
1641 DEBUG("Created directory for console and tty devices at \"%s\"", path
);
1643 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/dev/%s/console", rootfs_path
, ttydir
);
1644 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1647 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
1648 if (ret
< 0 && errno
!= EEXIST
)
1649 return log_error_errno(-errno
, errno
, "Failed to create \"%s\"", lxcpath
);
1651 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1652 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1655 if (file_exists(path
)) {
1656 ret
= lxc_unstack_mountpoint(path
, false);
1658 return log_error_errno(-ret
, errno
, "Failed to unmount \"%s\"", path
);
1660 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1663 ret
= mknod(path
, S_IFREG
| 0000, 0);
1664 if (ret
< 0 && errno
!= EEXIST
)
1665 return log_error_errno(-errno
, errno
, "Failed to create console");
1667 ret
= fchmod(console
->slave
, S_IXUSR
| S_IXGRP
);
1669 return log_error_errno(-errno
, errno
, "Failed to set mode \"0%o\" to \"%s\"", S_IXUSR
| S_IXGRP
, console
->name
);
1671 /* bind mount console->name to '/dev/<ttydir>/console' */
1672 ret
= safe_mount(console
->name
, lxcpath
, "none", MS_BIND
, 0, rootfs_path
);
1674 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1675 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1677 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
1678 ret
= safe_mount(lxcpath
, path
, "none", MS_BIND
, 0, rootfs_path
);
1680 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1681 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1683 DEBUG("Console has been setup under \"%s\" and mounted to \"%s\"", lxcpath
, path
);
1687 static int lxc_setup_console(const struct lxc_rootfs
*rootfs
,
1688 const struct lxc_terminal
*console
, char *ttydir
)
1692 return lxc_setup_dev_console(rootfs
, console
);
1694 return lxc_setup_ttydir_console(rootfs
, console
, ttydir
);
1697 static int parse_mntopt(char *opt
, unsigned long *flags
, char **data
, size_t size
)
1701 /* If '=' is contained in opt, the option must go into data. */
1702 if (!strchr(opt
, '=')) {
1704 * If opt is found in mount_opt, set or clear flags.
1705 * Otherwise append it to data.
1707 size_t opt_len
= strlen(opt
);
1708 for (struct mount_opt
*mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
1709 size_t mo_name_len
= strlen(mo
->name
);
1711 if (opt_len
== mo_name_len
&& strncmp(opt
, mo
->name
, mo_name_len
) == 0) {
1713 *flags
&= ~mo
->flag
;
1721 if (strlen(*data
)) {
1722 ret
= strlcat(*data
, ",", size
);
1724 return log_error_errno(ret
, errno
, "Failed to append \",\" to %s", *data
);
1727 ret
= strlcat(*data
, opt
, size
);
1729 return log_error_errno(ret
, errno
, "Failed to append \"%s\" to %s", opt
, *data
);
1734 int parse_mntopts(const char *mntopts
, unsigned long *mntflags
, char **mntdata
)
1736 __do_free
char *mntopts_new
= NULL
, *mntopts_dup
= NULL
;
1737 char *mntopt_cur
= NULL
;
1740 if (*mntdata
|| *mntflags
)
1741 return ret_errno(EINVAL
);
1746 mntopts_dup
= strdup(mntopts
);
1748 return ret_errno(ENOMEM
);
1750 size
= strlen(mntopts_dup
) + 1;
1751 mntopts_new
= zalloc(size
);
1753 return ret_errno(ENOMEM
);
1755 lxc_iterate_parts(mntopt_cur
, mntopts_dup
, ",")
1756 if (parse_mntopt(mntopt_cur
, mntflags
, &mntopts_new
, size
) < 0)
1757 return ret_errno(EINVAL
);
1760 *mntdata
= move_ptr(mntopts_new
);
1765 static void parse_propagationopt(char *opt
, unsigned long *flags
)
1767 struct mount_opt
*mo
;
1769 /* If opt is found in propagation_opt, set or clear flags. */
1770 for (mo
= &propagation_opt
[0]; mo
->name
!= NULL
; mo
++) {
1771 if (strncmp(opt
, mo
->name
, strlen(mo
->name
)) != 0)
1775 *flags
&= ~mo
->flag
;
1783 int parse_propagationopts(const char *mntopts
, unsigned long *pflags
)
1785 __do_free
char *s
= NULL
;
1791 s
= strdup(mntopts
);
1793 return log_error_errno(-ENOMEM
, errno
, "Failed to allocate memory");
1796 lxc_iterate_parts(p
, s
, ",")
1797 parse_propagationopt(p
, pflags
);
1802 static void null_endofword(char *word
)
1804 while (*word
&& *word
!= ' ' && *word
!= '\t')
1809 /* skip @nfields spaces in @src */
1810 static char *get_field(char *src
, int nfields
)
1815 for (i
= 0; i
< nfields
; i
++) {
1816 while (*p
&& *p
!= ' ' && *p
!= '\t')
1828 static int mount_entry(const char *fsname
, const char *target
,
1829 const char *fstype
, unsigned long mountflags
,
1830 unsigned long pflags
, const char *data
, bool optional
,
1831 bool dev
, bool relative
, const char *rootfs
)
1834 char srcbuf
[PATH_MAX
];
1835 const char *srcpath
= fsname
;
1841 ret
= snprintf(srcbuf
, sizeof(srcbuf
), "%s/%s", rootfs
? rootfs
: "/", fsname
? fsname
: "");
1842 if (ret
< 0 || ret
>= sizeof(srcbuf
))
1843 return log_error_errno(-1, errno
, "source path is too long");
1847 ret
= safe_mount(srcpath
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
1851 return log_info_errno(0, errno
, "Failed to mount \"%s\" on \"%s\" (optional)",
1852 srcpath
? srcpath
: "(null)", target
);
1854 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"",
1855 srcpath
? srcpath
: "(null)", target
);
1858 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
1860 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount options",
1861 srcpath
? srcpath
: "(none)", target
? target
: "(none)");
1864 if (srcpath
&& statvfs(srcpath
, &sb
) == 0) {
1865 unsigned long required_flags
= 0;
1867 if (sb
.f_flag
& MS_NOSUID
)
1868 required_flags
|= MS_NOSUID
;
1870 if (sb
.f_flag
& MS_NODEV
&& !dev
)
1871 required_flags
|= MS_NODEV
;
1873 if (sb
.f_flag
& MS_RDONLY
)
1874 required_flags
|= MS_RDONLY
;
1876 if (sb
.f_flag
& MS_NOEXEC
)
1877 required_flags
|= MS_NOEXEC
;
1879 DEBUG("Flags for \"%s\" were %lu, required extra flags are %lu",
1880 srcpath
, sb
.f_flag
, required_flags
);
1882 /* If this was a bind mount request, and required_flags
1883 * does not have any flags which are not already in
1884 * mountflags, then skip the remount.
1886 if (!(mountflags
& MS_REMOUNT
) &&
1887 (!(required_flags
& ~mountflags
) && !(mountflags
& MS_RDONLY
))) {
1888 DEBUG("Mountflags already were %lu, skipping remount", mountflags
);
1892 mountflags
|= required_flags
;
1896 ret
= mount(srcpath
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
1899 return log_info_errno(0, errno
, "Failed to mount \"%s\" on \"%s\" (optional)",
1900 srcpath
? srcpath
: "(null)",
1903 return log_error_errno(-1, errno
, "Failed to mount \"%s\" on \"%s\"",
1904 srcpath
? srcpath
: "(null)",
1913 ret
= mount(NULL
, target
, NULL
, pflags
, NULL
);
1916 return log_info_errno(0, errno
, "Failed to change mount propagation for \"%s\" (optional)", target
);
1918 return log_error_errno(-1, errno
, "Failed to change mount propagation for \"%s\" (optional)", target
);
1920 DEBUG("Changed mount propagation for \"%s\"", target
);
1923 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
1924 srcpath
? srcpath
: "(null)", target
, fstype
);
1929 /* Remove "optional", "create=dir", and "create=file" from mntopt */
1930 static void cull_mntent_opt(struct mntent
*mntent
)
1941 for (i
= 0; list
[i
]; i
++) {
1944 p
= strstr(mntent
->mnt_opts
, list
[i
]);
1948 p2
= strchr(p
, ',');
1950 /* no more mntopts, so just chop it here */
1955 memmove(p
, p2
+ 1, strlen(p2
+ 1) + 1);
1959 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
1961 const struct lxc_rootfs
*rootfs
,
1962 const char *lxc_name
, const char *lxc_path
)
1964 __do_free
char *p1
= NULL
;
1968 if (strncmp(mntent
->mnt_type
, "overlay", 7) == 0) {
1969 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
1974 if (hasmntopt(mntent
, "create=dir")) {
1975 ret
= mkdir_p(path
, 0755);
1976 if (ret
< 0 && errno
!= EEXIST
)
1977 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", path
);
1980 if (!hasmntopt(mntent
, "create=file"))
1983 ret
= access(path
, F_OK
);
1993 ret
= mkdir_p(p2
, 0755);
1994 if (ret
< 0 && errno
!= EEXIST
)
1995 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", path
);
1997 ret
= mknod(path
, S_IFREG
| 0000, 0);
1998 if (ret
< 0 && errno
!= EEXIST
)
2004 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2005 * without a rootfs. */
2006 static inline int mount_entry_on_generic(struct mntent
*mntent
,
2008 const struct lxc_rootfs
*rootfs
,
2009 const char *lxc_name
,
2010 const char *lxc_path
)
2012 __do_free
char *mntdata
= NULL
;
2013 unsigned long mntflags
= 0, pflags
= 0;
2014 char *rootfs_path
= NULL
;
2016 bool dev
, optional
, relative
;
2018 optional
= hasmntopt(mntent
, "optional") != NULL
;
2019 dev
= hasmntopt(mntent
, "dev") != NULL
;
2020 relative
= hasmntopt(mntent
, "relative") != NULL
;
2022 if (rootfs
&& rootfs
->path
)
2023 rootfs_path
= rootfs
->mount
;
2025 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
2033 cull_mntent_opt(mntent
);
2035 ret
= parse_propagationopts(mntent
->mnt_opts
, &pflags
);
2039 ret
= parse_mntopts(mntent
->mnt_opts
, &mntflags
, &mntdata
);
2043 ret
= mount_entry(mntent
->mnt_fsname
, path
, mntent
->mnt_type
, mntflags
,
2044 pflags
, mntdata
, optional
, dev
, relative
, rootfs_path
);
2049 static inline int mount_entry_on_systemfs(struct mntent
*mntent
)
2052 char path
[PATH_MAX
];
2054 /* For containers created without a rootfs all mounts are treated as
2055 * absolute paths starting at / on the host.
2057 if (mntent
->mnt_dir
[0] != '/')
2058 ret
= snprintf(path
, sizeof(path
), "/%s", mntent
->mnt_dir
);
2060 ret
= snprintf(path
, sizeof(path
), "%s", mntent
->mnt_dir
);
2061 if (ret
< 0 || ret
>= sizeof(path
))
2064 return mount_entry_on_generic(mntent
, path
, NULL
, NULL
, NULL
);
2067 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
2068 const struct lxc_rootfs
*rootfs
,
2069 const char *lxc_name
,
2070 const char *lxc_path
)
2074 const char *lxcpath
;
2075 char path
[PATH_MAX
];
2078 lxcpath
= lxc_global_config_value("lxc.lxcpath");
2082 /* If rootfs->path is a blockdev path, allow container fstab to use
2083 * <lxcpath>/<name>/rootfs" as the target prefix.
2085 ret
= snprintf(path
, PATH_MAX
, "%s/%s/rootfs", lxcpath
, lxc_name
);
2086 if (ret
< 0 || ret
>= PATH_MAX
)
2089 aux
= strstr(mntent
->mnt_dir
, path
);
2091 offset
= strlen(path
);
2096 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
2098 return log_warn(ret
, "Ignoring mount point \"%s\"", mntent
->mnt_dir
);
2099 offset
= strlen(rootfs
->path
);
2102 ret
= snprintf(path
, PATH_MAX
, "%s/%s", rootfs
->mount
, aux
+ offset
);
2103 if (ret
< 0 || ret
>= PATH_MAX
)
2106 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2109 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
2110 const struct lxc_rootfs
*rootfs
,
2111 const char *lxc_name
,
2112 const char *lxc_path
)
2115 char path
[PATH_MAX
];
2117 /* relative to root mount point */
2118 ret
= snprintf(path
, sizeof(path
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2119 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
2122 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2125 static int mount_file_entries(const struct lxc_conf
*conf
,
2126 const struct lxc_rootfs
*rootfs
, FILE *file
,
2127 const char *lxc_name
, const char *lxc_path
)
2130 struct mntent mntent
;
2132 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2136 ret
= mount_entry_on_systemfs(&mntent
);
2137 else if (mntent
.mnt_dir
[0] != '/')
2138 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2139 lxc_name
, lxc_path
);
2141 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2142 lxc_name
, lxc_path
);
2147 if (!feof(file
) || ferror(file
))
2148 return log_error(-1, "Failed to parse mount entries");
2153 static inline void __auto_endmntent__(FILE **f
)
2159 #define __do_endmntent __attribute__((__cleanup__(__auto_endmntent__)))
2161 static int setup_mount(const struct lxc_conf
*conf
,
2162 const struct lxc_rootfs
*rootfs
, const char *fstab
,
2163 const char *lxc_name
, const char *lxc_path
)
2165 __do_endmntent
FILE *f
= NULL
;
2171 f
= setmntent(fstab
, "re");
2173 return log_error_errno(-1, errno
, "Failed to open \"%s\"", fstab
);
2175 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2177 ERROR("Failed to set up mount entries");
2183 * In order for nested containers to be able to mount /proc and /sys they need
2184 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2186 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2187 * apparmor rule to deny access to them. This is mostly for convenience: The
2188 * container's root user can mount them anyway and thus has access to the two
2189 * file systems. But a non-root user in the container should not be allowed to
2190 * access them as a side effect without explicitly allowing it.
2192 static const char nesting_helpers
[] =
2193 "proc dev/.lxc/proc proc create=dir,optional 0 0\n"
2194 "sys dev/.lxc/sys sysfs create=dir,optional 0 0\n";
2196 FILE *make_anonymous_mount_file(struct lxc_list
*mount
,
2197 bool include_nesting_helpers
)
2199 __do_close
int fd
= -EBADF
;
2203 struct lxc_list
*iterator
;
2205 fd
= memfd_create(".lxc_mount_file", MFD_CLOEXEC
);
2207 char template[] = P_tmpdir
"/.lxc_mount_file_XXXXXX";
2209 if (errno
!= ENOSYS
)
2212 fd
= lxc_make_tmpfile(template, true);
2214 return log_error_errno(NULL
, errno
, "Could not create temporary mount file");
2216 TRACE("Created temporary mount file");
2219 lxc_list_for_each (iterator
, mount
) {
2222 mount_entry
= iterator
->elem
;
2223 len
= strlen(mount_entry
);
2225 ret
= lxc_write_nointr(fd
, mount_entry
, len
);
2229 ret
= lxc_write_nointr(fd
, "\n", 1);
2234 if (include_nesting_helpers
) {
2235 ret
= lxc_write_nointr(fd
, nesting_helpers
,
2236 STRARRAYLEN(nesting_helpers
));
2237 if (ret
!= STRARRAYLEN(nesting_helpers
))
2241 ret
= lseek(fd
, 0, SEEK_SET
);
2245 f
= fdopen(fd
, "re+");
2247 move_fd(fd
); /* Transfer ownership of fd. */
2251 static int setup_mount_entries(const struct lxc_conf
*conf
,
2252 const struct lxc_rootfs
*rootfs
,
2253 struct lxc_list
*mount
, const char *lxc_name
,
2254 const char *lxc_path
)
2256 __do_fclose
FILE *f
= NULL
;
2258 f
= make_anonymous_mount_file(mount
, conf
->lsm_aa_allow_nesting
);
2262 return mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2265 static int parse_cap(const char *cap
)
2269 size_t end
= sizeof(caps_opt
) / sizeof(caps_opt
[0]);
2272 if (strcmp(cap
, "none") == 0)
2275 for (i
= 0; i
< end
; i
++) {
2276 if (strcmp(cap
, caps_opt
[i
].name
))
2279 capid
= caps_opt
[i
].value
;
2284 /* Try to see if it's numeric, so the user may specify
2285 * capabilities that the running kernel knows about but we
2289 capid
= strtol(cap
, &ptr
, 10);
2290 if (!ptr
|| *ptr
!= '\0' || errno
!= 0)
2291 /* not a valid number */
2293 else if (capid
> lxc_caps_last_cap())
2294 /* we have a number but it's not a valid
2302 int in_caplist(int cap
, struct lxc_list
*caps
)
2305 struct lxc_list
*iterator
;
2307 lxc_list_for_each (iterator
, caps
) {
2308 capid
= parse_cap(iterator
->elem
);
2316 static int setup_caps(struct lxc_list
*caps
)
2320 struct lxc_list
*iterator
;
2322 lxc_list_for_each (iterator
, caps
) {
2325 drop_entry
= iterator
->elem
;
2327 capid
= parse_cap(drop_entry
);
2329 return log_error(-1, "unknown capability %s", drop_entry
);
2331 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(capid
), prctl_arg(0),
2332 prctl_arg(0), prctl_arg(0));
2334 return log_error_errno(-1, errno
, "Failed to remove %s capability", drop_entry
);
2335 DEBUG("Dropped %s (%d) capability", drop_entry
, capid
);
2338 DEBUG("Capabilities have been setup");
2342 static int dropcaps_except(struct lxc_list
*caps
)
2344 __do_free
int *caplist
= NULL
;
2345 int i
, capid
, numcaps
;
2347 struct lxc_list
*iterator
;
2349 numcaps
= lxc_caps_last_cap() + 1;
2350 if (numcaps
<= 0 || numcaps
> 200)
2352 TRACE("Found %d capabilities", numcaps
);
2354 /* caplist[i] is 1 if we keep capability i */
2355 caplist
= must_realloc(NULL
, numcaps
* sizeof(int));
2356 memset(caplist
, 0, numcaps
* sizeof(int));
2358 lxc_list_for_each (iterator
, caps
) {
2359 keep_entry
= iterator
->elem
;
2361 capid
= parse_cap(keep_entry
);
2366 return log_error(-1, "Unknown capability %s", keep_entry
);
2368 DEBUG("Keep capability %s (%d)", keep_entry
, capid
);
2372 for (i
= 0; i
< numcaps
; i
++) {
2378 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(i
), prctl_arg(0),
2379 prctl_arg(0), prctl_arg(0));
2381 return log_error_errno(-1, errno
, "Failed to remove capability %d", i
);
2384 DEBUG("Capabilities have been setup");
2388 static int parse_resource(const char *res
)
2394 for (i
= 0; i
< sizeof(limit_opt
) / sizeof(limit_opt
[0]); ++i
)
2395 if (strcmp(res
, limit_opt
[i
].name
) == 0)
2396 return limit_opt
[i
].value
;
2398 /* Try to see if it's numeric, so the user may specify
2399 * resources that the running kernel knows about but
2402 ret
= lxc_safe_int(res
, &resid
);
2409 int setup_resource_limits(struct lxc_list
*limits
, pid_t pid
)
2412 struct lxc_list
*it
;
2413 struct lxc_limit
*lim
;
2415 lxc_list_for_each (it
, limits
) {
2418 resid
= parse_resource(lim
->resource
);
2420 return log_error(-1, "Unknown resource %s", lim
->resource
);
2422 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
2423 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0)
2424 return log_error_errno(-1, errno
, "Failed to set limit %s", lim
->resource
);
2426 TRACE("Setup \"%s\" limit", lim
->resource
);
2428 return log_error(-1, "Cannot set limit \"%s\" as prlimit is missing", lim
->resource
);
2435 int setup_sysctl_parameters(struct lxc_list
*sysctls
)
2437 __do_free
char *tmp
= NULL
;
2438 struct lxc_list
*it
;
2439 struct lxc_sysctl
*elem
;
2441 char filename
[PATH_MAX
] = {0};
2443 lxc_list_for_each (it
, sysctls
) {
2445 tmp
= lxc_string_replace(".", "/", elem
->key
);
2447 return log_error(-1, "Failed to replace key %s", elem
->key
);
2449 ret
= snprintf(filename
, sizeof(filename
), "/proc/sys/%s", tmp
);
2450 if (ret
< 0 || (size_t)ret
>= sizeof(filename
))
2451 return log_error(-1, "Error setting up sysctl parameters path");
2453 ret
= lxc_write_to_file(filename
, elem
->value
,
2454 strlen(elem
->value
), false, 0666);
2456 return log_error_errno(-1, errno
, "Failed to setup sysctl parameters %s to %s",
2457 elem
->key
, elem
->value
);
2463 int setup_proc_filesystem(struct lxc_list
*procs
, pid_t pid
)
2465 __do_free
char *tmp
= NULL
;
2466 struct lxc_list
*it
;
2467 struct lxc_proc
*elem
;
2469 char filename
[PATH_MAX
] = {0};
2471 lxc_list_for_each (it
, procs
) {
2473 tmp
= lxc_string_replace(".", "/", elem
->filename
);
2475 return log_error(-1, "Failed to replace key %s", elem
->filename
);
2477 ret
= snprintf(filename
, sizeof(filename
), "/proc/%d/%s", pid
, tmp
);
2478 if (ret
< 0 || (size_t)ret
>= sizeof(filename
))
2479 return log_error(-1, "Error setting up proc filesystem path");
2481 ret
= lxc_write_to_file(filename
, elem
->value
,
2482 strlen(elem
->value
), false, 0666);
2484 return log_error_errno(-1, errno
, "Failed to setup proc filesystem %s to %s", elem
->filename
, elem
->value
);
2490 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
2492 struct lxc_conf
*lxc_conf_init(void)
2495 struct lxc_conf
*new;
2497 new = malloc(sizeof(*new));
2500 memset(new, 0, sizeof(*new));
2502 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
2503 new->personality
= -1;
2505 new->console
.buffer_size
= 0;
2506 new->console
.log_path
= NULL
;
2507 new->console
.log_fd
= -1;
2508 new->console
.log_size
= 0;
2509 new->console
.path
= NULL
;
2510 new->console
.peer
= -1;
2511 new->console
.proxy
.busy
= -1;
2512 new->console
.proxy
.master
= -1;
2513 new->console
.proxy
.slave
= -1;
2514 new->console
.master
= -1;
2515 new->console
.slave
= -1;
2516 new->console
.name
[0] = '\0';
2517 memset(&new->console
.ringbuf
, 0, sizeof(struct lxc_ringbuf
));
2518 new->maincmd_fd
= -1;
2519 new->monitor_signal_pdeath
= SIGKILL
;
2521 new->rootfs
.mount
= strdup(default_rootfs_mount
);
2522 if (!new->rootfs
.mount
) {
2526 new->rootfs
.managed
= true;
2528 lxc_list_init(&new->cgroup
);
2529 lxc_list_init(&new->cgroup2
);
2530 lxc_list_init(&new->devices
);
2531 lxc_list_init(&new->network
);
2532 lxc_list_init(&new->mount_list
);
2533 lxc_list_init(&new->caps
);
2534 lxc_list_init(&new->keepcaps
);
2535 lxc_list_init(&new->id_map
);
2536 new->root_nsuid_map
= NULL
;
2537 new->root_nsgid_map
= NULL
;
2538 lxc_list_init(&new->includes
);
2539 lxc_list_init(&new->aliens
);
2540 lxc_list_init(&new->environment
);
2541 lxc_list_init(&new->limits
);
2542 lxc_list_init(&new->sysctls
);
2543 lxc_list_init(&new->procs
);
2544 new->hooks_version
= 0;
2545 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++)
2546 lxc_list_init(&new->hooks
[i
]);
2547 lxc_list_init(&new->groups
);
2548 lxc_list_init(&new->state_clients
);
2549 new->lsm_aa_profile
= NULL
;
2550 lxc_list_init(&new->lsm_aa_raw
);
2551 new->lsm_se_context
= NULL
;
2552 new->lsm_se_keyring_context
= NULL
;
2553 new->keyring_disable_session
= false;
2554 new->tmp_umount_proc
= false;
2555 new->tmp_umount_proc
= 0;
2556 new->shmount
.path_host
= NULL
;
2557 new->shmount
.path_cont
= NULL
;
2559 /* if running in a new user namespace, init and COMMAND
2560 * default to running as UID/GID 0 when using lxc-execute */
2563 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
2564 memset(&new->ns_share
, 0, sizeof(char *) * LXC_NS_MAX
);
2565 seccomp_conf_init(new);
2570 int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
2573 __do_close
int fd
= -EBADF
;
2575 char path
[PATH_MAX
];
2577 if (geteuid() != 0 && idtype
== ID_TYPE_GID
) {
2578 __do_close
int setgroups_fd
= -EBADF
;
2580 ret
= snprintf(path
, PATH_MAX
, "/proc/%d/setgroups", pid
);
2581 if (ret
< 0 || ret
>= PATH_MAX
)
2584 setgroups_fd
= open(path
, O_WRONLY
);
2585 if (setgroups_fd
< 0 && errno
!= ENOENT
)
2586 return log_error_errno(-1, errno
, "Failed to open \"%s\"", path
);
2588 if (setgroups_fd
>= 0) {
2589 ret
= lxc_write_nointr(setgroups_fd
, "deny\n",
2590 STRLITERALLEN("deny\n"));
2591 if (ret
!= STRLITERALLEN("deny\n"))
2592 return log_error_errno(-1, errno
, "Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid
);
2593 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid
);
2597 ret
= snprintf(path
, PATH_MAX
, "/proc/%d/%cid_map", pid
,
2598 idtype
== ID_TYPE_UID
? 'u' : 'g');
2599 if (ret
< 0 || ret
>= PATH_MAX
)
2602 fd
= open(path
, O_WRONLY
| O_CLOEXEC
);
2604 return log_error_errno(-1, errno
, "Failed to open \"%s\"", path
);
2606 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
2607 if (ret
!= buf_size
)
2608 return log_error_errno(-1, errno
, "Failed to write %cid mapping to \"%s\"",
2609 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
2614 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2616 * @return 1 if functional binary was found
2617 * @return 0 if binary exists but is lacking privilege
2618 * @return -ENOENT if binary does not exist
2619 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2621 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
2623 __do_free
char *path
= NULL
;
2628 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
2632 path
= on_path(binary
, NULL
);
2636 ret
= stat(path
, &st
);
2640 /* Check if the binary is setuid. */
2641 if (st
.st_mode
& S_ISUID
)
2642 return log_debug(1, "The binary \"%s\" does have the setuid bit set", path
);
2644 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
2645 /* Check if it has the CAP_SETUID capability. */
2646 if ((cap
& CAP_SETUID
) &&
2647 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
2648 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
))
2649 return log_debug(1, "The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path
);
2651 /* Check if it has the CAP_SETGID capability. */
2652 if ((cap
& CAP_SETGID
) &&
2653 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
2654 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
))
2655 return log_debug(1, "The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE and CAP_PERMITTED sets", path
);
2657 /* If we cannot check for file capabilities we need to give the benefit
2658 * of the doubt. Otherwise we might fail even though all the necessary
2659 * file capabilities are set.
2661 DEBUG("Cannot check for file capabilities as full capability support is missing. Manual intervention needed");
2667 int lxc_map_ids_exec_wrapper(void *args
)
2669 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
2673 int lxc_map_ids(struct lxc_list
*idmap
, pid_t pid
)
2678 char cmd_output
[PATH_MAX
];
2680 struct lxc_list
*iterator
;
2682 /* strlen("new@idmap") = 9
2686 * INTTYPE_TO_STRLEN(uint32_t)
2690 * We add some additional space to make sure that we really have
2691 * LXC_IDMAPLEN bytes available for our the {g,u]id mapping.
2693 int ret
= 0, gidmap
= 0, uidmap
= 0;
2694 char mapbuf
[9 + 1 + INTTYPE_TO_STRLEN(uint32_t) + 1 + LXC_IDMAPLEN
] = {0};
2695 bool had_entry
= false, use_shadow
= false;
2696 int hostuid
, hostgid
;
2698 hostuid
= geteuid();
2699 hostgid
= getegid();
2701 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2702 * ranges, then insist that root also reserve ranges in subuid. This
2703 * will protected it by preventing another user from being handed the
2706 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
2707 if (uidmap
== -ENOENT
)
2708 WARN("newuidmap binary is missing");
2710 WARN("newuidmap is lacking necessary privileges");
2712 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
2713 if (gidmap
== -ENOENT
)
2714 WARN("newgidmap binary is missing");
2716 WARN("newgidmap is lacking necessary privileges");
2718 if (uidmap
> 0 && gidmap
> 0) {
2719 DEBUG("Functional newuidmap and newgidmap binary found");
2722 /* In case unprivileged users run application containers via
2723 * execute() or a start*() there are valid cases where they may
2724 * only want to map their own {g,u}id. Let's not block them from
2725 * doing so by requiring geteuid() == 0.
2727 DEBUG("No newuidmap and newgidmap binary found. Trying to "
2728 "write directly with euid %d", hostuid
);
2731 /* Check if we really need to use newuidmap and newgidmap.
2732 * If the user is only remapping his own {g,u}id, we don't need it.
2734 if (use_shadow
&& lxc_list_len(idmap
) == 2) {
2736 lxc_list_for_each(iterator
, idmap
) {
2737 map
= iterator
->elem
;
2738 if (map
->idtype
== ID_TYPE_UID
&& map
->range
== 1 &&
2739 map
->nsid
== hostuid
&& map
->hostid
== hostuid
)
2741 if (map
->idtype
== ID_TYPE_GID
&& map
->range
== 1 &&
2742 map
->nsid
== hostgid
&& map
->hostid
== hostgid
)
2749 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
2750 type
++, u_or_g
= 'g') {
2754 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
2756 lxc_list_for_each(iterator
, idmap
) {
2757 map
= iterator
->elem
;
2758 if (map
->idtype
!= type
)
2763 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
2764 fill
= snprintf(pos
, left
, "%s%lu %lu %lu%s",
2765 use_shadow
? " " : "", map
->nsid
,
2766 map
->hostid
, map
->range
,
2767 use_shadow
? "" : "\n");
2769 * The kernel only takes <= 4k for writes to
2770 * /proc/<pid>/{g,u}id_map
2772 if (fill
<= 0 || fill
>= left
)
2773 return log_error_errno(-1, errno
, "Too many %cid mappings defined", u_or_g
);
2780 /* Try to catch the output of new{g,u}idmap to make debugging
2784 ret
= run_command(cmd_output
, sizeof(cmd_output
),
2785 lxc_map_ids_exec_wrapper
,
2788 return log_error(-1, "new%cidmap failed to write mapping \"%s\": %s", u_or_g
, cmd_output
, mapbuf
);
2789 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g
, mapbuf
);
2791 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
2793 return log_error(-1, "Failed to write mapping: %s", mapbuf
);
2794 TRACE("Wrote mapping \"%s\"", mapbuf
);
2797 memset(mapbuf
, 0, sizeof(mapbuf
));
2803 /* Return the host uid/gid to which the container root is mapped in val.
2804 * Return true if id was found, false otherwise.
2806 static bool get_mapped_rootid(const struct lxc_conf
*conf
, enum idtype idtype
,
2811 struct lxc_list
*it
;
2813 if (idtype
== ID_TYPE_UID
)
2814 nsid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
2816 nsid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
2818 lxc_list_for_each (it
, &conf
->id_map
) {
2820 if (map
->idtype
!= idtype
)
2822 if (map
->nsid
!= nsid
)
2831 int mapped_hostid(unsigned id
, const struct lxc_conf
*conf
, enum idtype idtype
)
2834 struct lxc_list
*it
;
2836 lxc_list_for_each (it
, &conf
->id_map
) {
2838 if (map
->idtype
!= idtype
)
2841 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
2842 return (id
- map
->hostid
) + map
->nsid
;
2848 int find_unmapped_nsid(struct lxc_conf
*conf
, enum idtype idtype
)
2851 struct lxc_list
*it
;
2852 unsigned int freeid
= 0;
2855 lxc_list_for_each (it
, &conf
->id_map
) {
2857 if (map
->idtype
!= idtype
)
2860 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
2861 freeid
= map
->nsid
+ map
->range
;
2869 int chown_mapped_root_exec_wrapper(void *args
)
2871 execvp("lxc-usernsexec", args
);
2875 /* chown_mapped_root: for an unprivileged user with uid/gid X to
2876 * chown a dir to subuid/subgid Y, he needs to run chown as root
2877 * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and
2878 * nsid Y is mapped to hostuid/hostgid X. That way, the container
2879 * root is privileged with respect to hostuid/hostgid X, allowing
2880 * him to do the chown.
2882 int chown_mapped_root(const char *path
, const struct lxc_conf
*conf
)
2884 uid_t rootuid
, rootgid
;
2886 int hostuid
, hostgid
, ret
;
2888 char map1
[100], map2
[100], map3
[100], map4
[100], map5
[100];
2890 const char *args1
[] = {"lxc-usernsexec",
2895 "--", "chown", ugid
, path
,
2897 const char *args2
[] = {"lxc-usernsexec",
2903 "--", "chown", ugid
, path
,
2905 char cmd_output
[PATH_MAX
];
2907 hostuid
= geteuid();
2908 hostgid
= getegid();
2910 if (!get_mapped_rootid(conf
, ID_TYPE_UID
, &val
))
2911 return log_error(-1, "No uid mapping for container root");
2912 rootuid
= (uid_t
)val
;
2914 if (!get_mapped_rootid(conf
, ID_TYPE_GID
, &val
))
2915 return log_error(-1, "No gid mapping for container root");
2916 rootgid
= (gid_t
)val
;
2919 if (chown(path
, rootuid
, rootgid
) < 0)
2920 return log_error(-1, "Error chowning %s", path
);
2926 if (rootuid
== hostuid
)
2927 return log_info(0, "Container root is our uid; no need to chown");
2929 /* save the current gid of "path" */
2930 if (stat(path
, &sb
) < 0)
2931 return log_error(-1, "Error stat %s", path
);
2933 /* Update the path argument in case this was overlayfs. */
2934 args1
[sizeof(args1
) / sizeof(args1
[0]) - 2] = path
;
2935 args2
[sizeof(args2
) / sizeof(args2
[0]) - 2] = path
;
2938 * A file has to be group-owned by a gid mapped into the
2939 * container, or the container won't be privileged over it.
2941 DEBUG("trying to chown \"%s\" to %d", path
, hostgid
);
2942 if (sb
.st_uid
== hostuid
&&
2943 mapped_hostid(sb
.st_gid
, conf
, ID_TYPE_GID
) < 0 &&
2944 chown(path
, -1, hostgid
) < 0)
2945 return log_error(-1, "Failed chgrping %s", path
);
2947 /* "u:0:rootuid:1" */
2948 ret
= snprintf(map1
, 100, "u:0:%d:1", rootuid
);
2949 if (ret
< 0 || ret
>= 100)
2950 return log_error(-1, "Error uid printing map string");
2952 /* "u:hostuid:hostuid:1" */
2953 ret
= snprintf(map2
, 100, "u:%d:%d:1", hostuid
, hostuid
);
2954 if (ret
< 0 || ret
>= 100)
2955 return log_error(-1, "Error uid printing map string");
2957 /* "g:0:rootgid:1" */
2958 ret
= snprintf(map3
, 100, "g:0:%d:1", rootgid
);
2959 if (ret
< 0 || ret
>= 100)
2960 return log_error(-1, "Error gid printing map string");
2962 /* "g:pathgid:rootgid+pathgid:1" */
2963 ret
= snprintf(map4
, 100, "g:%d:%d:1", (gid_t
)sb
.st_gid
,
2964 rootgid
+ (gid_t
)sb
.st_gid
);
2965 if (ret
< 0 || ret
>= 100)
2966 return log_error(-1, "Error gid printing map string");
2968 /* "g:hostgid:hostgid:1" */
2969 ret
= snprintf(map5
, 100, "g:%d:%d:1", hostgid
, hostgid
);
2970 if (ret
< 0 || ret
>= 100)
2971 return log_error(-1, "Error gid printing map string");
2973 /* "0:pathgid" (chown) */
2974 ret
= snprintf(ugid
, 100, "0:%d", (gid_t
)sb
.st_gid
);
2975 if (ret
< 0 || ret
>= 100)
2976 return log_error(-1, "Error owner printing format string for chown");
2978 if (hostgid
== sb
.st_gid
)
2979 ret
= run_command(cmd_output
, sizeof(cmd_output
),
2980 chown_mapped_root_exec_wrapper
,
2983 ret
= run_command(cmd_output
, sizeof(cmd_output
),
2984 chown_mapped_root_exec_wrapper
,
2987 ERROR("lxc-usernsexec failed: %s", cmd_output
);
2992 /* NOTE: Must not be called from inside the container namespace! */
2993 int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
2997 mounted
= lxc_mount_proc_if_needed(conf
->rootfs
.path
? conf
->rootfs
.mount
: "");
2998 if (mounted
== -1) {
2999 SYSERROR("Failed to mount proc in the container");
3000 /* continue only if there is no rootfs */
3001 if (conf
->rootfs
.path
)
3003 } else if (mounted
== 1) {
3004 conf
->tmp_umount_proc
= true;
3010 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
3012 if (!lxc_conf
->tmp_umount_proc
)
3015 (void)umount2("/proc", MNT_DETACH
);
3016 lxc_conf
->tmp_umount_proc
= false;
3019 /* Walk /proc/mounts and change any shared entries to slave. */
3020 void remount_all_slave(void)
3022 __do_free
char *line
= NULL
;
3023 __do_fclose
FILE *f
= NULL
;
3024 __do_close
int memfd
= -EBADF
, mntinfo_fd
= -EBADF
;
3029 mntinfo_fd
= open("/proc/self/mountinfo", O_RDONLY
| O_CLOEXEC
);
3030 if (mntinfo_fd
< 0) {
3031 SYSERROR("Failed to open \"/proc/self/mountinfo\"");
3035 memfd
= memfd_create(".lxc_mountinfo", MFD_CLOEXEC
);
3037 char template[] = P_tmpdir
"/.lxc_mountinfo_XXXXXX";
3039 if (errno
!= ENOSYS
) {
3040 SYSERROR("Failed to create temporary in-memory file");
3044 memfd
= lxc_make_tmpfile(template, true);
3046 WARN("Failed to create temporary file");
3052 copied
= lxc_sendfile_nointr(memfd
, mntinfo_fd
, NULL
, LXC_SENDFILE_MAX
);
3057 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
3061 ret
= lseek(memfd
, 0, SEEK_SET
);
3063 SYSERROR("Failed to reset file descriptor offset");
3067 f
= fdopen(memfd
, "re");
3069 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark all shared. Continuing");
3074 * After a successful fdopen() memfd will be closed when calling
3075 * fclose(f). Calling close(memfd) afterwards is undefined.
3079 while (getline(&line
, &len
, f
) != -1) {
3080 char *opts
, *target
;
3082 target
= get_field(line
, 4);
3086 opts
= get_field(target
, 2);
3090 null_endofword(opts
);
3091 if (!strstr(opts
, "shared"))
3094 null_endofword(target
);
3095 ret
= mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
);
3097 SYSERROR("Failed to make \"%s\" MS_SLAVE", target
);
3098 ERROR("Continuing...");
3101 TRACE("Remounted \"%s\" as MS_SLAVE", target
);
3103 TRACE("Remounted all mount table entries as MS_SLAVE");
3106 static int lxc_execute_bind_init(struct lxc_handler
*handler
)
3110 char path
[PATH_MAX
], destpath
[PATH_MAX
];
3111 struct lxc_conf
*conf
= handler
->conf
;
3113 /* If init exists in the container, don't bind mount a static one */
3114 p
= choose_init(conf
->rootfs
.mount
);
3116 __do_free
char *old
= p
;
3118 p
= strdup(old
+ strlen(conf
->rootfs
.mount
));
3122 INFO("Found existing init at \"%s\"", p
);
3126 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3127 if (ret
< 0 || ret
>= PATH_MAX
)
3130 if (!file_exists(path
))
3131 return log_error_errno(-1, errno
, "The file \"%s\" does not exist on host", path
);
3133 ret
= snprintf(destpath
, PATH_MAX
, "%s" P_tmpdir
"%s", conf
->rootfs
.mount
, "/.lxc-init");
3134 if (ret
< 0 || ret
>= PATH_MAX
)
3137 if (!file_exists(destpath
)) {
3138 ret
= mknod(destpath
, S_IFREG
| 0000, 0);
3139 if (ret
< 0 && errno
!= EEXIST
)
3140 return log_error_errno(-1, errno
, "Failed to create dummy \"%s\" file as bind mount target", destpath
);
3143 ret
= safe_mount(path
, destpath
, "none", MS_BIND
, NULL
, conf
->rootfs
.mount
);
3145 return log_error_errno(-1, errno
, "Failed to bind mount lxc.init.static into container");
3147 p
= strdup(destpath
+ strlen(conf
->rootfs
.mount
));
3151 INFO("Bind mounted lxc.init.static into container at \"%s\"", path
);
3153 ((struct execute_args
*)handler
->data
)->init_fd
= -1;
3154 ((struct execute_args
*)handler
->data
)->init_path
= p
;
3158 /* This does the work of remounting / if it is shared, calling the container
3159 * pre-mount hooks, and mounting the rootfs.
3161 int lxc_setup_rootfs_prepare_root(struct lxc_conf
*conf
, const char *name
,
3162 const char *lxcpath
)
3166 if (conf
->rootfs_setup
) {
3167 const char *path
= conf
->rootfs
.mount
;
3169 /* The rootfs was set up in another namespace. bind-mount it to
3170 * give us a mount in our own ns so we can pivot_root to it
3172 ret
= mount(path
, path
, "rootfs", MS_BIND
, NULL
);
3174 return log_error(-1, "Failed to bind mount container / onto itself");
3176 return log_trace(0, "Bind mounted container / onto itself");
3179 remount_all_slave();
3181 ret
= run_lxc_hooks(name
, "pre-mount", conf
, NULL
);
3183 return log_error(-1, "Failed to run pre-mount hooks");
3185 ret
= lxc_mount_rootfs(conf
);
3187 return log_error(-1, "Failed to setup rootfs for");
3189 conf
->rootfs_setup
= true;
3193 static bool verify_start_hooks(struct lxc_conf
*conf
)
3195 char path
[PATH_MAX
];
3196 struct lxc_list
*it
;
3198 lxc_list_for_each (it
, &conf
->hooks
[LXCHOOK_START
]) {
3200 char *hookname
= it
->elem
;
3202 ret
= snprintf(path
, PATH_MAX
, "%s%s",
3203 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
3205 if (ret
< 0 || ret
>= PATH_MAX
)
3208 ret
= access(path
, X_OK
);
3210 return log_error_errno(false, errno
, "Start hook \"%s\" not found in container", hookname
);
3218 static bool execveat_supported(void)
3220 lxc_raw_execveat(-1, "", NULL
, NULL
, AT_EMPTY_PATH
);
3221 if (errno
== ENOSYS
)
3227 static int lxc_setup_boot_id(void)
3230 const char *boot_id_path
= "/proc/sys/kernel/random/boot_id";
3231 const char *mock_boot_id_path
= "/dev/.lxc-boot-id";
3234 if (access(boot_id_path
, F_OK
))
3237 memset(&n
, 0, sizeof(n
));
3238 if (lxc_id128_randomize(&n
)) {
3239 SYSERROR("Failed to generate random data for uuid");
3243 ret
= lxc_id128_write(mock_boot_id_path
, n
);
3245 SYSERROR("Failed to write uuid to %s", mock_boot_id_path
);
3249 ret
= chmod(mock_boot_id_path
, 0444);
3251 SYSERROR("Failed to chown %s", mock_boot_id_path
);
3252 (void)unlink(mock_boot_id_path
);
3256 ret
= mount(mock_boot_id_path
, boot_id_path
, NULL
, MS_BIND
, NULL
);
3258 SYSERROR("Failed to mount %s to %s", mock_boot_id_path
,
3260 (void)unlink(mock_boot_id_path
);
3264 ret
= mount(NULL
, boot_id_path
, NULL
,
3265 (MS_BIND
| MS_REMOUNT
| MS_RDONLY
| MS_NOSUID
| MS_NOEXEC
|
3269 SYSERROR("Failed to remount %s read-only", boot_id_path
);
3270 (void)unlink(mock_boot_id_path
);
3277 int lxc_setup(struct lxc_handler
*handler
)
3280 const char *lxcpath
= handler
->lxcpath
, *name
= handler
->name
;
3281 struct lxc_conf
*lxc_conf
= handler
->conf
;
3282 char *keyring_context
= NULL
;
3284 ret
= lxc_setup_rootfs_prepare_root(lxc_conf
, name
, lxcpath
);
3286 return log_error(-1, "Failed to setup rootfs");
3288 if (handler
->nsfd
[LXC_NS_UTS
] == -EBADF
) {
3289 ret
= setup_utsname(lxc_conf
->utsname
);
3291 return log_error(-1, "Failed to setup the utsname %s", name
);
3294 if (!lxc_conf
->keyring_disable_session
) {
3295 if (lxc_conf
->lsm_se_keyring_context
) {
3296 keyring_context
= lxc_conf
->lsm_se_keyring_context
;
3297 } else if (lxc_conf
->lsm_se_context
) {
3298 keyring_context
= lxc_conf
->lsm_se_context
;
3301 ret
= lxc_setup_keyring(keyring_context
);
3306 if (handler
->ns_clone_flags
& CLONE_NEWNET
) {
3307 ret
= lxc_setup_network_in_child_namespaces(lxc_conf
,
3308 &lxc_conf
->network
);
3310 return log_error(-1, "Failed to setup network");
3312 ret
= lxc_network_send_name_and_ifindex_to_parent(handler
);
3314 return log_error(-1, "Failed to send network device names and ifindices to parent");
3317 if (lxc_conf
->autodev
> 0) {
3318 ret
= mount_autodev(name
, &lxc_conf
->rootfs
, lxc_conf
->autodevtmpfssize
, lxcpath
);
3320 return log_error(-1, "Failed to mount \"/dev\"");
3323 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
3324 * need to wait until other stuff has finished.
3326 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
, handler
);
3328 return log_error(-1, "Failed to setup first automatic mounts");
3330 ret
= setup_mount(lxc_conf
, &lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
);
3332 return log_error(-1, "Failed to setup mounts");
3334 if (!lxc_list_empty(&lxc_conf
->mount_list
)) {
3335 ret
= setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
,
3336 &lxc_conf
->mount_list
, name
, lxcpath
);
3338 return log_error(-1, "Failed to setup mount entries");
3341 if (lxc_conf
->is_execute
) {
3342 if (execveat_supported()) {
3344 char path
[PATH_MAX
];
3346 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3347 if (ret
< 0 || ret
>= PATH_MAX
)
3348 return log_error(-1, "Path to init.lxc.static too long");
3350 fd
= open(path
, O_PATH
| O_CLOEXEC
);
3352 return log_error_errno(-1, errno
, "Unable to open lxc.init.static");
3354 ((struct execute_args
*)handler
->data
)->init_fd
= fd
;
3355 ((struct execute_args
*)handler
->data
)->init_path
= NULL
;
3357 ret
= lxc_execute_bind_init(handler
);
3359 return log_error(-1, "Failed to bind-mount the lxc init system");
3363 /* Now mount only cgroups, if wanted. Before, /sys could not have been
3364 * mounted. It is guaranteed to be mounted now either through
3365 * automatically or via fstab entries.
3367 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
, handler
);
3369 return log_error(-1, "Failed to setup remaining automatic mounts");
3371 ret
= run_lxc_hooks(name
, "mount", lxc_conf
, NULL
);
3373 return log_error(-1, "Failed to run mount hooks");
3375 if (lxc_conf
->autodev
> 0) {
3376 ret
= run_lxc_hooks(name
, "autodev", lxc_conf
, NULL
);
3378 return log_error(-1, "Failed to run autodev hooks");
3380 ret
= lxc_fill_autodev(&lxc_conf
->rootfs
);
3382 return log_error(-1, "Failed to populate \"/dev\"");
3385 /* Make sure any start hooks are in the container */
3386 if (!verify_start_hooks(lxc_conf
))
3387 return log_error(-1, "Failed to verify start hooks");
3389 ret
= lxc_setup_console(&lxc_conf
->rootfs
, &lxc_conf
->console
,
3390 lxc_conf
->ttys
.dir
);
3392 return log_error(-1, "Failed to setup console");
3394 ret
= lxc_setup_dev_symlinks(&lxc_conf
->rootfs
);
3396 return log_error(-1, "Failed to setup \"/dev\" symlinks");
3398 ret
= lxc_create_tmp_proc_mount(lxc_conf
);
3400 return log_error(-1, "Failed to \"/proc\" LSMs");
3402 ret
= lxc_setup_rootfs_switch_root(&lxc_conf
->rootfs
);
3404 return log_error(-1, "Failed to pivot root into rootfs");
3406 /* Setting the boot-id is best-effort for now. */
3407 if (lxc_conf
->autodev
> 0)
3408 (void)lxc_setup_boot_id();
3410 ret
= lxc_setup_devpts(lxc_conf
);
3412 return log_error(-1, "Failed to setup new devpts instance");
3414 ret
= lxc_create_ttys(handler
);
3418 ret
= setup_personality(lxc_conf
->personality
);
3420 return log_error(-1, "Failed to set personality");
3422 /* Set sysctl value to a path under /proc/sys as determined from the
3423 * key. For e.g. net.ipv4.ip_forward translated to
3424 * /proc/sys/net/ipv4/ip_forward.
3426 if (!lxc_list_empty(&lxc_conf
->sysctls
)) {
3427 ret
= setup_sysctl_parameters(&lxc_conf
->sysctls
);
3429 return log_error(-1, "Failed to setup sysctl parameters");
3432 if (!lxc_list_empty(&lxc_conf
->keepcaps
)) {
3433 if (!lxc_list_empty(&lxc_conf
->caps
))
3434 return log_error(-1, "Container requests lxc.cap.drop and lxc.cap.keep: either use lxc.cap.drop or lxc.cap.keep, not both");
3436 if (dropcaps_except(&lxc_conf
->keepcaps
))
3437 return log_error(-1, "Failed to keep capabilities");
3438 } else if (setup_caps(&lxc_conf
->caps
)) {
3439 return log_error(-1, "Failed to drop capabilities");
3442 NOTICE("The container \"%s\" is set up", name
);
3447 int run_lxc_hooks(const char *name
, char *hookname
, struct lxc_conf
*conf
,
3450 struct lxc_list
*it
;
3453 for (which
= 0; which
< NUM_LXC_HOOKS
; which
++) {
3454 if (strcmp(hookname
, lxchook_names
[which
]) == 0)
3458 if (which
>= NUM_LXC_HOOKS
)
3461 lxc_list_for_each (it
, &conf
->hooks
[which
]) {
3463 char *hook
= it
->elem
;
3465 ret
= run_script_argv(name
, conf
->hooks_version
, "lxc", hook
,
3474 int lxc_clear_config_caps(struct lxc_conf
*c
)
3476 struct lxc_list
*it
, *next
;
3478 lxc_list_for_each_safe (it
, &c
->caps
, next
) {
3487 static int lxc_free_idmap(struct lxc_list
*id_map
)
3489 struct lxc_list
*it
, *next
;
3491 lxc_list_for_each_safe (it
, id_map
, next
) {
3500 int lxc_clear_idmaps(struct lxc_conf
*c
)
3502 return lxc_free_idmap(&c
->id_map
);
3505 int lxc_clear_config_keepcaps(struct lxc_conf
*c
)
3507 struct lxc_list
*it
, *next
;
3509 lxc_list_for_each_safe (it
, &c
->keepcaps
, next
) {
3518 int lxc_clear_namespace(struct lxc_conf
*c
)
3521 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
3522 free(c
->ns_share
[i
]);
3523 c
->ns_share
[i
] = NULL
;
3528 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
, int version
)
3530 char *global_token
, *namespaced_token
;
3531 size_t namespaced_token_len
;
3532 struct lxc_list
*it
, *next
, *list
;
3533 const char *k
= key
;
3536 if (version
== CGROUP2_SUPER_MAGIC
) {
3537 global_token
= "lxc.cgroup2";
3538 namespaced_token
= "lxc.cgroup2.";
3539 namespaced_token_len
= STRLITERALLEN("lxc.cgroup2.");
3541 } else if (version
== CGROUP_SUPER_MAGIC
) {
3542 global_token
= "lxc.cgroup";
3543 namespaced_token
= "lxc.cgroup.";
3544 namespaced_token_len
= STRLITERALLEN("lxc.cgroup.");
3550 if (strcmp(key
, global_token
) == 0)
3552 else if (strncmp(key
, namespaced_token
, namespaced_token_len
) == 0)
3553 k
+= namespaced_token_len
;
3557 lxc_list_for_each_safe (it
, list
, next
) {
3558 struct lxc_cgroup
*cg
= it
->elem
;
3560 if (!all
&& strcmp(cg
->subsystem
, k
) != 0)
3564 free(cg
->subsystem
);
3573 static void lxc_clear_devices(struct lxc_conf
*conf
)
3575 struct lxc_list
*list
= &conf
->devices
;
3576 struct lxc_list
*it
, *next
;
3578 lxc_list_for_each_safe(it
, list
, next
) {
3584 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
3586 struct lxc_list
*it
, *next
;
3587 const char *k
= NULL
;
3590 if (strcmp(key
, "lxc.limit") == 0 || strcmp(key
, "lxc.prlimit") == 0)
3592 else if (strncmp(key
, "lxc.limit.", STRLITERALLEN("lxc.limit.")) == 0)
3593 k
= key
+ STRLITERALLEN("lxc.limit.");
3594 else if (strncmp(key
, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")) == 0)
3595 k
= key
+ STRLITERALLEN("lxc.prlimit.");
3599 lxc_list_for_each_safe (it
, &c
->limits
, next
) {
3600 struct lxc_limit
*lim
= it
->elem
;
3602 if (!all
&& strcmp(lim
->resource
, k
) != 0)
3606 free(lim
->resource
);
3614 int lxc_clear_sysctls(struct lxc_conf
*c
, const char *key
)
3616 struct lxc_list
*it
, *next
;
3617 const char *k
= NULL
;
3620 if (strcmp(key
, "lxc.sysctl") == 0)
3622 else if (strncmp(key
, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")) == 0)
3623 k
= key
+ STRLITERALLEN("lxc.sysctl.");
3627 lxc_list_for_each_safe (it
, &c
->sysctls
, next
) {
3628 struct lxc_sysctl
*elem
= it
->elem
;
3630 if (!all
&& strcmp(elem
->key
, k
) != 0)
3643 int lxc_clear_procs(struct lxc_conf
*c
, const char *key
)
3645 struct lxc_list
*it
, *next
;
3646 const char *k
= NULL
;
3649 if (strcmp(key
, "lxc.proc") == 0)
3651 else if (strncmp(key
, "lxc.proc.", STRLITERALLEN("lxc.proc.")) == 0)
3652 k
= key
+ STRLITERALLEN("lxc.proc.");
3656 lxc_list_for_each_safe (it
, &c
->procs
, next
) {
3657 struct lxc_proc
*proc
= it
->elem
;
3659 if (!all
&& strcmp(proc
->filename
, k
) != 0)
3663 free(proc
->filename
);
3672 int lxc_clear_groups(struct lxc_conf
*c
)
3674 struct lxc_list
*it
, *next
;
3676 lxc_list_for_each_safe (it
, &c
->groups
, next
) {
3685 int lxc_clear_environment(struct lxc_conf
*c
)
3687 struct lxc_list
*it
, *next
;
3689 lxc_list_for_each_safe (it
, &c
->environment
, next
) {
3698 int lxc_clear_mount_entries(struct lxc_conf
*c
)
3700 struct lxc_list
*it
, *next
;
3702 lxc_list_for_each_safe (it
, &c
->mount_list
, next
) {
3711 int lxc_clear_automounts(struct lxc_conf
*c
)
3717 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
3720 struct lxc_list
*it
, *next
;
3721 const char *k
= NULL
;
3722 bool all
= false, done
= false;
3724 if (strcmp(key
, "lxc.hook") == 0)
3726 else if (strncmp(key
, "lxc.hook.", STRLITERALLEN("lxc.hook.")) == 0)
3727 k
= key
+ STRLITERALLEN("lxc.hook.");
3731 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++) {
3732 if (all
|| strcmp(k
, lxchook_names
[i
]) == 0) {
3733 lxc_list_for_each_safe (it
, &c
->hooks
[i
], next
) {
3744 return log_error(-1, "Invalid hook key: %s", key
);
3749 static inline void lxc_clear_aliens(struct lxc_conf
*conf
)
3751 struct lxc_list
*it
, *next
;
3753 lxc_list_for_each_safe (it
, &conf
->aliens
, next
) {
3760 void lxc_clear_includes(struct lxc_conf
*conf
)
3762 struct lxc_list
*it
, *next
;
3764 lxc_list_for_each_safe (it
, &conf
->includes
, next
) {
3771 int lxc_clear_apparmor_raw(struct lxc_conf
*c
)
3773 struct lxc_list
*it
, *next
;
3775 lxc_list_for_each_safe (it
, &c
->lsm_aa_raw
, next
) {
3784 void lxc_conf_free(struct lxc_conf
*conf
)
3789 if (current_config
== conf
)
3790 current_config
= NULL
;
3791 lxc_terminal_conf_free(&conf
->console
);
3792 free(conf
->rootfs
.mount
);
3793 free(conf
->rootfs
.bdev_type
);
3794 free(conf
->rootfs
.options
);
3795 free(conf
->rootfs
.path
);
3796 free(conf
->rootfs
.data
);
3797 free(conf
->logfile
);
3798 if (conf
->logfd
!= -1)
3800 free(conf
->utsname
);
3801 free(conf
->ttys
.dir
);
3802 free(conf
->ttys
.tty_names
);
3805 free(conf
->execute_cmd
);
3806 free(conf
->init_cmd
);
3807 free(conf
->init_cwd
);
3808 free(conf
->unexpanded_config
);
3810 lxc_free_networks(&conf
->network
);
3811 free(conf
->lsm_aa_profile
);
3812 free(conf
->lsm_aa_profile_computed
);
3813 free(conf
->lsm_se_context
);
3814 lxc_seccomp_free(&conf
->seccomp
);
3815 lxc_clear_config_caps(conf
);
3816 lxc_clear_config_keepcaps(conf
);
3817 lxc_clear_cgroups(conf
, "lxc.cgroup", CGROUP_SUPER_MAGIC
);
3818 lxc_clear_cgroups(conf
, "lxc.cgroup2", CGROUP2_SUPER_MAGIC
);
3819 lxc_clear_devices(conf
);
3820 lxc_clear_cgroup2_devices(conf
);
3821 lxc_clear_hooks(conf
, "lxc.hook");
3822 lxc_clear_mount_entries(conf
);
3823 lxc_clear_idmaps(conf
);
3824 lxc_clear_groups(conf
);
3825 lxc_clear_includes(conf
);
3826 lxc_clear_aliens(conf
);
3827 lxc_clear_environment(conf
);
3828 lxc_clear_limits(conf
, "lxc.prlimit");
3829 lxc_clear_sysctls(conf
, "lxc.sysctl");
3830 lxc_clear_procs(conf
, "lxc.proc");
3831 lxc_clear_apparmor_raw(conf
);
3832 lxc_clear_namespace(conf
);
3833 free(conf
->cgroup_meta
.dir
);
3834 free(conf
->cgroup_meta
.controllers
);
3835 free(conf
->shmount
.path_host
);
3836 free(conf
->shmount
.path_cont
);
3840 struct userns_fn_data
{
3842 const char *fn_name
;
3847 static int run_userns_fn(void *data
)
3851 struct userns_fn_data
*d
= data
;
3853 /* Close write end of the pipe. */
3856 /* Wait for parent to finish establishing a new mapping in the user
3857 * namespace we are executing in.
3859 ret
= lxc_read_nointr(d
->p
[0], &c
, 1);
3860 /* Close read end of the pipe. */
3866 TRACE("Calling function \"%s\"", d
->fn_name
);
3868 /* Call function to run. */
3869 return d
->fn(d
->arg
);
3872 static struct id_map
*mapped_nsid_add(struct lxc_conf
*conf
, unsigned id
,
3875 const struct id_map
*map
;
3876 struct id_map
*retmap
;
3878 map
= find_mapped_nsid_entry(conf
, id
, idtype
);
3882 retmap
= malloc(sizeof(*retmap
));
3886 memcpy(retmap
, map
, sizeof(*retmap
));
3890 static struct id_map
*find_mapped_hostid_entry(struct lxc_conf
*conf
,
3891 unsigned id
, enum idtype idtype
)
3894 struct lxc_list
*it
;
3895 struct id_map
*retmap
= NULL
;
3897 lxc_list_for_each (it
, &conf
->id_map
) {
3899 if (map
->idtype
!= idtype
)
3902 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
3911 /* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
3912 * existing one or establish a new one.
3914 static struct id_map
*mapped_hostid_add(struct lxc_conf
*conf
, uid_t id
,
3917 __do_free
struct id_map
*entry
= NULL
;
3919 struct id_map
*tmp
= NULL
;
3921 entry
= malloc(sizeof(*entry
));
3925 /* Reuse existing mapping. */
3926 tmp
= find_mapped_hostid_entry(conf
, id
, type
);
3928 return memcpy(entry
, tmp
, sizeof(*entry
));
3930 /* Find new mapping. */
3931 hostid_mapped
= find_unmapped_nsid(conf
, type
);
3932 if (hostid_mapped
< 0)
3933 return log_debug(NULL
, "Failed to find free mapping for id %d", id
);
3935 entry
->idtype
= type
;
3936 entry
->nsid
= hostid_mapped
;
3937 entry
->hostid
= (unsigned long)id
;
3940 return move_ptr(entry
);
3943 struct lxc_list
*get_minimal_idmap(struct lxc_conf
*conf
)
3945 __do_free
struct id_map
*container_root_uid
= NULL
,
3946 *container_root_gid
= NULL
,
3947 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
3948 __do_free
struct lxc_list
*idmap
= NULL
;
3950 uid_t nsuid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
3951 gid_t nsgid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
3952 struct lxc_list
*tmplist
= NULL
;
3954 /* Find container root mappings. */
3955 container_root_uid
= mapped_nsid_add(conf
, nsuid
, ID_TYPE_UID
);
3956 if (!container_root_uid
)
3957 return log_debug(NULL
, "Failed to find mapping for namespace uid %d", 0);
3959 if (euid
>= container_root_uid
->hostid
&&
3960 euid
< (container_root_uid
->hostid
+ container_root_uid
->range
))
3961 host_uid_map
= container_root_uid
;
3963 container_root_gid
= mapped_nsid_add(conf
, nsgid
, ID_TYPE_GID
);
3964 if (!container_root_gid
)
3965 return log_debug(NULL
, "Failed to find mapping for namespace gid %d", 0);
3967 if (egid
>= container_root_gid
->hostid
&&
3968 egid
< (container_root_gid
->hostid
+ container_root_gid
->range
))
3969 host_gid_map
= container_root_gid
;
3971 /* Check whether the {g,u}id of the user has a mapping. */
3973 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
3975 return log_debug(NULL
, "Failed to find mapping for uid %d", euid
);
3978 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
3980 return log_debug(NULL
, "Failed to find mapping for gid %d", egid
);
3982 /* Allocate new {g,u}id map list. */
3983 idmap
= malloc(sizeof(*idmap
));
3986 lxc_list_init(idmap
);
3988 /* Add container root to the map. */
3989 tmplist
= malloc(sizeof(*tmplist
));
3992 lxc_list_add_elem(tmplist
, container_root_uid
);
3993 lxc_list_add_tail(idmap
, tmplist
);
3995 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
3996 /* idmap will now keep track of that memory. */
3997 move_ptr(container_root_uid
);
3999 /* Add container root to the map. */
4000 tmplist
= malloc(sizeof(*tmplist
));
4003 lxc_list_add_elem(tmplist
, host_uid_map
);
4004 lxc_list_add_tail(idmap
, tmplist
);
4006 /* idmap will now keep track of that memory. */
4007 move_ptr(container_root_uid
);
4008 /* idmap will now keep track of that memory. */
4009 move_ptr(host_uid_map
);
4011 tmplist
= malloc(sizeof(*tmplist
));
4014 lxc_list_add_elem(tmplist
, container_root_gid
);
4015 lxc_list_add_tail(idmap
, tmplist
);
4017 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4018 /* idmap will now keep track of that memory. */
4019 move_ptr(container_root_gid
);
4021 tmplist
= malloc(sizeof(*tmplist
));
4024 lxc_list_add_elem(tmplist
, host_gid_map
);
4025 lxc_list_add_tail(idmap
, tmplist
);
4027 /* idmap will now keep track of that memory. */
4028 move_ptr(container_root_gid
);
4029 /* idmap will now keep track of that memory. */
4030 move_ptr(host_gid_map
);
4032 TRACE("Allocated minimal idmapping");
4033 return move_ptr(idmap
);
4036 /* Run a function in a new user namespace.
4037 * The caller's euid/egid will be mapped if it is not already.
4038 * Afaict, userns_exec_1() is only used to operate based on privileges for the
4039 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
4040 * This means we require only to establish a mapping from:
4041 * - the container root {g,u}id as seen from the host > user's host {g,u}id
4042 * - the container root -> some sub{g,u}id
4043 * The former we add, if the user did not specify a mapping. The latter we
4044 * retrieve from the container's configured {g,u}id mappings as it must have been
4045 * there to start the container in the first place.
4047 int userns_exec_1(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4048 const char *fn_name
)
4052 struct userns_fn_data d
;
4053 struct lxc_list
*idmap
;
4054 int ret
= -1, status
= -1;
4060 idmap
= get_minimal_idmap(conf
);
4064 ret
= pipe2(p
, O_CLOEXEC
);
4066 SYSERROR("Failed to create pipe");
4070 d
.fn_name
= fn_name
;
4075 /* Clone child in new user namespace. */
4076 pid
= lxc_raw_clone_cb(run_userns_fn
, &d
, CLONE_NEWUSER
, NULL
);
4078 ERROR("Failed to clone process in new user namespace");
4085 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4086 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4088 struct lxc_list
*it
;
4090 lxc_list_for_each (it
, idmap
) {
4092 TRACE("Establishing %cid mapping for \"%d\" in new "
4093 "user namespace: nsuid %lu - hostid %lu - range "
4095 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4096 map
->nsid
, map
->hostid
, map
->range
);
4100 /* Set up {g,u}id mapping for user namespace of child process. */
4101 ret
= lxc_map_ids(idmap
, pid
);
4103 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
4107 /* Tell child to proceed. */
4108 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4109 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4118 /* Wait for child to finish. */
4120 status
= wait_for_pid(pid
);
4128 int userns_exec_full(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4129 const char *fn_name
)
4135 struct lxc_list
*cur
;
4136 struct userns_fn_data d
;
4139 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
4140 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
4141 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4146 ret
= pipe2(p
, O_CLOEXEC
);
4148 SYSERROR("opening pipe");
4152 d
.fn_name
= fn_name
;
4157 /* Clone child in new user namespace. */
4158 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
, NULL
);
4160 ERROR("Failed to clone process in new user namespace");
4170 /* Allocate new {g,u}id map list. */
4171 idmap
= malloc(sizeof(*idmap
));
4174 lxc_list_init(idmap
);
4176 /* Find container root. */
4177 lxc_list_for_each (cur
, &conf
->id_map
) {
4178 struct id_map
*tmpmap
;
4180 tmplist
= malloc(sizeof(*tmplist
));
4184 tmpmap
= malloc(sizeof(*tmpmap
));
4190 memset(tmpmap
, 0, sizeof(*tmpmap
));
4191 memcpy(tmpmap
, cur
->elem
, sizeof(*tmpmap
));
4192 tmplist
->elem
= tmpmap
;
4194 lxc_list_add_tail(idmap
, tmplist
);
4198 if (map
->idtype
== ID_TYPE_UID
)
4199 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
4202 if (map
->idtype
== ID_TYPE_GID
)
4203 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
4209 if (map
->idtype
== ID_TYPE_UID
)
4210 if (container_root_uid
== NULL
)
4211 container_root_uid
= map
;
4213 if (map
->idtype
== ID_TYPE_GID
)
4214 if (container_root_gid
== NULL
)
4215 container_root_gid
= map
;
4218 if (!container_root_uid
|| !container_root_gid
) {
4219 ERROR("No mapping for container root found");
4223 /* Check whether the {g,u}id of the user has a mapping. */
4225 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4227 host_uid_map
= container_root_uid
;
4230 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4232 host_gid_map
= container_root_gid
;
4234 if (!host_uid_map
) {
4235 DEBUG("Failed to find mapping for uid %d", euid
);
4239 if (!host_gid_map
) {
4240 DEBUG("Failed to find mapping for gid %d", egid
);
4244 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4245 /* Add container root to the map. */
4246 tmplist
= malloc(sizeof(*tmplist
));
4249 lxc_list_add_elem(tmplist
, host_uid_map
);
4250 lxc_list_add_tail(idmap
, tmplist
);
4252 /* idmap will now keep track of that memory. */
4253 host_uid_map
= NULL
;
4255 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4256 tmplist
= malloc(sizeof(*tmplist
));
4259 lxc_list_add_elem(tmplist
, host_gid_map
);
4260 lxc_list_add_tail(idmap
, tmplist
);
4262 /* idmap will now keep track of that memory. */
4263 host_gid_map
= NULL
;
4265 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4266 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4267 lxc_list_for_each (cur
, idmap
) {
4269 TRACE("establishing %cid mapping for \"%d\" in new "
4270 "user namespace: nsuid %lu - hostid %lu - range "
4272 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4273 map
->nsid
, map
->hostid
, map
->range
);
4277 /* Set up {g,u}id mapping for user namespace of child process. */
4278 ret
= lxc_map_ids(idmap
, pid
);
4280 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid
);
4284 /* Tell child to proceed. */
4285 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4286 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4295 /* Wait for child to finish. */
4297 ret
= wait_for_pid(pid
);
4300 lxc_free_idmap(idmap
);
4304 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
4306 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
4312 /* not thread-safe, do not use from api without first forking */
4313 static char *getuname(void)
4315 __do_free
char *buf
= NULL
;
4316 struct passwd pwent
;
4317 struct passwd
*pwentp
= NULL
;
4321 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
4325 buf
= malloc(bufsize
);
4329 ret
= getpwuid_r(geteuid(), &pwent
, buf
, bufsize
, &pwentp
);
4332 WARN("Could not find matched password record.");
4334 return log_error(NULL
, "Failed to get password record - %u", geteuid());
4337 return strdup(pwent
.pw_name
);
4340 /* not thread-safe, do not use from api without first forking */
4341 static char *getgname(void)
4343 __do_free
char *buf
= NULL
;
4345 struct group
*grentp
= NULL
;
4349 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
4353 buf
= malloc(bufsize
);
4357 ret
= getgrgid_r(getegid(), &grent
, buf
, bufsize
, &grentp
);
4360 WARN("Could not find matched group record");
4362 return log_error(NULL
, "Failed to get group record - %u", getegid());
4365 return strdup(grent
.gr_name
);
4368 /* not thread-safe, do not use from api without first forking */
4369 void suggest_default_idmap(void)
4371 __do_free
char *gname
= NULL
, *line
= NULL
, *uname
= NULL
;
4372 __do_fclose
FILE *subuid_f
= NULL
, *subgid_f
= NULL
;
4373 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
4384 subuid_f
= fopen(subuidfile
, "re");
4386 ERROR("Your system is not configured with subuids");
4390 while (getline(&line
, &len
, subuid_f
) != -1) {
4392 size_t no_newline
= 0;
4394 p
= strchr(line
, ':');
4402 if (strcmp(line
, uname
))
4405 p2
= strchr(p
, ':');
4412 no_newline
= strcspn(p2
, "\n");
4413 p2
[no_newline
] = '\0';
4415 if (lxc_safe_uint(p
, &uid
) < 0)
4416 WARN("Could not parse UID");
4417 if (lxc_safe_uint(p2
, &urange
) < 0)
4418 WARN("Could not parse UID range");
4421 subgid_f
= fopen(subgidfile
, "re");
4423 ERROR("Your system is not configured with subgids");
4427 while (getline(&line
, &len
, subgid_f
) != -1) {
4429 size_t no_newline
= 0;
4431 p
= strchr(line
, ':');
4439 if (strcmp(line
, uname
))
4442 p2
= strchr(p
, ':');
4449 no_newline
= strcspn(p2
, "\n");
4450 p2
[no_newline
] = '\0';
4452 if (lxc_safe_uint(p
, &gid
) < 0)
4453 WARN("Could not parse GID");
4454 if (lxc_safe_uint(p2
, &grange
) < 0)
4455 WARN("Could not parse GID range");
4458 if (!urange
|| !grange
) {
4459 ERROR("You do not have subuids or subgids allocated");
4460 ERROR("Unprivileged containers require subuids and subgids");
4464 ERROR("You must either run as root, or define uid mappings");
4465 ERROR("To pass uid mappings to lxc-create, you could create");
4466 ERROR("~/.config/lxc/default.conf:");
4467 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
4468 ERROR("lxc.idmap = u 0 %u %u", uid
, urange
);
4469 ERROR("lxc.idmap = g 0 %u %u", gid
, grange
);
4472 static void free_cgroup_settings(struct lxc_list
*result
)
4474 struct lxc_list
*iterator
, *next
;
4476 lxc_list_for_each_safe (iterator
, result
, next
) {
4477 lxc_list_del(iterator
);
4478 free_disarm(iterator
);
4480 free_disarm(result
);
4483 /* Return the list of cgroup_settings sorted according to the following rules
4484 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4486 struct lxc_list
*sort_cgroup_settings(struct lxc_list
*cgroup_settings
)
4488 struct lxc_list
*result
;
4489 struct lxc_cgroup
*cg
= NULL
;
4490 struct lxc_list
*it
= NULL
, *item
= NULL
, *memsw_limit
= NULL
;
4492 result
= malloc(sizeof(*result
));
4495 lxc_list_init(result
);
4497 /* Iterate over the cgroup settings and copy them to the output list. */
4498 lxc_list_for_each (it
, cgroup_settings
) {
4499 item
= malloc(sizeof(*item
));
4501 free_cgroup_settings(result
);
4505 item
->elem
= it
->elem
;
4507 if (strcmp(cg
->subsystem
, "memory.memsw.limit_in_bytes") == 0) {
4508 /* Store the memsw_limit location */
4510 } else if (strcmp(cg
->subsystem
, "memory.limit_in_bytes") == 0 &&
4511 memsw_limit
!= NULL
) {
4512 /* lxc.cgroup.memory.memsw.limit_in_bytes is found
4513 * before lxc.cgroup.memory.limit_in_bytes, swap these
4515 item
->elem
= memsw_limit
->elem
;
4516 memsw_limit
->elem
= it
->elem
;
4518 lxc_list_add_tail(result
, item
);