2 * lxc: linux Container library
4 * (C) Copyright IBM Corp. 2007, 2008
7 * Daniel Lezcano <daniel.lezcano at free.fr>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include <arpa/inet.h>
34 #include <linux/loop.h>
36 #include <netinet/in.h>
43 #include <sys/mount.h>
44 #include <sys/param.h>
45 #include <sys/prctl.h>
46 #include <sys/sendfile.h>
47 #include <sys/socket.h>
49 #include <sys/syscall.h>
50 #include <sys/sysmacros.h>
51 #include <sys/types.h>
52 #include <sys/utsname.h>
63 #include "confile_utils.h"
68 #include "lxcseccomp.h"
70 #include "memory_utils.h"
71 #include "namespace.h"
74 #include "raw_syscalls.h"
78 #include "storage/overlay.h"
79 #include "syscall_wrappers.h"
84 #include <sys/mkdev.h>
88 #include <sys/statvfs.h>
94 #include <../include/openpty.h>
98 #include <sys/capability.h>
101 #if HAVE_SYS_PERSONALITY_H
102 #include <sys/personality.h>
106 #include "include/strlcat.h"
110 #include <../include/lxcmntent.h>
115 #if !defined(HAVE_PRLIMIT) && defined(HAVE_PRLIMIT64)
116 #include <../include/prlimit.h>
119 lxc_log_define(conf
, lxc
);
121 /* The lxc_conf of the container currently being worked on in an API call.
122 * This is used in the error calls.
125 thread_local
struct lxc_conf
*current_config
;
127 struct lxc_conf
*current_config
;
130 char *lxchook_names
[NUM_LXC_HOOKS
] = {
159 static struct mount_opt mount_opt
[] = {
160 { "async", 1, MS_SYNCHRONOUS
},
161 { "atime", 1, MS_NOATIME
},
162 { "bind", 0, MS_BIND
},
163 { "defaults", 0, 0 },
164 { "dev", 1, MS_NODEV
},
165 { "diratime", 1, MS_NODIRATIME
},
166 { "dirsync", 0, MS_DIRSYNC
},
167 { "exec", 1, MS_NOEXEC
},
168 { "lazytime", 0, MS_LAZYTIME
},
169 { "mand", 0, MS_MANDLOCK
},
170 { "noatime", 0, MS_NOATIME
},
171 { "nodev", 0, MS_NODEV
},
172 { "nodiratime", 0, MS_NODIRATIME
},
173 { "noexec", 0, MS_NOEXEC
},
174 { "nomand", 1, MS_MANDLOCK
},
175 { "norelatime", 1, MS_RELATIME
},
176 { "nostrictatime", 1, MS_STRICTATIME
},
177 { "nosuid", 0, MS_NOSUID
},
178 { "rbind", 0, MS_BIND
|MS_REC
},
179 { "relatime", 0, MS_RELATIME
},
180 { "remount", 0, MS_REMOUNT
},
181 { "ro", 0, MS_RDONLY
},
182 { "rw", 1, MS_RDONLY
},
183 { "strictatime", 0, MS_STRICTATIME
},
184 { "suid", 1, MS_NOSUID
},
185 { "sync", 0, MS_SYNCHRONOUS
},
189 static struct mount_opt propagation_opt
[] = {
190 { "private", 0, MS_PRIVATE
},
191 { "shared", 0, MS_SHARED
},
192 { "slave", 0, MS_SLAVE
},
193 { "unbindable", 0, MS_UNBINDABLE
},
194 { "rprivate", 0, MS_PRIVATE
|MS_REC
},
195 { "rshared", 0, MS_SHARED
|MS_REC
},
196 { "rslave", 0, MS_SLAVE
|MS_REC
},
197 { "runbindable", 0, MS_UNBINDABLE
|MS_REC
},
201 static struct caps_opt caps_opt
[] = {
203 { "chown", CAP_CHOWN
},
204 { "dac_override", CAP_DAC_OVERRIDE
},
205 { "dac_read_search", CAP_DAC_READ_SEARCH
},
206 { "fowner", CAP_FOWNER
},
207 { "fsetid", CAP_FSETID
},
208 { "kill", CAP_KILL
},
209 { "setgid", CAP_SETGID
},
210 { "setuid", CAP_SETUID
},
211 { "setpcap", CAP_SETPCAP
},
212 { "linux_immutable", CAP_LINUX_IMMUTABLE
},
213 { "net_bind_service", CAP_NET_BIND_SERVICE
},
214 { "net_broadcast", CAP_NET_BROADCAST
},
215 { "net_admin", CAP_NET_ADMIN
},
216 { "net_raw", CAP_NET_RAW
},
217 { "ipc_lock", CAP_IPC_LOCK
},
218 { "ipc_owner", CAP_IPC_OWNER
},
219 { "sys_module", CAP_SYS_MODULE
},
220 { "sys_rawio", CAP_SYS_RAWIO
},
221 { "sys_chroot", CAP_SYS_CHROOT
},
222 { "sys_ptrace", CAP_SYS_PTRACE
},
223 { "sys_pacct", CAP_SYS_PACCT
},
224 { "sys_admin", CAP_SYS_ADMIN
},
225 { "sys_boot", CAP_SYS_BOOT
},
226 { "sys_nice", CAP_SYS_NICE
},
227 { "sys_resource", CAP_SYS_RESOURCE
},
228 { "sys_time", CAP_SYS_TIME
},
229 { "sys_tty_config", CAP_SYS_TTY_CONFIG
},
230 { "mknod", CAP_MKNOD
},
231 { "lease", CAP_LEASE
},
232 #ifdef CAP_AUDIT_READ
233 { "audit_read", CAP_AUDIT_READ
},
235 #ifdef CAP_AUDIT_WRITE
236 { "audit_write", CAP_AUDIT_WRITE
},
238 #ifdef CAP_AUDIT_CONTROL
239 { "audit_control", CAP_AUDIT_CONTROL
},
241 { "setfcap", CAP_SETFCAP
},
242 { "mac_override", CAP_MAC_OVERRIDE
},
243 { "mac_admin", CAP_MAC_ADMIN
},
245 { "syslog", CAP_SYSLOG
},
247 #ifdef CAP_WAKE_ALARM
248 { "wake_alarm", CAP_WAKE_ALARM
},
250 #ifdef CAP_BLOCK_SUSPEND
251 { "block_suspend", CAP_BLOCK_SUSPEND
},
256 static struct limit_opt limit_opt
[] = {
261 { "core", RLIMIT_CORE
},
264 { "cpu", RLIMIT_CPU
},
267 { "data", RLIMIT_DATA
},
270 { "fsize", RLIMIT_FSIZE
},
273 { "locks", RLIMIT_LOCKS
},
275 #ifdef RLIMIT_MEMLOCK
276 { "memlock", RLIMIT_MEMLOCK
},
278 #ifdef RLIMIT_MSGQUEUE
279 { "msgqueue", RLIMIT_MSGQUEUE
},
282 { "nice", RLIMIT_NICE
},
285 { "nofile", RLIMIT_NOFILE
},
288 { "nproc", RLIMIT_NPROC
},
291 { "rss", RLIMIT_RSS
},
294 { "rtprio", RLIMIT_RTPRIO
},
297 { "rttime", RLIMIT_RTTIME
},
299 #ifdef RLIMIT_SIGPENDING
300 { "sigpending", RLIMIT_SIGPENDING
},
303 { "stack", RLIMIT_STACK
},
307 static int run_buffer(char *buffer
)
309 __do_free
char *output
= NULL
;
311 struct lxc_popen_FILE
*f
;
313 f
= lxc_popen(buffer
);
315 SYSERROR("Failed to popen() %s", buffer
);
319 output
= malloc(LXC_LOG_BUFFER_SIZE
);
321 ERROR("Failed to allocate memory for %s", buffer
);
328 SYSERROR("Failed to retrieve underlying file descriptor");
333 for (int i
= 0; i
< 10; i
++) {
336 bytes_read
= lxc_read_nointr(fd
, output
, LXC_LOG_BUFFER_SIZE
- 1);
337 if (bytes_read
> 0) {
338 output
[bytes_read
] = '\0';
339 DEBUG("Script %s produced output: %s", buffer
, output
);
348 SYSERROR("Script exited with error");
350 } else if (WIFEXITED(ret
) && WEXITSTATUS(ret
) != 0) {
351 ERROR("Script exited with status %d", WEXITSTATUS(ret
));
353 } else if (WIFSIGNALED(ret
)) {
354 ERROR("Script terminated by signal %d", WTERMSIG(ret
));
361 int run_script_argv(const char *name
, unsigned int hook_version
,
362 const char *section
, const char *script
,
363 const char *hookname
, char **argv
)
365 __do_free
char *buffer
= NULL
;
369 if (hook_version
== 0)
370 INFO("Executing script \"%s\" for container \"%s\", config "
371 "section \"%s\"", script
, name
, section
);
373 INFO("Executing script \"%s\" for container \"%s\"", script
, name
);
375 for (i
= 0; argv
&& argv
[i
]; i
++)
376 size
+= strlen(argv
[i
]) + 1;
378 size
+= STRLITERALLEN("exec");
380 size
+= strlen(script
);
386 if (hook_version
== 0) {
387 size
+= strlen(hookname
);
390 size
+= strlen(name
);
393 size
+= strlen(section
);
400 buffer
= malloc(size
);
404 if (hook_version
== 0)
405 buf_pos
= snprintf(buffer
, size
, "exec %s %s %s %s", script
, name
, section
, hookname
);
407 buf_pos
= snprintf(buffer
, size
, "exec %s", script
);
408 if (buf_pos
< 0 || (size_t)buf_pos
>= size
) {
409 ERROR("Failed to create command line for script \"%s\"", script
);
413 if (hook_version
== 1) {
414 ret
= setenv("LXC_HOOK_TYPE", hookname
, 1);
416 SYSERROR("Failed to set environment variable: "
417 "LXC_HOOK_TYPE=%s", hookname
);
420 TRACE("Set environment variable: LXC_HOOK_TYPE=%s", hookname
);
422 ret
= setenv("LXC_HOOK_SECTION", section
, 1);
424 SYSERROR("Failed to set environment variable: "
425 "LXC_HOOK_SECTION=%s", section
);
428 TRACE("Set environment variable: LXC_HOOK_SECTION=%s", section
);
430 if (strcmp(section
, "net") == 0) {
433 if (!argv
|| !argv
[0])
436 ret
= setenv("LXC_NET_TYPE", argv
[0], 1);
438 SYSERROR("Failed to set environment variable: "
439 "LXC_NET_TYPE=%s", argv
[0]);
442 TRACE("Set environment variable: LXC_NET_TYPE=%s", argv
[0]);
444 parent
= argv
[1] ? argv
[1] : "";
446 if (strcmp(argv
[0], "macvlan") == 0) {
447 ret
= setenv("LXC_NET_PARENT", parent
, 1);
449 SYSERROR("Failed to set environment "
450 "variable: LXC_NET_PARENT=%s", parent
);
453 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
454 } else if (strcmp(argv
[0], "phys") == 0) {
455 ret
= setenv("LXC_NET_PARENT", parent
, 1);
457 SYSERROR("Failed to set environment "
458 "variable: LXC_NET_PARENT=%s", parent
);
461 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
462 } else if (strcmp(argv
[0], "veth") == 0) {
463 char *peer
= argv
[2] ? argv
[2] : "";
465 ret
= setenv("LXC_NET_PEER", peer
, 1);
467 SYSERROR("Failed to set environment "
468 "variable: LXC_NET_PEER=%s", peer
);
471 TRACE("Set environment variable: LXC_NET_PEER=%s", peer
);
473 ret
= setenv("LXC_NET_PARENT", parent
, 1);
475 SYSERROR("Failed to set environment "
476 "variable: LXC_NET_PARENT=%s", parent
);
479 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
484 for (i
= 0; argv
&& argv
[i
]; i
++) {
485 size_t len
= size
- buf_pos
;
487 ret
= snprintf(buffer
+ buf_pos
, len
, " %s", argv
[i
]);
488 if (ret
< 0 || (size_t)ret
>= len
) {
489 ERROR("Failed to create command line for script \"%s\"", script
);
495 return run_buffer(buffer
);
498 int run_script(const char *name
, const char *section
, const char *script
, ...)
500 __do_free
char *buffer
= NULL
;
506 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
507 script
, name
, section
);
509 va_start(ap
, script
);
510 while ((p
= va_arg(ap
, char *)))
511 size
+= strlen(p
) + 1;
514 size
+= STRLITERALLEN("exec");
515 size
+= strlen(script
);
516 size
+= strlen(name
);
517 size
+= strlen(section
);
523 buffer
= must_realloc(NULL
, size
);
524 ret
= snprintf(buffer
, size
, "exec %s %s %s", script
, name
, section
);
525 if (ret
< 0 || ret
>= size
)
528 va_start(ap
, script
);
529 while ((p
= va_arg(ap
, char *))) {
530 int len
= size
- ret
;
532 rc
= snprintf(buffer
+ ret
, len
, " %s", p
);
533 if (rc
< 0 || rc
>= len
) {
541 return run_buffer(buffer
);
545 * if rootfs is a directory, then open ${rootfs}/.lxc-keep for writing for
546 * the duration of the container run, to prevent the container from marking
547 * the underlying fs readonly on shutdown. unlink the file immediately so
548 * no name pollution is happens.
549 * don't unlink on NFS to avoid random named stale handles.
550 * return -1 on error.
551 * return -2 if nothing needed to be pinned.
552 * return an open fd (>=0) if we pinned it.
554 int pin_rootfs(const char *rootfs
)
556 __do_free
char *absrootfs
= NULL
;
558 char absrootfspin
[PATH_MAX
];
562 if (rootfs
== NULL
|| strlen(rootfs
) == 0)
565 absrootfs
= realpath(rootfs
, NULL
);
569 ret
= stat(absrootfs
, &s
);
573 if (!S_ISDIR(s
.st_mode
))
576 ret
= snprintf(absrootfspin
, PATH_MAX
, "%s/.lxc-keep", absrootfs
);
577 if (ret
< 0 || ret
>= PATH_MAX
)
580 fd
= open(absrootfspin
, O_CREAT
| O_RDWR
, S_IWUSR
| S_IRUSR
);
584 ret
= fstatfs (fd
, &sfs
);
588 if (sfs
.f_type
== NFS_SUPER_MAGIC
) {
589 DEBUG("Rootfs on NFS, not unlinking pin file \"%s\"", absrootfspin
);
593 (void)unlink(absrootfspin
);
598 /* If we are asking to remount something, make sure that any NOEXEC etc are
601 unsigned long add_required_remount_flags(const char *s
, const char *d
,
607 unsigned long required_flags
= 0;
615 ret
= statvfs(s
, &sb
);
619 if (flags
& MS_REMOUNT
) {
620 if (sb
.f_flag
& MS_NOSUID
)
621 required_flags
|= MS_NOSUID
;
622 if (sb
.f_flag
& MS_NODEV
)
623 required_flags
|= MS_NODEV
;
624 if (sb
.f_flag
& MS_RDONLY
)
625 required_flags
|= MS_RDONLY
;
626 if (sb
.f_flag
& MS_NOEXEC
)
627 required_flags
|= MS_NOEXEC
;
630 if (sb
.f_flag
& MS_NOATIME
)
631 required_flags
|= MS_NOATIME
;
632 if (sb
.f_flag
& MS_NODIRATIME
)
633 required_flags
|= MS_NODIRATIME
;
634 if (sb
.f_flag
& MS_LAZYTIME
)
635 required_flags
|= MS_LAZYTIME
;
636 if (sb
.f_flag
& MS_RELATIME
)
637 required_flags
|= MS_RELATIME
;
638 if (sb
.f_flag
& MS_STRICTATIME
)
639 required_flags
|= MS_STRICTATIME
;
641 return flags
| required_flags
;
647 static int add_shmount_to_list(struct lxc_conf
*conf
)
649 char new_mount
[PATH_MAX
];
650 /* Offset for the leading '/' since the path_cont
651 * is absolute inside the container.
653 int offset
= 1, ret
= -1;
655 ret
= snprintf(new_mount
, sizeof(new_mount
),
656 "%s %s none bind,create=dir 0 0", conf
->shmount
.path_host
,
657 conf
->shmount
.path_cont
+ offset
);
658 if (ret
< 0 || (size_t)ret
>= sizeof(new_mount
))
661 return add_elem_to_mount_list(new_mount
, conf
);
664 static int lxc_mount_auto_mounts(struct lxc_conf
*conf
, int flags
, struct lxc_handler
*handler
)
671 const char *destination
;
675 } default_mounts
[] = {
676 /* Read-only bind-mounting... In older kernels, doing that
677 * required to do one MS_BIND mount and then
678 * MS_REMOUNT|MS_RDONLY the same one. According to mount(2)
679 * manpage, MS_BIND honors MS_RDONLY from kernel 2.6.26
680 * onwards. However, this apparently does not work on kernel
681 * 3.8. Unfortunately, on that very same kernel, doing the same
682 * trick as above doesn't seem to work either, there one needs
683 * to ALSO specify MS_BIND for the remount, otherwise the
684 * entire fs is remounted read-only or the mount fails because
685 * it's busy... MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for
686 * kernels as low as 2.6.32...
688 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
689 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
690 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys/net", "%r/proc/tty", NULL
, MS_BIND
, NULL
},
691 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys", "%r/proc/sys", NULL
, MS_BIND
, NULL
},
692 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
693 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/tty", "%r/proc/sys/net", NULL
, MS_MOVE
, NULL
},
694 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL
, MS_BIND
, NULL
},
695 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sysrq-trigger", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
696 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_RW
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
697 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RW
, "sysfs", "%r/sys", "sysfs", 0, NULL
},
698 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RO
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
, NULL
},
699 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys", "sysfs", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
700 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/sys", "%r/sys", NULL
, MS_BIND
, NULL
},
701 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, NULL
, "%r/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
702 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys/devices/virtual/net", "sysfs", 0, NULL
},
703 { 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
},
704 { 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
},
705 { 0, 0, NULL
, NULL
, NULL
, 0, NULL
}
708 for (i
= 0; default_mounts
[i
].match_mask
; i
++) {
709 __do_free
char *destination
= NULL
, *source
= NULL
;
711 unsigned long mflags
;
712 if ((flags
& default_mounts
[i
].match_mask
) != default_mounts
[i
].match_flag
)
715 if (default_mounts
[i
].source
) {
716 /* will act like strdup if %r is not present */
717 source
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].source
);
722 if (!default_mounts
[i
].destination
) {
723 ERROR("BUG: auto mounts destination %d was NULL", i
);
727 /* will act like strdup if %r is not present */
728 destination
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].destination
);
733 mflags
= add_required_remount_flags(source
, destination
,
734 default_mounts
[i
].flags
);
735 r
= safe_mount(source
, destination
, default_mounts
[i
].fstype
,
736 mflags
, default_mounts
[i
].options
,
737 conf
->rootfs
.path
? conf
->rootfs
.mount
: NULL
);
739 if (r
< 0 && errno
== ENOENT
) {
740 INFO("Mount source or target for \"%s\" on \"%s\" does "
741 "not exist. Skipping", source
, destination
);
744 SYSERROR("Failed to mount \"%s\" on \"%s\" with flags %lu", source
, destination
, mflags
);
753 if (flags
& LXC_AUTO_CGROUP_MASK
) {
756 cg_flags
= flags
& (LXC_AUTO_CGROUP_MASK
& ~LXC_AUTO_CGROUP_FORCE
);
757 /* If the type of cgroup mount was not specified, it depends on
758 * the container's capabilities as to what makes sense: if we
759 * have CAP_SYS_ADMIN, the read-only part can be remounted
760 * read-write anyway, so we may as well default to read-write;
761 * then the admin will not be given a false sense of security.
762 * (And if they really want mixed r/o r/w, then they can
763 * explicitly specify :mixed.) OTOH, if the container lacks
764 * CAP_SYS_ADMIN, do only default to :mixed, because then the
765 * container can't remount it read-write.
767 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
|| cg_flags
== LXC_AUTO_CGROUP_FULL_NOSPEC
) {
768 int has_sys_admin
= 0;
770 if (!lxc_list_empty(&conf
->keepcaps
))
771 has_sys_admin
= in_caplist(CAP_SYS_ADMIN
, &conf
->keepcaps
);
773 has_sys_admin
= !in_caplist(CAP_SYS_ADMIN
, &conf
->caps
);
775 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
776 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_RW
: LXC_AUTO_CGROUP_MIXED
;
778 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_FULL_RW
: LXC_AUTO_CGROUP_FULL_MIXED
;
781 if (flags
& LXC_AUTO_CGROUP_FORCE
)
782 cg_flags
|= LXC_AUTO_CGROUP_FORCE
;
784 if (!handler
->cgroup_ops
->mount(handler
->cgroup_ops
,
786 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
788 SYSERROR("Failed to mount \"/sys/fs/cgroup\"");
793 if (flags
& LXC_AUTO_SHMOUNTS_MASK
) {
794 int ret
= add_shmount_to_list(conf
);
796 ERROR("Failed to add shmount entry to container config");
804 static int setup_utsname(struct utsname
*utsname
)
811 ret
= sethostname(utsname
->nodename
, strlen(utsname
->nodename
));
813 SYSERROR("Failed to set the hostname to \"%s\"", utsname
->nodename
);
817 INFO("Set hostname to \"%s\"", utsname
->nodename
);
822 struct dev_symlinks
{
827 static const struct dev_symlinks dev_symlinks
[] = {
828 { "/proc/self/fd", "fd" },
829 { "/proc/self/fd/0", "stdin" },
830 { "/proc/self/fd/1", "stdout" },
831 { "/proc/self/fd/2", "stderr" },
834 static int lxc_setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
840 for (i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
841 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
843 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s",
844 rootfs
->path
? rootfs
->mount
: "", d
->name
);
845 if (ret
< 0 || ret
>= PATH_MAX
)
848 /* Stat the path first. If we don't get an error accept it as
849 * is and don't try to create it
851 ret
= stat(path
, &s
);
855 ret
= symlink(d
->oldpath
, path
);
856 if (ret
&& errno
!= EEXIST
) {
857 if (errno
== EROFS
) {
858 WARN("Failed to create \"%s\". Read-only filesystem", path
);
860 SYSERROR("Failed to create \"%s\"", path
);
869 /* Build a space-separate list of ptys to pass to systemd. */
870 static bool append_ttyname(char **pp
, char *name
)
876 *pp
= malloc(strlen(name
) + strlen("container_ttys=") + 1);
880 sprintf(*pp
, "container_ttys=%s", name
);
884 size
= strlen(*pp
) + strlen(name
) + 2;
885 p
= realloc(*pp
, size
);
890 (void)strlcat(p
, " ", size
);
891 (void)strlcat(p
, name
, size
);
896 static int lxc_setup_ttys(struct lxc_conf
*conf
)
899 const struct lxc_tty_info
*ttys
= &conf
->ttys
;
900 char *ttydir
= ttys
->dir
;
901 char path
[PATH_MAX
], lxcpath
[PATH_MAX
];
903 if (!conf
->rootfs
.path
)
906 for (i
= 0; i
< ttys
->max
; i
++) {
907 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
909 ret
= snprintf(path
, sizeof(path
), "/dev/tty%d", i
+ 1);
910 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
914 /* create dev/lxc/tty%d" */
915 ret
= snprintf(lxcpath
, sizeof(lxcpath
),
916 "/dev/%s/tty%d", ttydir
, i
+ 1);
917 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
920 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
921 if (ret
< 0 && errno
!= EEXIST
) {
922 SYSERROR("Failed to create \"%s\"", lxcpath
);
927 if (ret
< 0 && errno
!= ENOENT
) {
928 SYSERROR("Failed to unlink \"%s\"", path
);
932 ret
= mount(tty
->name
, lxcpath
, "none", MS_BIND
, 0);
934 SYSWARN("Failed to bind mount \"%s\" onto \"%s\"",
938 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
,
941 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/tty%d",
943 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
946 ret
= symlink(lxcpath
, path
);
948 SYSERROR("Failed to create symlink \"%s\" -> \"%s\"",
953 /* If we populated /dev, then we need to create
956 ret
= mknod(path
, S_IFREG
| 0000, 0);
957 if (ret
< 0) /* this isn't fatal, continue */
958 SYSERROR("Failed to create \"%s\"", path
);
960 ret
= mount(tty
->name
, path
, "none", MS_BIND
, 0);
962 SYSERROR("Failed to mount '%s'->'%s'", tty
->name
, path
);
966 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, path
);
969 if (!append_ttyname(&conf
->ttys
.tty_names
, tty
->name
)) {
970 ERROR("Error setting up container_ttys string");
975 INFO("Finished setting up %zu /dev/tty<N> device(s)", ttys
->max
);
979 int lxc_allocate_ttys(struct lxc_conf
*conf
)
983 struct lxc_tty_info
*ttys
= &conf
->ttys
;
985 /* no tty in the configuration */
989 ttys
->tty
= malloc(sizeof(*ttys
->tty
) * ttys
->max
);
993 for (i
= 0; i
< ttys
->max
; i
++) {
994 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
996 tty
->master
= -EBADF
;
998 ret
= openpty(&tty
->master
, &tty
->slave
, NULL
, NULL
, NULL
);
1000 SYSERROR("Failed to create tty %zu", i
);
1002 lxc_delete_tty(ttys
);
1006 ret
= ttyname_r(tty
->slave
, tty
->name
, sizeof(tty
->name
));
1008 SYSERROR("Failed to retrieve name of tty %zu slave", i
);
1010 lxc_delete_tty(ttys
);
1014 DEBUG("Created tty \"%s\" with master fd %d and slave fd %d",
1015 tty
->name
, tty
->master
, tty
->slave
);
1017 /* Prevent leaking the file descriptors to the container */
1018 ret
= fd_cloexec(tty
->master
, true);
1020 SYSWARN("Failed to set FD_CLOEXEC flag on master fd %d of "
1021 "tty device \"%s\"", tty
->master
, tty
->name
);
1023 ret
= fd_cloexec(tty
->slave
, true);
1025 SYSWARN("Failed to set FD_CLOEXEC flag on slave fd %d of "
1026 "tty device \"%s\"", tty
->slave
, tty
->name
);
1031 INFO("Finished creating %zu tty devices", ttys
->max
);
1035 void lxc_delete_tty(struct lxc_tty_info
*ttys
)
1042 for (i
= 0; i
< ttys
->max
; i
++) {
1043 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1045 if (tty
->master
>= 0) {
1047 tty
->master
= -EBADF
;
1050 if (tty
->slave
>= 0) {
1052 tty
->slave
= -EBADF
;
1060 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
1064 struct lxc_conf
*conf
= handler
->conf
;
1065 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1066 int sock
= handler
->data_sock
[0];
1071 for (i
= 0; i
< ttys
->max
; i
++) {
1073 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1075 ttyfds
[0] = tty
->master
;
1076 ttyfds
[1] = tty
->slave
;
1078 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, 2, NULL
, 0);
1082 TRACE("Sent tty \"%s\" with master fd %d and slave fd %d to "
1083 "parent", tty
->name
, tty
->master
, tty
->slave
);
1087 SYSERROR("Failed to send %zu ttys to parent", ttys
->max
);
1089 TRACE("Sent %zu ttys to parent", ttys
->max
);
1094 static int lxc_create_ttys(struct lxc_handler
*handler
)
1097 struct lxc_conf
*conf
= handler
->conf
;
1099 ret
= lxc_allocate_ttys(conf
);
1101 ERROR("Failed to allocate ttys");
1105 ret
= lxc_send_ttys_to_parent(handler
);
1107 ERROR("Failed to send ttys to parent");
1111 if (!conf
->is_execute
) {
1112 ret
= lxc_setup_ttys(conf
);
1114 ERROR("Failed to setup ttys");
1119 if (conf
->ttys
.tty_names
) {
1120 ret
= setenv("container_ttys", conf
->ttys
.tty_names
, 1);
1122 SYSERROR("Failed to set \"container_ttys=%s\"", conf
->ttys
.tty_names
);
1128 lxc_delete_tty(&conf
->ttys
);
1133 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1134 * error, log it but don't fail yet.
1136 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
,
1137 const char *lxcpath
)
1139 __do_free
char *path
= NULL
;
1144 INFO("Preparing \"/dev\"");
1146 /* $(rootfs->mount) + "/dev/pts" + '\0' */
1147 clen
= (rootfs
->path
? strlen(rootfs
->mount
) : 0) + 9;
1148 path
= must_realloc(NULL
, clen
);
1150 ret
= snprintf(path
, clen
, "%s/dev", rootfs
->path
? rootfs
->mount
: "");
1151 if (ret
< 0 || (size_t)ret
>= clen
)
1154 cur_mask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1155 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1156 if (ret
< 0 && errno
!= EEXIST
) {
1157 SYSERROR("Failed to create \"/dev\" directory");
1162 ret
= safe_mount("none", path
, "tmpfs", 0, "size=500000,mode=755",
1163 rootfs
->path
? rootfs
->mount
: NULL
);
1165 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1168 TRACE("Mounted tmpfs on \"%s\"", path
);
1170 ret
= snprintf(path
, clen
, "%s/dev/pts", rootfs
->path
? rootfs
->mount
: "");
1171 if (ret
< 0 || (size_t)ret
>= clen
) {
1176 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1177 * If not, then create it and exit if that fails...
1179 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1180 if (ret
< 0 && errno
!= EEXIST
) {
1181 SYSERROR("Failed to create directory \"%s\"", path
);
1189 (void)umask(cur_mask
);
1191 INFO("Prepared \"/dev\"");
1195 struct lxc_device_node
{
1202 static const struct lxc_device_node lxc_devices
[] = {
1203 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1204 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1205 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1206 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1207 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1208 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1215 LXC_DEVNODE_PARTIAL
,
1219 static int lxc_fill_autodev(const struct lxc_rootfs
*rootfs
)
1222 char path
[PATH_MAX
];
1224 int use_mknod
= LXC_DEVNODE_MKNOD
;
1226 ret
= snprintf(path
, PATH_MAX
, "%s/dev",
1227 rootfs
->path
? rootfs
->mount
: "");
1228 if (ret
< 0 || ret
>= PATH_MAX
)
1231 /* ignore, just don't try to fill in */
1232 if (!dir_exists(path
))
1235 INFO("Populating \"/dev\"");
1237 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1238 for (i
= 0; i
< sizeof(lxc_devices
) / sizeof(lxc_devices
[0]); i
++) {
1239 char hostpath
[PATH_MAX
];
1240 const struct lxc_device_node
*device
= &lxc_devices
[i
];
1242 ret
= snprintf(path
, PATH_MAX
, "%s/dev/%s",
1243 rootfs
->path
? rootfs
->mount
: "", device
->name
);
1244 if (ret
< 0 || ret
>= PATH_MAX
)
1247 if (use_mknod
>= LXC_DEVNODE_MKNOD
) {
1248 ret
= mknod(path
, device
->mode
, makedev(device
->maj
, device
->min
));
1249 if (ret
== 0 || (ret
< 0 && errno
== EEXIST
)) {
1250 DEBUG("Created device node \"%s\"", path
);
1251 } else if (ret
< 0) {
1252 if (errno
!= EPERM
) {
1253 SYSERROR("Failed to create device node \"%s\"", path
);
1257 use_mknod
= LXC_DEVNODE_BIND
;
1260 /* Device nodes are fully useable. */
1261 if (use_mknod
== LXC_DEVNODE_OPEN
)
1264 if (use_mknod
== LXC_DEVNODE_MKNOD
) {
1266 * - https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=55956b59df336f6738da916dbb520b6e37df9fbd
1267 * - https://lists.linuxfoundation.org/pipermail/containers/2018-June/039176.html
1269 ret
= open(path
, O_RDONLY
| O_CLOEXEC
);
1271 close_prot_errno_disarm(ret
);
1272 /* Device nodes are fully useable. */
1273 use_mknod
= LXC_DEVNODE_OPEN
;
1277 SYSTRACE("Failed to open \"%s\" device", path
);
1278 /* Device nodes are only partially useable. */
1279 use_mknod
= LXC_DEVNODE_PARTIAL
;
1283 if (use_mknod
!= LXC_DEVNODE_PARTIAL
) {
1284 /* If we are dealing with partially functional device
1285 * nodes the prio mknod() call will have created the
1286 * device node so we can use it as a bind-mount target.
1288 ret
= mknod(path
, S_IFREG
| 0000, 0);
1289 if (ret
< 0 && errno
!= EEXIST
) {
1290 SYSERROR("Failed to create file \"%s\"", path
);
1295 /* Fallback to bind-mounting the device from the host. */
1296 ret
= snprintf(hostpath
, PATH_MAX
, "/dev/%s", device
->name
);
1297 if (ret
< 0 || ret
>= PATH_MAX
)
1300 ret
= safe_mount(hostpath
, path
, 0, MS_BIND
, NULL
,
1301 rootfs
->path
? rootfs
->mount
: NULL
);
1303 SYSERROR("Failed to bind mount host device node \"%s\" "
1304 "onto \"%s\"", hostpath
, path
);
1307 DEBUG("Bind mounted host device node \"%s\" onto \"%s\"",
1312 INFO("Populated \"/dev\"");
1316 static int lxc_mount_rootfs(struct lxc_conf
*conf
)
1319 struct lxc_storage
*bdev
;
1320 const struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
1322 if (!rootfs
->path
) {
1323 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
1325 SYSERROR("Failed to remount \"/\" MS_REC | MS_SLAVE");
1332 ret
= access(rootfs
->mount
, F_OK
);
1334 SYSERROR("Failed to access to \"%s\". Check it is present",
1339 bdev
= storage_init(conf
);
1341 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1342 rootfs
->path
, rootfs
->mount
,
1343 rootfs
->options
? rootfs
->options
: "(null)");
1347 ret
= bdev
->ops
->mount(bdev
);
1350 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1351 rootfs
->path
, rootfs
->mount
,
1352 rootfs
->options
? rootfs
->options
: "(null)");
1356 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
1357 rootfs
->path
, rootfs
->mount
,
1358 rootfs
->options
? rootfs
->options
: "(null)");
1363 int lxc_chroot(const struct lxc_rootfs
*rootfs
)
1365 __do_free
char *nroot
= NULL
;
1367 char *root
= rootfs
->mount
;
1369 nroot
= realpath(root
, NULL
);
1371 SYSERROR("Failed to resolve \"%s\"", root
);
1379 /* We could use here MS_MOVE, but in userns this mount is locked and
1382 ret
= mount(nroot
, "/", NULL
, MS_REC
| MS_BIND
, NULL
);
1384 SYSERROR("Failed to mount \"%s\" onto \"/\" as MS_REC | MS_BIND", nroot
);
1388 ret
= mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
);
1390 SYSERROR("Failed to remount \"/\"");
1394 /* The following code cleans up inherited mounts which are not required
1397 * The mountinfo file shows not all mounts, if a few points have been
1398 * unmounted between read operations from the mountinfo. So we need to
1399 * read mountinfo a few times.
1401 * This loop can be skipped if a container uses userns, because all
1402 * inherited mounts are locked and we should live with all this trash.
1405 __do_fclose
FILE *f
= NULL
;
1406 __do_free
char *line
= NULL
;
1407 char *slider1
, *slider2
;
1411 f
= fopen("./proc/self/mountinfo", "r");
1413 SYSERROR("Failed to open \"/proc/self/mountinfo\"");
1417 while (getline(&line
, &len
, f
) > 0) {
1418 for (slider1
= line
, i
= 0; slider1
&& i
< 4; i
++)
1419 slider1
= strchr(slider1
+ 1, ' ');
1424 slider2
= strchr(slider1
+ 1, ' ');
1431 if (strcmp(slider1
+ 1, "/") == 0)
1434 if (strcmp(slider1
+ 1, "/proc") == 0)
1437 ret
= umount2(slider1
, MNT_DETACH
);
1446 /* This also can be skipped if a container uses userns. */
1447 (void)umount2("./proc", MNT_DETACH
);
1449 /* It is weird, but chdir("..") moves us in a new root */
1452 SYSERROR("Failed to chdir(\"..\")");
1458 SYSERROR("Failed to chroot(\".\")");
1465 /* (The following explanation is copied verbatim from the kernel.)
1467 * pivot_root Semantics:
1468 * Moves the root file system of the current process to the directory put_old,
1469 * makes new_root as the new root file system of the current process, and sets
1470 * root/cwd of all processes which had them on the current root to new_root.
1473 * The new_root and put_old must be directories, and must not be on the
1474 * same file system as the current process root. The put_old must be
1475 * underneath new_root, i.e. adding a non-zero number of /.. to the string
1476 * pointed to by put_old must yield the same directory as new_root. No other
1477 * file system may be mounted on put_old. After all, new_root is a mountpoint.
1479 * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
1480 * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
1481 * in this situation.
1484 * - we don't move root/cwd if they are not at the root (reason: if something
1485 * cared enough to change them, it's probably wrong to force them elsewhere)
1486 * - it's okay to pick a root that isn't the root of a file system, e.g.
1487 * /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
1488 * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
1491 static int lxc_pivot_root(const char *rootfs
)
1493 __do_close_prot_errno
int oldroot
= -EBADF
, newroot
= -EBADF
;
1496 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1498 SYSERROR("Failed to open old root directory");
1502 newroot
= open(rootfs
, O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1504 SYSERROR("Failed to open new root directory");
1508 /* change into new root fs */
1509 ret
= fchdir(newroot
);
1511 SYSERROR("Failed to change to new rootfs \"%s\"", rootfs
);
1515 /* pivot_root into our new root fs */
1516 ret
= pivot_root(".", ".");
1518 SYSERROR("Failed to pivot_root()");
1522 /* At this point the old-root is mounted on top of our new-root. To
1523 * unmounted it we must not be chdir'd into it, so escape back to
1526 ret
= fchdir(oldroot
);
1528 SYSERROR("Failed to enter old root directory");
1532 /* Make oldroot rslave to make sure our umounts don't propagate to the
1535 ret
= mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
);
1537 SYSERROR("Failed to make oldroot rslave");
1541 ret
= umount2(".", MNT_DETACH
);
1543 SYSERROR("Failed to detach old root directory");
1547 ret
= fchdir(newroot
);
1549 SYSERROR("Failed to re-enter new root directory");
1553 TRACE("pivot_root(\"%s\") successful", rootfs
);
1558 static int lxc_setup_rootfs_switch_root(const struct lxc_rootfs
*rootfs
)
1560 if (!rootfs
->path
) {
1561 DEBUG("Container does not have a rootfs");
1565 if (detect_ramfs_rootfs())
1566 return lxc_chroot(rootfs
);
1568 return lxc_pivot_root(rootfs
->mount
);
1571 static const struct id_map
*find_mapped_nsid_entry(struct lxc_conf
*conf
,
1575 struct lxc_list
*it
;
1577 struct id_map
*retmap
= NULL
;
1579 /* Shortcut for container's root mappings. */
1581 if (idtype
== ID_TYPE_UID
)
1582 return conf
->root_nsuid_map
;
1584 if (idtype
== ID_TYPE_GID
)
1585 return conf
->root_nsgid_map
;
1588 lxc_list_for_each(it
, &conf
->id_map
) {
1590 if (map
->idtype
!= idtype
)
1593 if (id
>= map
->nsid
&& id
< map
->nsid
+ map
->range
) {
1602 static int lxc_setup_devpts(struct lxc_conf
*conf
)
1606 char devpts_mntopts
[256];
1607 char *mntopt_sets
[5];
1608 char default_devpts_mntopts
[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
1610 if (conf
->pty_max
<= 0) {
1611 DEBUG("No new devpts instance will be mounted since no pts "
1612 "devices are requested");
1616 ret
= snprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%zu",
1617 default_devpts_mntopts
, conf
->pty_max
);
1618 if (ret
< 0 || (size_t)ret
>= sizeof(devpts_mntopts
))
1621 (void)umount2("/dev/pts", MNT_DETACH
);
1623 /* Create mountpoint for devpts instance. */
1624 ret
= mkdir("/dev/pts", 0755);
1625 if (ret
< 0 && errno
!= EEXIST
) {
1626 SYSERROR("Failed to create \"/dev/pts\" directory");
1631 mntopt_sets
[0] = devpts_mntopts
;
1633 /* !gid=5 && max= */
1634 mntopt_sets
[1] = devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1636 /* gid=5 && !max= */
1637 mntopt_sets
[2] = default_devpts_mntopts
;
1639 /* !gid=5 && !max= */
1640 mntopt_sets
[3] = default_devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1643 mntopt_sets
[4] = NULL
;
1645 for (ret
= -1, opts
= mntopt_sets
; opts
&& *opts
; opts
++) {
1646 /* mount new devpts instance */
1647 ret
= mount("devpts", "/dev/pts", "devpts", MS_NOSUID
| MS_NOEXEC
, *opts
);
1653 SYSERROR("Failed to mount new devpts instance");
1656 DEBUG("Mount new devpts instance with options \"%s\"", *opts
);
1658 /* Remove any pre-existing /dev/ptmx file. */
1659 ret
= remove("/dev/ptmx");
1661 if (errno
!= ENOENT
) {
1662 SYSERROR("Failed to remove existing \"/dev/ptmx\" file");
1666 DEBUG("Removed existing \"/dev/ptmx\" file");
1669 /* Create dummy /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1670 ret
= mknod("/dev/ptmx", S_IFREG
| 0000, 0);
1671 if (ret
< 0 && errno
!= EEXIST
) {
1672 SYSERROR("Failed to create dummy \"/dev/ptmx\" file as bind mount target");
1675 DEBUG("Created dummy \"/dev/ptmx\" file as bind mount target");
1677 /* Fallback option: create symlink /dev/ptmx -> /dev/pts/ptmx */
1678 ret
= mount("/dev/pts/ptmx", "/dev/ptmx", NULL
, MS_BIND
, NULL
);
1680 DEBUG("Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1683 /* Fallthrough and try to create a symlink. */
1684 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1687 /* Remove the dummy /dev/ptmx file we created above. */
1688 ret
= remove("/dev/ptmx");
1690 SYSERROR("Failed to remove existing \"/dev/ptmx\"");
1694 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1695 ret
= symlink("/dev/pts/ptmx", "/dev/ptmx");
1697 SYSERROR("Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1700 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1705 static int setup_personality(int persona
)
1709 #if HAVE_SYS_PERSONALITY_H
1713 ret
= personality(persona
);
1715 SYSERROR("Failed to set personality to \"0x%x\"", persona
);
1719 INFO("Set personality to \"0x%x\"", persona
);
1725 static int lxc_setup_dev_console(const struct lxc_rootfs
*rootfs
,
1726 const struct lxc_terminal
*console
)
1729 char path
[PATH_MAX
];
1730 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1732 if (console
->path
&& !strcmp(console
->path
, "none"))
1735 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1736 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1739 /* When we are asked to setup a console we remove any previous
1740 * /dev/console bind-mounts.
1742 if (file_exists(path
)) {
1743 ret
= lxc_unstack_mountpoint(path
, false);
1745 SYSERROR("Failed to unmount \"%s\"", path
);
1748 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1752 /* For unprivileged containers autodev or automounts will already have
1753 * taken care of creating /dev/console.
1755 ret
= mknod(path
, S_IFREG
| 0000, 0);
1756 if (ret
< 0 && errno
!= EEXIST
) {
1757 SYSERROR("Failed to create console");
1761 ret
= fchmod(console
->slave
, S_IXUSR
| S_IXGRP
);
1763 SYSERROR("Failed to set mode \"0%o\" to \"%s\"",
1764 S_IXUSR
| S_IXGRP
, console
->name
);
1768 ret
= safe_mount(console
->name
, path
, "none", MS_BIND
, 0, rootfs_path
);
1770 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, path
);
1774 DEBUG("Mounted pts device \"%s\" onto \"%s\"", console
->name
, path
);
1778 static int lxc_setup_ttydir_console(const struct lxc_rootfs
*rootfs
,
1779 const struct lxc_terminal
*console
,
1783 char path
[PATH_MAX
], lxcpath
[PATH_MAX
];
1784 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1786 if (console
->path
&& !strcmp(console
->path
, "none"))
1789 /* create rootfs/dev/<ttydir> directory */
1790 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs_path
, ttydir
);
1791 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1794 ret
= mkdir(path
, 0755);
1795 if (ret
&& errno
!= EEXIST
) {
1796 SYSERROR("Failed to create \"%s\"", path
);
1799 DEBUG("Created directory for console and tty devices at \"%s\"", path
);
1801 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/dev/%s/console", rootfs_path
, ttydir
);
1802 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1805 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
1806 if (ret
< 0 && errno
!= EEXIST
) {
1807 SYSERROR("Failed to create \"%s\"", lxcpath
);
1811 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1812 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1815 if (file_exists(path
)) {
1816 ret
= lxc_unstack_mountpoint(path
, false);
1818 SYSERROR("Failed to unmount \"%s\"", path
);
1821 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1825 ret
= mknod(path
, S_IFREG
| 0000, 0);
1826 if (ret
< 0 && errno
!= EEXIST
) {
1827 SYSERROR("Failed to create console");
1831 ret
= fchmod(console
->slave
, S_IXUSR
| S_IXGRP
);
1833 SYSERROR("Failed to set mode \"0%o\" to \"%s\"",
1834 S_IXUSR
| S_IXGRP
, console
->name
);
1838 /* bind mount console->name to '/dev/<ttydir>/console' */
1839 ret
= safe_mount(console
->name
, lxcpath
, "none", MS_BIND
, 0, rootfs_path
);
1841 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1844 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1846 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
1847 ret
= safe_mount(lxcpath
, path
, "none", MS_BIND
, 0, rootfs_path
);
1849 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1852 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1854 DEBUG("Console has been setup under \"%s\" and mounted to \"%s\"", lxcpath
, path
);
1858 static int lxc_setup_console(const struct lxc_rootfs
*rootfs
,
1859 const struct lxc_terminal
*console
, char *ttydir
)
1863 return lxc_setup_dev_console(rootfs
, console
);
1865 return lxc_setup_ttydir_console(rootfs
, console
, ttydir
);
1868 static void parse_mntopt(char *opt
, unsigned long *flags
, char **data
, size_t size
)
1870 struct mount_opt
*mo
;
1872 /* If opt is found in mount_opt, set or clear flags.
1873 * Otherwise append it to data. */
1875 for (mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
1876 if (strncmp(opt
, mo
->name
, strlen(mo
->name
)) == 0) {
1878 *flags
&= ~mo
->flag
;
1886 (void)strlcat(*data
, ",", size
);
1888 (void)strlcat(*data
, opt
, size
);
1891 int parse_mntopts(const char *mntopts
, unsigned long *mntflags
, char **mntdata
)
1893 __do_free
char *data
= NULL
, *s
= NULL
;
1903 s
= strdup(mntopts
);
1907 size
= strlen(s
) + 1;
1908 data
= malloc(size
);
1913 lxc_iterate_parts(p
, s
, ",")
1914 parse_mntopt(p
, mntflags
, &data
, size
);
1917 *mntdata
= move_ptr(data
);
1922 static void parse_propagationopt(char *opt
, unsigned long *flags
)
1924 struct mount_opt
*mo
;
1926 /* If opt is found in propagation_opt, set or clear flags. */
1927 for (mo
= &propagation_opt
[0]; mo
->name
!= NULL
; mo
++) {
1928 if (strncmp(opt
, mo
->name
, strlen(mo
->name
)) != 0)
1932 *flags
&= ~mo
->flag
;
1940 int parse_propagationopts(const char *mntopts
, unsigned long *pflags
)
1942 __do_free
char *s
= NULL
;
1948 s
= strdup(mntopts
);
1950 SYSERROR("Failed to allocate memory");
1955 lxc_iterate_parts(p
, s
, ",")
1956 parse_propagationopt(p
, pflags
);
1961 static void null_endofword(char *word
)
1963 while (*word
&& *word
!= ' ' && *word
!= '\t')
1968 /* skip @nfields spaces in @src */
1969 static char *get_field(char *src
, int nfields
)
1974 for (i
= 0; i
< nfields
; i
++) {
1975 while (*p
&& *p
!= ' ' && *p
!= '\t')
1987 static int mount_entry(const char *fsname
, const char *target
,
1988 const char *fstype
, unsigned long mountflags
,
1989 unsigned long pflags
, const char *data
, bool optional
,
1990 bool dev
, bool relative
, const char *rootfs
)
1993 char srcbuf
[PATH_MAX
];
1994 const char *srcpath
= fsname
;
2000 ret
= snprintf(srcbuf
, PATH_MAX
, "%s/%s", rootfs
? rootfs
: "/", fsname
? fsname
: "");
2001 if (ret
< 0 || ret
>= PATH_MAX
) {
2002 ERROR("source path is too long");
2008 ret
= safe_mount(srcpath
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
2012 SYSINFO("Failed to mount \"%s\" on \"%s\" (optional)",
2013 srcpath
? srcpath
: "(null)", target
);
2017 SYSERROR("Failed to mount \"%s\" on \"%s\"",
2018 srcpath
? srcpath
: "(null)", target
);
2022 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
2023 unsigned long rqd_flags
= 0;
2025 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount "
2026 "options", srcpath
? srcpath
: "(none)", target
? target
: "(none)");
2028 if (mountflags
& MS_RDONLY
)
2029 rqd_flags
|= MS_RDONLY
;
2031 if (srcpath
&& statvfs(srcpath
, &sb
) == 0) {
2032 unsigned long required_flags
= rqd_flags
;
2034 if (sb
.f_flag
& MS_NOSUID
)
2035 required_flags
|= MS_NOSUID
;
2037 if (sb
.f_flag
& MS_NODEV
&& !dev
)
2038 required_flags
|= MS_NODEV
;
2040 if (sb
.f_flag
& MS_RDONLY
)
2041 required_flags
|= MS_RDONLY
;
2043 if (sb
.f_flag
& MS_NOEXEC
)
2044 required_flags
|= MS_NOEXEC
;
2046 DEBUG("Flags for \"%s\" were %lu, required extra flags "
2047 "are %lu", srcpath
, sb
.f_flag
, required_flags
);
2049 /* If this was a bind mount request, and required_flags
2050 * does not have any flags which are not already in
2051 * mountflags, then skip the remount.
2053 if (!(mountflags
& MS_REMOUNT
)) {
2054 if (!(required_flags
& ~mountflags
) &&
2056 DEBUG("Mountflags already were %lu, "
2057 "skipping remount", mountflags
);
2062 mountflags
|= required_flags
;
2066 ret
= mount(srcpath
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
2069 SYSINFO("Failed to mount \"%s\" on \"%s\" (optional)",
2070 srcpath
? srcpath
: "(null)", target
);
2074 SYSERROR("Failed to mount \"%s\" on \"%s\"",
2075 srcpath
? srcpath
: "(null)", target
);
2084 ret
= mount(NULL
, target
, NULL
, pflags
, NULL
);
2087 SYSINFO("Failed to change mount propagation "
2088 "for \"%s\" (optional)", target
);
2091 SYSERROR("Failed to change mount propagation "
2092 "for \"%s\" (optional)", target
);
2096 DEBUG("Changed mount propagation for \"%s\"", target
);
2099 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
2100 srcpath
? srcpath
: "(null)", target
, fstype
);
2105 /* Remove "optional", "create=dir", and "create=file" from mntopt */
2106 static void cull_mntent_opt(struct mntent
*mntent
)
2117 for (i
= 0; list
[i
]; i
++) {
2120 p
= strstr(mntent
->mnt_opts
, list
[i
]);
2124 p2
= strchr(p
, ',');
2126 /* no more mntopts, so just chop it here */
2131 memmove(p
, p2
+ 1, strlen(p2
+ 1) + 1);
2135 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
2137 const struct lxc_rootfs
*rootfs
,
2138 const char *lxc_name
, const char *lxc_path
)
2140 __do_free
char *p1
= NULL
;
2144 if (strncmp(mntent
->mnt_type
, "overlay", 7) == 0) {
2145 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
2150 if (hasmntopt(mntent
, "create=dir")) {
2151 ret
= mkdir_p(path
, 0755);
2152 if (ret
< 0 && errno
!= EEXIST
) {
2153 SYSERROR("Failed to create directory \"%s\"", path
);
2158 if (!hasmntopt(mntent
, "create=file"))
2161 ret
= access(path
, F_OK
);
2171 ret
= mkdir_p(p2
, 0755);
2172 if (ret
< 0 && errno
!= EEXIST
) {
2173 SYSERROR("Failed to create directory \"%s\"", path
);
2177 ret
= mknod(path
, S_IFREG
| 0000, 0);
2178 if (ret
< 0 && errno
!= EEXIST
)
2184 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2185 * without a rootfs. */
2186 static inline int mount_entry_on_generic(struct mntent
*mntent
,
2188 const struct lxc_rootfs
*rootfs
,
2189 const char *lxc_name
,
2190 const char *lxc_path
)
2192 __do_free
char *mntdata
= NULL
;
2194 unsigned long mntflags
;
2195 bool dev
, optional
, relative
;
2196 unsigned long pflags
= 0;
2197 char *rootfs_path
= NULL
;
2199 optional
= hasmntopt(mntent
, "optional") != NULL
;
2200 dev
= hasmntopt(mntent
, "dev") != NULL
;
2201 relative
= hasmntopt(mntent
, "relative") != NULL
;
2203 if (rootfs
&& rootfs
->path
)
2204 rootfs_path
= rootfs
->mount
;
2206 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
2214 cull_mntent_opt(mntent
);
2216 ret
= parse_propagationopts(mntent
->mnt_opts
, &pflags
);
2220 ret
= parse_mntopts(mntent
->mnt_opts
, &mntflags
, &mntdata
);
2224 ret
= mount_entry(mntent
->mnt_fsname
, path
, mntent
->mnt_type
, mntflags
,
2225 pflags
, mntdata
, optional
, dev
, relative
, rootfs_path
);
2230 static inline int mount_entry_on_systemfs(struct mntent
*mntent
)
2233 char path
[PATH_MAX
];
2235 /* For containers created without a rootfs all mounts are treated as
2236 * absolute paths starting at / on the host.
2238 if (mntent
->mnt_dir
[0] != '/')
2239 ret
= snprintf(path
, sizeof(path
), "/%s", mntent
->mnt_dir
);
2241 ret
= snprintf(path
, sizeof(path
), "%s", mntent
->mnt_dir
);
2242 if (ret
< 0 || ret
>= sizeof(path
))
2245 return mount_entry_on_generic(mntent
, path
, NULL
, NULL
, NULL
);
2248 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
2249 const struct lxc_rootfs
*rootfs
,
2250 const char *lxc_name
,
2251 const char *lxc_path
)
2255 const char *lxcpath
;
2256 char path
[PATH_MAX
];
2259 lxcpath
= lxc_global_config_value("lxc.lxcpath");
2263 /* If rootfs->path is a blockdev path, allow container fstab to use
2264 * <lxcpath>/<name>/rootfs" as the target prefix.
2266 ret
= snprintf(path
, PATH_MAX
, "%s/%s/rootfs", lxcpath
, lxc_name
);
2267 if (ret
< 0 || ret
>= PATH_MAX
)
2270 aux
= strstr(mntent
->mnt_dir
, path
);
2272 offset
= strlen(path
);
2277 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
2279 WARN("Ignoring mount point \"%s\"", mntent
->mnt_dir
);
2282 offset
= strlen(rootfs
->path
);
2285 ret
= snprintf(path
, PATH_MAX
, "%s/%s", rootfs
->mount
, aux
+ offset
);
2286 if (ret
< 0 || ret
>= PATH_MAX
)
2289 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2292 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
2293 const struct lxc_rootfs
*rootfs
,
2294 const char *lxc_name
,
2295 const char *lxc_path
)
2298 char path
[PATH_MAX
];
2300 /* relative to root mount point */
2301 ret
= snprintf(path
, sizeof(path
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2302 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
2305 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2308 static int mount_file_entries(const struct lxc_conf
*conf
,
2309 const struct lxc_rootfs
*rootfs
, FILE *file
,
2310 const char *lxc_name
, const char *lxc_path
)
2313 struct mntent mntent
;
2315 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2319 ret
= mount_entry_on_systemfs(&mntent
);
2320 else if (mntent
.mnt_dir
[0] != '/')
2321 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2322 lxc_name
, lxc_path
);
2324 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2325 lxc_name
, lxc_path
);
2330 if (!feof(file
) || ferror(file
)) {
2331 ERROR("Failed to parse mount entries");
2338 static int setup_mount(const struct lxc_conf
*conf
,
2339 const struct lxc_rootfs
*rootfs
, const char *fstab
,
2340 const char *lxc_name
, const char *lxc_path
)
2348 f
= setmntent(fstab
, "r");
2350 SYSERROR("Failed to open \"%s\"", fstab
);
2354 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2356 ERROR("Failed to set up mount entries");
2363 * In order for nested containers to be able to mount /proc and /sys they need
2364 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2366 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2367 * apparmor rule to deny access to them. This is mostly for convenience: The
2368 * container's root user can mount them anyway and thus has access to the two
2369 * file systems. But a non-root user in the container should not be allowed to
2370 * access them as a side effect without explicitly allowing it.
2372 static const char nesting_helpers
[] =
2373 "proc dev/.lxc/proc proc create=dir,optional 0 0\n"
2374 "sys dev/.lxc/sys sysfs create=dir,optional 0 0\n";
2376 FILE *make_anonymous_mount_file(struct lxc_list
*mount
,
2377 bool include_nesting_helpers
)
2379 __do_close_prot_errno
int fd
= -EBADF
;
2382 struct lxc_list
*iterator
;
2384 fd
= memfd_create(".lxc_mount_file", MFD_CLOEXEC
);
2386 char template[] = P_tmpdir
"/.lxc_mount_file_XXXXXX";
2388 if (errno
!= ENOSYS
)
2391 fd
= lxc_make_tmpfile(template, true);
2393 SYSERROR("Could not create temporary mount file");
2397 TRACE("Created temporary mount file");
2400 lxc_list_for_each (iterator
, mount
) {
2403 mount_entry
= iterator
->elem
;
2404 len
= strlen(mount_entry
);
2406 ret
= lxc_write_nointr(fd
, mount_entry
, len
);
2410 ret
= lxc_write_nointr(fd
, "\n", 1);
2415 if (include_nesting_helpers
) {
2416 ret
= lxc_write_nointr(fd
, nesting_helpers
,
2417 STRARRAYLEN(nesting_helpers
));
2418 if (ret
!= STRARRAYLEN(nesting_helpers
))
2422 ret
= lseek(fd
, 0, SEEK_SET
);
2426 return fdopen(move_fd(fd
), "r+");
2429 static int setup_mount_entries(const struct lxc_conf
*conf
,
2430 const struct lxc_rootfs
*rootfs
,
2431 struct lxc_list
*mount
, const char *lxc_name
,
2432 const char *lxc_path
)
2434 __do_fclose
FILE *f
= NULL
;
2436 f
= make_anonymous_mount_file(mount
, conf
->lsm_aa_allow_nesting
);
2440 return mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2443 static int parse_cap(const char *cap
)
2447 size_t end
= sizeof(caps_opt
) / sizeof(caps_opt
[0]);
2450 if (strcmp(cap
, "none") == 0)
2453 for (i
= 0; i
< end
; i
++) {
2454 if (strcmp(cap
, caps_opt
[i
].name
))
2457 capid
= caps_opt
[i
].value
;
2462 /* Try to see if it's numeric, so the user may specify
2463 * capabilities that the running kernel knows about but we
2467 capid
= strtol(cap
, &ptr
, 10);
2468 if (!ptr
|| *ptr
!= '\0' || errno
!= 0)
2469 /* not a valid number */
2471 else if (capid
> lxc_caps_last_cap())
2472 /* we have a number but it's not a valid
2480 int in_caplist(int cap
, struct lxc_list
*caps
)
2483 struct lxc_list
*iterator
;
2485 lxc_list_for_each (iterator
, caps
) {
2486 capid
= parse_cap(iterator
->elem
);
2494 static int setup_caps(struct lxc_list
*caps
)
2498 struct lxc_list
*iterator
;
2500 lxc_list_for_each (iterator
, caps
) {
2503 drop_entry
= iterator
->elem
;
2505 capid
= parse_cap(drop_entry
);
2507 ERROR("unknown capability %s", drop_entry
);
2511 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(capid
), prctl_arg(0),
2512 prctl_arg(0), prctl_arg(0));
2514 SYSERROR("Failed to remove %s capability", drop_entry
);
2517 DEBUG("Dropped %s (%d) capability", drop_entry
, capid
);
2520 DEBUG("Capabilities have been setup");
2524 static int dropcaps_except(struct lxc_list
*caps
)
2526 __do_free
int *caplist
= NULL
;
2527 int i
, capid
, numcaps
;
2529 struct lxc_list
*iterator
;
2531 numcaps
= lxc_caps_last_cap() + 1;
2532 if (numcaps
<= 0 || numcaps
> 200)
2534 TRACE("Found %d capabilities", numcaps
);
2536 /* caplist[i] is 1 if we keep capability i */
2537 caplist
= must_realloc(NULL
, numcaps
* sizeof(int));
2538 memset(caplist
, 0, numcaps
* sizeof(int));
2540 lxc_list_for_each (iterator
, caps
) {
2541 keep_entry
= iterator
->elem
;
2543 capid
= parse_cap(keep_entry
);
2548 ERROR("Unknown capability %s", keep_entry
);
2552 DEBUG("Keep capability %s (%d)", keep_entry
, capid
);
2556 for (i
= 0; i
< numcaps
; i
++) {
2562 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(i
), prctl_arg(0),
2563 prctl_arg(0), prctl_arg(0));
2565 SYSERROR("Failed to remove capability %d", i
);
2570 DEBUG("Capabilities have been setup");
2574 static int parse_resource(const char *res
)
2580 for (i
= 0; i
< sizeof(limit_opt
) / sizeof(limit_opt
[0]); ++i
)
2581 if (strcmp(res
, limit_opt
[i
].name
) == 0)
2582 return limit_opt
[i
].value
;
2584 /* Try to see if it's numeric, so the user may specify
2585 * resources that the running kernel knows about but
2588 ret
= lxc_safe_int(res
, &resid
);
2595 int setup_resource_limits(struct lxc_list
*limits
, pid_t pid
)
2598 struct lxc_list
*it
;
2599 struct lxc_limit
*lim
;
2601 lxc_list_for_each (it
, limits
) {
2604 resid
= parse_resource(lim
->resource
);
2606 ERROR("Unknown resource %s", lim
->resource
);
2610 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
2611 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0) {
2612 SYSERROR("Failed to set limit %s", lim
->resource
);
2616 TRACE("Setup \"%s\" limit", lim
->resource
);
2618 ERROR("Cannot set limit \"%s\" as prlimit is missing", lim
->resource
);
2626 int setup_sysctl_parameters(struct lxc_list
*sysctls
)
2628 __do_free
char *tmp
= NULL
;
2629 struct lxc_list
*it
;
2630 struct lxc_sysctl
*elem
;
2632 char filename
[PATH_MAX
] = {0};
2634 lxc_list_for_each (it
, sysctls
) {
2636 tmp
= lxc_string_replace(".", "/", elem
->key
);
2638 ERROR("Failed to replace key %s", elem
->key
);
2642 ret
= snprintf(filename
, sizeof(filename
), "/proc/sys/%s", tmp
);
2643 if (ret
< 0 || (size_t)ret
>= sizeof(filename
)) {
2644 ERROR("Error setting up sysctl parameters path");
2648 ret
= lxc_write_to_file(filename
, elem
->value
,
2649 strlen(elem
->value
), false, 0666);
2651 SYSERROR("Failed to setup sysctl parameters %s to %s",
2652 elem
->key
, elem
->value
);
2660 int setup_proc_filesystem(struct lxc_list
*procs
, pid_t pid
)
2662 __do_free
char *tmp
= NULL
;
2663 struct lxc_list
*it
;
2664 struct lxc_proc
*elem
;
2666 char filename
[PATH_MAX
] = {0};
2668 lxc_list_for_each (it
, procs
) {
2670 tmp
= lxc_string_replace(".", "/", elem
->filename
);
2672 ERROR("Failed to replace key %s", elem
->filename
);
2676 ret
= snprintf(filename
, sizeof(filename
), "/proc/%d/%s", pid
, tmp
);
2677 if (ret
< 0 || (size_t)ret
>= sizeof(filename
)) {
2678 ERROR("Error setting up proc filesystem path");
2682 ret
= lxc_write_to_file(filename
, elem
->value
,
2683 strlen(elem
->value
), false, 0666);
2685 SYSERROR("Failed to setup proc filesystem %s to %s",
2686 elem
->filename
, elem
->value
);
2694 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
2696 struct lxc_conf
*lxc_conf_init(void)
2699 struct lxc_conf
*new;
2701 new = malloc(sizeof(*new));
2704 memset(new, 0, sizeof(*new));
2706 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
2707 new->personality
= -1;
2709 new->console
.buffer_size
= 0;
2710 new->console
.log_path
= NULL
;
2711 new->console
.log_fd
= -1;
2712 new->console
.log_size
= 0;
2713 new->console
.path
= NULL
;
2714 new->console
.peer
= -1;
2715 new->console
.proxy
.busy
= -1;
2716 new->console
.proxy
.master
= -1;
2717 new->console
.proxy
.slave
= -1;
2718 new->console
.master
= -1;
2719 new->console
.slave
= -1;
2720 new->console
.name
[0] = '\0';
2721 memset(&new->console
.ringbuf
, 0, sizeof(struct lxc_ringbuf
));
2722 new->maincmd_fd
= -1;
2723 new->monitor_signal_pdeath
= SIGKILL
;
2725 new->rootfs
.mount
= strdup(default_rootfs_mount
);
2726 if (!new->rootfs
.mount
) {
2730 new->rootfs
.managed
= true;
2732 lxc_list_init(&new->cgroup
);
2733 lxc_list_init(&new->cgroup2
);
2734 lxc_list_init(&new->network
);
2735 lxc_list_init(&new->mount_list
);
2736 lxc_list_init(&new->caps
);
2737 lxc_list_init(&new->keepcaps
);
2738 lxc_list_init(&new->id_map
);
2739 new->root_nsuid_map
= NULL
;
2740 new->root_nsgid_map
= NULL
;
2741 lxc_list_init(&new->includes
);
2742 lxc_list_init(&new->aliens
);
2743 lxc_list_init(&new->environment
);
2744 lxc_list_init(&new->limits
);
2745 lxc_list_init(&new->sysctls
);
2746 lxc_list_init(&new->procs
);
2747 new->hooks_version
= 0;
2748 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++)
2749 lxc_list_init(&new->hooks
[i
]);
2750 lxc_list_init(&new->groups
);
2751 lxc_list_init(&new->state_clients
);
2752 new->lsm_aa_profile
= NULL
;
2753 lxc_list_init(&new->lsm_aa_raw
);
2754 new->lsm_se_context
= NULL
;
2755 new->tmp_umount_proc
= false;
2756 new->tmp_umount_proc
= 0;
2757 new->shmount
.path_host
= NULL
;
2758 new->shmount
.path_cont
= NULL
;
2760 /* if running in a new user namespace, init and COMMAND
2761 * default to running as UID/GID 0 when using lxc-execute */
2764 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
2765 memset(&new->ns_share
, 0, sizeof(char *) * LXC_NS_MAX
);
2770 int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
2773 __do_close_prot_errno
int fd
= -EBADF
;
2775 char path
[PATH_MAX
];
2777 if (geteuid() != 0 && idtype
== ID_TYPE_GID
) {
2778 __do_close_prot_errno
int setgroups_fd
= -EBADF
;
2780 ret
= snprintf(path
, PATH_MAX
, "/proc/%d/setgroups", pid
);
2781 if (ret
< 0 || ret
>= PATH_MAX
)
2784 setgroups_fd
= open(path
, O_WRONLY
);
2785 if (setgroups_fd
< 0 && errno
!= ENOENT
) {
2786 SYSERROR("Failed to open \"%s\"", path
);
2790 if (setgroups_fd
>= 0) {
2791 ret
= lxc_write_nointr(setgroups_fd
, "deny\n",
2792 STRLITERALLEN("deny\n"));
2793 if (ret
!= STRLITERALLEN("deny\n")) {
2794 SYSERROR("Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid
);
2797 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid
);
2801 ret
= snprintf(path
, PATH_MAX
, "/proc/%d/%cid_map", pid
,
2802 idtype
== ID_TYPE_UID
? 'u' : 'g');
2803 if (ret
< 0 || ret
>= PATH_MAX
)
2806 fd
= open(path
, O_WRONLY
);
2808 SYSERROR("Failed to open \"%s\"", path
);
2812 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
2813 if (ret
!= buf_size
) {
2814 SYSERROR("Failed to write %cid mapping to \"%s\"",
2815 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
2822 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2824 * @return 1 if functional binary was found
2825 * @return 0 if binary exists but is lacking privilege
2826 * @return -ENOENT if binary does not exist
2827 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2829 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
2831 __do_free
char *path
= NULL
;
2836 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
2840 path
= on_path(binary
, NULL
);
2844 ret
= stat(path
, &st
);
2848 /* Check if the binary is setuid. */
2849 if (st
.st_mode
& S_ISUID
) {
2850 DEBUG("The binary \"%s\" does have the setuid bit set", path
);
2854 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
2855 /* Check if it has the CAP_SETUID capability. */
2856 if ((cap
& CAP_SETUID
) &&
2857 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
2858 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
)) {
2859 DEBUG("The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE "
2860 "and CAP_PERMITTED sets", path
);
2864 /* Check if it has the CAP_SETGID capability. */
2865 if ((cap
& CAP_SETGID
) &&
2866 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
2867 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
)) {
2868 DEBUG("The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE "
2869 "and CAP_PERMITTED sets", path
);
2873 /* If we cannot check for file capabilities we need to give the benefit
2874 * of the doubt. Otherwise we might fail even though all the necessary
2875 * file capabilities are set.
2877 DEBUG("Cannot check for file capabilities as full capability support is "
2878 "missing. Manual intervention needed");
2884 int lxc_map_ids_exec_wrapper(void *args
)
2886 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
2890 int lxc_map_ids(struct lxc_list
*idmap
, pid_t pid
)
2895 char cmd_output
[PATH_MAX
];
2897 struct lxc_list
*iterator
;
2899 /* strlen("new@idmap") = 9
2903 * INTTYPE_TO_STRLEN(uint32_t)
2907 * We add some additional space to make sure that we really have
2908 * LXC_IDMAPLEN bytes available for our the {g,u]id mapping.
2910 int ret
= 0, gidmap
= 0, uidmap
= 0;
2911 char mapbuf
[9 + 1 + INTTYPE_TO_STRLEN(uint32_t) + 1 + LXC_IDMAPLEN
] = {0};
2912 bool had_entry
= false, use_shadow
= false;
2913 int hostuid
, hostgid
;
2915 hostuid
= geteuid();
2916 hostgid
= getegid();
2918 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2919 * ranges, then insist that root also reserve ranges in subuid. This
2920 * will protected it by preventing another user from being handed the
2923 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
2924 if (uidmap
== -ENOENT
)
2925 WARN("newuidmap binary is missing");
2927 WARN("newuidmap is lacking necessary privileges");
2929 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
2930 if (gidmap
== -ENOENT
)
2931 WARN("newgidmap binary is missing");
2933 WARN("newgidmap is lacking necessary privileges");
2935 if (uidmap
> 0 && gidmap
> 0) {
2936 DEBUG("Functional newuidmap and newgidmap binary found");
2939 /* In case unprivileged users run application containers via
2940 * execute() or a start*() there are valid cases where they may
2941 * only want to map their own {g,u}id. Let's not block them from
2942 * doing so by requiring geteuid() == 0.
2944 DEBUG("No newuidmap and newgidmap binary found. Trying to "
2945 "write directly with euid %d", hostuid
);
2948 /* Check if we really need to use newuidmap and newgidmap.
2949 * If the user is only remapping his own {g,u}id, we don't need it.
2951 if (use_shadow
&& lxc_list_len(idmap
) == 2) {
2953 lxc_list_for_each(iterator
, idmap
) {
2954 map
= iterator
->elem
;
2955 if (map
->idtype
== ID_TYPE_UID
&& map
->range
== 1 &&
2956 map
->nsid
== hostuid
&& map
->hostid
== hostuid
)
2958 if (map
->idtype
== ID_TYPE_GID
&& map
->range
== 1 &&
2959 map
->nsid
== hostgid
&& map
->hostid
== hostgid
)
2966 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
2967 type
++, u_or_g
= 'g') {
2971 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
2973 lxc_list_for_each(iterator
, idmap
) {
2974 map
= iterator
->elem
;
2975 if (map
->idtype
!= type
)
2980 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
2981 fill
= snprintf(pos
, left
, "%s%lu %lu %lu%s",
2982 use_shadow
? " " : "", map
->nsid
,
2983 map
->hostid
, map
->range
,
2984 use_shadow
? "" : "\n");
2985 if (fill
<= 0 || fill
>= left
) {
2986 /* The kernel only takes <= 4k for writes to
2987 * /proc/<pid>/{g,u}id_map
2989 SYSERROR("Too many %cid mappings defined", u_or_g
);
2998 /* Try to catch the output of new{g,u}idmap to make debugging
3002 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3003 lxc_map_ids_exec_wrapper
,
3006 ERROR("new%cidmap failed to write mapping \"%s\": %s",
3007 u_or_g
, cmd_output
, mapbuf
);
3010 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g
, mapbuf
);
3012 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
3014 ERROR("Failed to write mapping: %s", mapbuf
);
3017 TRACE("Wrote mapping \"%s\"", mapbuf
);
3020 memset(mapbuf
, 0, sizeof(mapbuf
));
3026 /* Return the host uid/gid to which the container root is mapped in val.
3027 * Return true if id was found, false otherwise.
3029 bool get_mapped_rootid(struct lxc_conf
*conf
, enum idtype idtype
,
3034 struct lxc_list
*it
;
3036 if (idtype
== ID_TYPE_UID
)
3037 nsid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
3039 nsid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
3041 lxc_list_for_each (it
, &conf
->id_map
) {
3043 if (map
->idtype
!= idtype
)
3045 if (map
->nsid
!= nsid
)
3054 int mapped_hostid(unsigned id
, struct lxc_conf
*conf
, enum idtype idtype
)
3057 struct lxc_list
*it
;
3059 lxc_list_for_each (it
, &conf
->id_map
) {
3061 if (map
->idtype
!= idtype
)
3064 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
3065 return (id
- map
->hostid
) + map
->nsid
;
3071 int find_unmapped_nsid(struct lxc_conf
*conf
, enum idtype idtype
)
3074 struct lxc_list
*it
;
3075 unsigned int freeid
= 0;
3078 lxc_list_for_each (it
, &conf
->id_map
) {
3080 if (map
->idtype
!= idtype
)
3083 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
3084 freeid
= map
->nsid
+ map
->range
;
3092 int chown_mapped_root_exec_wrapper(void *args
)
3094 execvp("lxc-usernsexec", args
);
3098 /* chown_mapped_root: for an unprivileged user with uid/gid X to
3099 * chown a dir to subuid/subgid Y, he needs to run chown as root
3100 * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and
3101 * nsid Y is mapped to hostuid/hostgid X. That way, the container
3102 * root is privileged with respect to hostuid/hostgid X, allowing
3103 * him to do the chown.
3105 int chown_mapped_root(const char *path
, struct lxc_conf
*conf
)
3107 uid_t rootuid
, rootgid
;
3109 int hostuid
, hostgid
, ret
;
3111 char map1
[100], map2
[100], map3
[100], map4
[100], map5
[100];
3113 const char *args1
[] = {"lxc-usernsexec",
3118 "--", "chown", ugid
, path
,
3120 const char *args2
[] = {"lxc-usernsexec",
3126 "--", "chown", ugid
, path
,
3128 char cmd_output
[PATH_MAX
];
3130 hostuid
= geteuid();
3131 hostgid
= getegid();
3133 if (!get_mapped_rootid(conf
, ID_TYPE_UID
, &val
)) {
3134 ERROR("No uid mapping for container root");
3137 rootuid
= (uid_t
)val
;
3139 if (!get_mapped_rootid(conf
, ID_TYPE_GID
, &val
)) {
3140 ERROR("No gid mapping for container root");
3143 rootgid
= (gid_t
)val
;
3146 if (chown(path
, rootuid
, rootgid
) < 0) {
3147 ERROR("Error chowning %s", path
);
3154 if (rootuid
== hostuid
) {
3156 INFO("Container root is our uid; no need to chown");
3160 /* save the current gid of "path" */
3161 if (stat(path
, &sb
) < 0) {
3162 ERROR("Error stat %s", path
);
3166 /* Update the path argument in case this was overlayfs. */
3167 args1
[sizeof(args1
) / sizeof(args1
[0]) - 2] = path
;
3168 args2
[sizeof(args2
) / sizeof(args2
[0]) - 2] = path
;
3171 * A file has to be group-owned by a gid mapped into the
3172 * container, or the container won't be privileged over it.
3174 DEBUG("trying to chown \"%s\" to %d", path
, hostgid
);
3175 if (sb
.st_uid
== hostuid
&&
3176 mapped_hostid(sb
.st_gid
, conf
, ID_TYPE_GID
) < 0 &&
3177 chown(path
, -1, hostgid
) < 0) {
3178 ERROR("Failed chgrping %s", path
);
3182 /* "u:0:rootuid:1" */
3183 ret
= snprintf(map1
, 100, "u:0:%d:1", rootuid
);
3184 if (ret
< 0 || ret
>= 100) {
3185 ERROR("Error uid printing map string");
3189 /* "u:hostuid:hostuid:1" */
3190 ret
= snprintf(map2
, 100, "u:%d:%d:1", hostuid
, hostuid
);
3191 if (ret
< 0 || ret
>= 100) {
3192 ERROR("Error uid printing map string");
3196 /* "g:0:rootgid:1" */
3197 ret
= snprintf(map3
, 100, "g:0:%d:1", rootgid
);
3198 if (ret
< 0 || ret
>= 100) {
3199 ERROR("Error gid printing map string");
3203 /* "g:pathgid:rootgid+pathgid:1" */
3204 ret
= snprintf(map4
, 100, "g:%d:%d:1", (gid_t
)sb
.st_gid
,
3205 rootgid
+ (gid_t
)sb
.st_gid
);
3206 if (ret
< 0 || ret
>= 100) {
3207 ERROR("Error gid printing map string");
3211 /* "g:hostgid:hostgid:1" */
3212 ret
= snprintf(map5
, 100, "g:%d:%d:1", hostgid
, hostgid
);
3213 if (ret
< 0 || ret
>= 100) {
3214 ERROR("Error gid printing map string");
3218 /* "0:pathgid" (chown) */
3219 ret
= snprintf(ugid
, 100, "0:%d", (gid_t
)sb
.st_gid
);
3220 if (ret
< 0 || ret
>= 100) {
3221 ERROR("Error owner printing format string for chown");
3225 if (hostgid
== sb
.st_gid
)
3226 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3227 chown_mapped_root_exec_wrapper
,
3230 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3231 chown_mapped_root_exec_wrapper
,
3234 ERROR("lxc-usernsexec failed: %s", cmd_output
);
3239 /* NOTE: Must not be called from inside the container namespace! */
3240 int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
3244 mounted
= lxc_mount_proc_if_needed(conf
->rootfs
.path
? conf
->rootfs
.mount
: "");
3245 if (mounted
== -1) {
3246 SYSERROR("Failed to mount proc in the container");
3247 /* continue only if there is no rootfs */
3248 if (conf
->rootfs
.path
)
3250 } else if (mounted
== 1) {
3251 conf
->tmp_umount_proc
= true;
3257 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
3259 if (!lxc_conf
->tmp_umount_proc
)
3262 (void)umount2("/proc", MNT_DETACH
);
3263 lxc_conf
->tmp_umount_proc
= false;
3266 /* Walk /proc/mounts and change any shared entries to slave. */
3267 void remount_all_slave(void)
3269 __do_free
char *line
= NULL
;
3270 __do_fclose
FILE *f
= NULL
;
3271 __do_close_prot_errno
int memfd
= -EBADF
, mntinfo_fd
= -EBADF
;
3276 mntinfo_fd
= open("/proc/self/mountinfo", O_RDONLY
| O_CLOEXEC
);
3277 if (mntinfo_fd
< 0) {
3278 SYSERROR("Failed to open \"/proc/self/mountinfo\"");
3282 memfd
= memfd_create(".lxc_mountinfo", MFD_CLOEXEC
);
3284 char template[] = P_tmpdir
"/.lxc_mountinfo_XXXXXX";
3286 if (errno
!= ENOSYS
) {
3287 SYSERROR("Failed to create temporary in-memory file");
3291 memfd
= lxc_make_tmpfile(template, true);
3293 WARN("Failed to create temporary file");
3299 copied
= lxc_sendfile_nointr(memfd
, mntinfo_fd
, NULL
, LXC_SENDFILE_MAX
);
3304 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
3308 ret
= lseek(memfd
, 0, SEEK_SET
);
3310 SYSERROR("Failed to reset file descriptor offset");
3314 f
= fdopen(memfd
, "r");
3316 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark all shared. Continuing");
3321 * After a successful fdopen() memfd will be closed when calling
3322 * fclose(f). Calling close(memfd) afterwards is undefined.
3326 while (getline(&line
, &len
, f
) != -1) {
3327 char *opts
, *target
;
3329 target
= get_field(line
, 4);
3333 opts
= get_field(target
, 2);
3337 null_endofword(opts
);
3338 if (!strstr(opts
, "shared"))
3341 null_endofword(target
);
3342 ret
= mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
);
3344 SYSERROR("Failed to make \"%s\" MS_SLAVE", target
);
3345 ERROR("Continuing...");
3348 TRACE("Remounted \"%s\" as MS_SLAVE", target
);
3350 TRACE("Remounted all mount table entries as MS_SLAVE");
3353 static int lxc_execute_bind_init(struct lxc_handler
*handler
)
3357 char path
[PATH_MAX
], destpath
[PATH_MAX
];
3358 struct lxc_conf
*conf
= handler
->conf
;
3360 /* If init exists in the container, don't bind mount a static one */
3361 p
= choose_init(conf
->rootfs
.mount
);
3363 __do_free
char *old
= p
;
3365 p
= strdup(old
+ strlen(conf
->rootfs
.mount
));
3369 INFO("Found existing init at \"%s\"", p
);
3373 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3374 if (ret
< 0 || ret
>= PATH_MAX
)
3377 if (!file_exists(path
)) {
3378 ERROR("The file \"%s\" does not exist on host", path
);
3382 ret
= snprintf(destpath
, PATH_MAX
, "%s" P_tmpdir
"%s", conf
->rootfs
.mount
, "/.lxc-init");
3383 if (ret
< 0 || ret
>= PATH_MAX
)
3386 if (!file_exists(destpath
)) {
3387 ret
= mknod(destpath
, S_IFREG
| 0000, 0);
3388 if (ret
< 0 && errno
!= EEXIST
) {
3389 SYSERROR("Failed to create dummy \"%s\" file as bind mount target", destpath
);
3394 ret
= safe_mount(path
, destpath
, "none", MS_BIND
, NULL
, conf
->rootfs
.mount
);
3396 SYSERROR("Failed to bind mount lxc.init.static into container");
3400 p
= strdup(destpath
+ strlen(conf
->rootfs
.mount
));
3404 INFO("Bind mounted lxc.init.static into container at \"%s\"", path
);
3406 ((struct execute_args
*)handler
->data
)->init_fd
= -1;
3407 ((struct execute_args
*)handler
->data
)->init_path
= p
;
3411 /* This does the work of remounting / if it is shared, calling the container
3412 * pre-mount hooks, and mounting the rootfs.
3414 int lxc_setup_rootfs_prepare_root(struct lxc_conf
*conf
, const char *name
,
3415 const char *lxcpath
)
3419 if (conf
->rootfs_setup
) {
3420 const char *path
= conf
->rootfs
.mount
;
3422 /* The rootfs was set up in another namespace. bind-mount it to
3423 * give us a mount in our own ns so we can pivot_root to it
3425 ret
= mount(path
, path
, "rootfs", MS_BIND
, NULL
);
3427 ERROR("Failed to bind mount container / onto itself");
3431 TRACE("Bind mounted container / onto itself");
3435 remount_all_slave();
3437 ret
= run_lxc_hooks(name
, "pre-mount", conf
, NULL
);
3439 ERROR("Failed to run pre-mount hooks");
3443 ret
= lxc_mount_rootfs(conf
);
3445 ERROR("Failed to setup rootfs for");
3449 conf
->rootfs_setup
= true;
3453 static bool verify_start_hooks(struct lxc_conf
*conf
)
3455 char path
[PATH_MAX
];
3456 struct lxc_list
*it
;
3458 lxc_list_for_each (it
, &conf
->hooks
[LXCHOOK_START
]) {
3460 char *hookname
= it
->elem
;
3462 ret
= snprintf(path
, PATH_MAX
, "%s%s",
3463 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
3465 if (ret
< 0 || ret
>= PATH_MAX
)
3468 ret
= access(path
, X_OK
);
3470 SYSERROR("Start hook \"%s\" not found in container",
3481 static bool execveat_supported(void)
3483 lxc_raw_execveat(-1, "", NULL
, NULL
, AT_EMPTY_PATH
);
3484 if (errno
== ENOSYS
)
3490 int lxc_setup(struct lxc_handler
*handler
)
3493 const char *lxcpath
= handler
->lxcpath
, *name
= handler
->name
;
3494 struct lxc_conf
*lxc_conf
= handler
->conf
;
3496 ret
= lxc_setup_rootfs_prepare_root(lxc_conf
, name
, lxcpath
);
3498 ERROR("Failed to setup rootfs");
3502 if (handler
->nsfd
[LXC_NS_UTS
] == -1) {
3503 ret
= setup_utsname(lxc_conf
->utsname
);
3505 ERROR("Failed to setup the utsname %s", name
);
3510 ret
= lxc_setup_keyring();
3514 ret
= lxc_setup_network_in_child_namespaces(lxc_conf
, &lxc_conf
->network
);
3516 ERROR("Failed to setup network");
3520 ret
= lxc_network_send_name_and_ifindex_to_parent(handler
);
3522 ERROR("Failed to send network device names and ifindices to parent");
3526 if (lxc_conf
->autodev
> 0) {
3527 ret
= mount_autodev(name
, &lxc_conf
->rootfs
, lxcpath
);
3529 ERROR("Failed to mount \"/dev\"");
3534 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
3535 * need to wait until other stuff has finished.
3537 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
, handler
);
3539 ERROR("Failed to setup first automatic mounts");
3543 ret
= setup_mount(lxc_conf
, &lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
);
3545 ERROR("Failed to setup mounts");
3549 if (lxc_conf
->is_execute
) {
3550 if (execveat_supported()) {
3552 char path
[PATH_MAX
];
3554 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3555 if (ret
< 0 || ret
>= PATH_MAX
) {
3556 ERROR("Path to init.lxc.static too long");
3560 fd
= open(path
, O_PATH
| O_CLOEXEC
);
3562 SYSERROR("Unable to open lxc.init.static");
3566 ((struct execute_args
*)handler
->data
)->init_fd
= fd
;
3567 ((struct execute_args
*)handler
->data
)->init_path
= NULL
;
3569 ret
= lxc_execute_bind_init(handler
);
3571 ERROR("Failed to bind-mount the lxc init system");
3577 /* Now mount only cgroups, if wanted. Before, /sys could not have been
3578 * mounted. It is guaranteed to be mounted now either through
3579 * automatically or via fstab entries.
3581 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
, handler
);
3583 ERROR("Failed to setup remaining automatic mounts");
3587 ret
= run_lxc_hooks(name
, "mount", lxc_conf
, NULL
);
3589 ERROR("Failed to run mount hooks");
3593 if (lxc_conf
->autodev
> 0) {
3594 ret
= run_lxc_hooks(name
, "autodev", lxc_conf
, NULL
);
3596 ERROR("Failed to run autodev hooks");
3600 ret
= lxc_fill_autodev(&lxc_conf
->rootfs
);
3602 ERROR("Failed to populate \"/dev\"");
3607 if (!lxc_list_empty(&lxc_conf
->mount_list
)) {
3608 ret
= setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
,
3609 &lxc_conf
->mount_list
, name
, lxcpath
);
3611 ERROR("Failed to setup mount entries");
3616 /* Make sure any start hooks are in the container */
3617 if (!verify_start_hooks(lxc_conf
)) {
3618 ERROR("Failed to verify start hooks");
3622 ret
= lxc_setup_console(&lxc_conf
->rootfs
, &lxc_conf
->console
,
3623 lxc_conf
->ttys
.dir
);
3625 ERROR("Failed to setup console");
3629 ret
= lxc_setup_dev_symlinks(&lxc_conf
->rootfs
);
3631 ERROR("Failed to setup \"/dev\" symlinks");
3635 ret
= lxc_create_tmp_proc_mount(lxc_conf
);
3637 ERROR("Failed to \"/proc\" LSMs");
3641 ret
= lxc_setup_rootfs_switch_root(&lxc_conf
->rootfs
);
3643 ERROR("Failed to pivot root into rootfs");
3647 ret
= lxc_setup_devpts(lxc_conf
);
3649 ERROR("Failed to setup new devpts instance");
3653 ret
= lxc_create_ttys(handler
);
3657 ret
= setup_personality(lxc_conf
->personality
);
3659 ERROR("Failed to set personality");
3663 /* Set sysctl value to a path under /proc/sys as determined from the
3664 * key. For e.g. net.ipv4.ip_forward translated to
3665 * /proc/sys/net/ipv4/ip_forward.
3667 if (!lxc_list_empty(&lxc_conf
->sysctls
)) {
3668 ret
= setup_sysctl_parameters(&lxc_conf
->sysctls
);
3670 ERROR("Failed to setup sysctl parameters");
3675 if (!lxc_list_empty(&lxc_conf
->keepcaps
)) {
3676 if (!lxc_list_empty(&lxc_conf
->caps
)) {
3677 ERROR("Container requests lxc.cap.drop and "
3678 "lxc.cap.keep: either use lxc.cap.drop or "
3679 "lxc.cap.keep, not both");
3683 if (dropcaps_except(&lxc_conf
->keepcaps
)) {
3684 ERROR("Failed to keep capabilities");
3687 } else if (setup_caps(&lxc_conf
->caps
)) {
3688 ERROR("Failed to drop capabilities");
3692 NOTICE("The container \"%s\" is set up", name
);
3697 int run_lxc_hooks(const char *name
, char *hookname
, struct lxc_conf
*conf
,
3700 struct lxc_list
*it
;
3703 if (strcmp(hookname
, "pre-start") == 0)
3704 which
= LXCHOOK_PRESTART
;
3705 else if (strcmp(hookname
, "start-host") == 0)
3706 which
= LXCHOOK_START_HOST
;
3707 else if (strcmp(hookname
, "pre-mount") == 0)
3708 which
= LXCHOOK_PREMOUNT
;
3709 else if (strcmp(hookname
, "mount") == 0)
3710 which
= LXCHOOK_MOUNT
;
3711 else if (strcmp(hookname
, "autodev") == 0)
3712 which
= LXCHOOK_AUTODEV
;
3713 else if (strcmp(hookname
, "start") == 0)
3714 which
= LXCHOOK_START
;
3715 else if (strcmp(hookname
, "stop") == 0)
3716 which
= LXCHOOK_STOP
;
3717 else if (strcmp(hookname
, "post-stop") == 0)
3718 which
= LXCHOOK_POSTSTOP
;
3719 else if (strcmp(hookname
, "clone") == 0)
3720 which
= LXCHOOK_CLONE
;
3721 else if (strcmp(hookname
, "destroy") == 0)
3722 which
= LXCHOOK_DESTROY
;
3726 lxc_list_for_each (it
, &conf
->hooks
[which
]) {
3728 char *hook
= it
->elem
;
3730 ret
= run_script_argv(name
, conf
->hooks_version
, "lxc", hook
,
3739 int lxc_clear_config_caps(struct lxc_conf
*c
)
3741 struct lxc_list
*it
, *next
;
3743 lxc_list_for_each_safe (it
, &c
->caps
, next
) {
3752 static int lxc_free_idmap(struct lxc_list
*id_map
)
3754 struct lxc_list
*it
, *next
;
3756 lxc_list_for_each_safe (it
, id_map
, next
) {
3765 int lxc_clear_idmaps(struct lxc_conf
*c
)
3767 return lxc_free_idmap(&c
->id_map
);
3770 int lxc_clear_config_keepcaps(struct lxc_conf
*c
)
3772 struct lxc_list
*it
, *next
;
3774 lxc_list_for_each_safe (it
, &c
->keepcaps
, next
) {
3783 int lxc_clear_namespace(struct lxc_conf
*c
)
3786 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
3787 free(c
->ns_share
[i
]);
3788 c
->ns_share
[i
] = NULL
;
3793 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
, int version
)
3795 char *global_token
, *namespaced_token
;
3796 size_t namespaced_token_len
;
3797 struct lxc_list
*it
, *next
, *list
;
3798 const char *k
= key
;
3801 if (version
== CGROUP2_SUPER_MAGIC
) {
3802 global_token
= "lxc.cgroup2";
3803 namespaced_token
= "lxc.cgroup2.";
3804 namespaced_token_len
= STRLITERALLEN("lxc.cgroup2.");
3806 } else if (version
== CGROUP_SUPER_MAGIC
) {
3807 global_token
= "lxc.cgroup";
3808 namespaced_token
= "lxc.cgroup.";
3809 namespaced_token_len
= STRLITERALLEN("lxc.cgroup.");
3815 if (strcmp(key
, global_token
) == 0)
3817 else if (strncmp(key
, namespaced_token
, namespaced_token_len
) == 0)
3818 k
+= namespaced_token_len
;
3822 lxc_list_for_each_safe (it
, list
, next
) {
3823 struct lxc_cgroup
*cg
= it
->elem
;
3825 if (!all
&& strcmp(cg
->subsystem
, k
) != 0)
3829 free(cg
->subsystem
);
3838 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
3840 struct lxc_list
*it
, *next
;
3841 const char *k
= NULL
;
3844 if (strcmp(key
, "lxc.limit") == 0 || strcmp(key
, "lxc.prlimit") == 0)
3846 else if (strncmp(key
, "lxc.limit.", STRLITERALLEN("lxc.limit.")) == 0)
3847 k
= key
+ STRLITERALLEN("lxc.limit.");
3848 else if (strncmp(key
, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")) == 0)
3849 k
= key
+ STRLITERALLEN("lxc.prlimit.");
3853 lxc_list_for_each_safe (it
, &c
->limits
, next
) {
3854 struct lxc_limit
*lim
= it
->elem
;
3856 if (!all
&& strcmp(lim
->resource
, k
) != 0)
3860 free(lim
->resource
);
3868 int lxc_clear_sysctls(struct lxc_conf
*c
, const char *key
)
3870 struct lxc_list
*it
, *next
;
3871 const char *k
= NULL
;
3874 if (strcmp(key
, "lxc.sysctl") == 0)
3876 else if (strncmp(key
, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")) == 0)
3877 k
= key
+ STRLITERALLEN("lxc.sysctl.");
3881 lxc_list_for_each_safe (it
, &c
->sysctls
, next
) {
3882 struct lxc_sysctl
*elem
= it
->elem
;
3884 if (!all
&& strcmp(elem
->key
, k
) != 0)
3897 int lxc_clear_procs(struct lxc_conf
*c
, const char *key
)
3899 struct lxc_list
*it
, *next
;
3900 const char *k
= NULL
;
3903 if (strcmp(key
, "lxc.proc") == 0)
3905 else if (strncmp(key
, "lxc.proc.", STRLITERALLEN("lxc.proc.")) == 0)
3906 k
= key
+ STRLITERALLEN("lxc.proc.");
3910 lxc_list_for_each_safe (it
, &c
->procs
, next
) {
3911 struct lxc_proc
*proc
= it
->elem
;
3913 if (!all
&& strcmp(proc
->filename
, k
) != 0)
3917 free(proc
->filename
);
3926 int lxc_clear_groups(struct lxc_conf
*c
)
3928 struct lxc_list
*it
, *next
;
3930 lxc_list_for_each_safe (it
, &c
->groups
, next
) {
3939 int lxc_clear_environment(struct lxc_conf
*c
)
3941 struct lxc_list
*it
, *next
;
3943 lxc_list_for_each_safe (it
, &c
->environment
, next
) {
3952 int lxc_clear_mount_entries(struct lxc_conf
*c
)
3954 struct lxc_list
*it
, *next
;
3956 lxc_list_for_each_safe (it
, &c
->mount_list
, next
) {
3965 int lxc_clear_automounts(struct lxc_conf
*c
)
3971 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
3974 struct lxc_list
*it
, *next
;
3975 const char *k
= NULL
;
3976 bool all
= false, done
= false;
3978 if (strcmp(key
, "lxc.hook") == 0)
3980 else if (strncmp(key
, "lxc.hook.", STRLITERALLEN("lxc.hook.")) == 0)
3981 k
= key
+ STRLITERALLEN("lxc.hook.");
3985 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++) {
3986 if (all
|| strcmp(k
, lxchook_names
[i
]) == 0) {
3987 lxc_list_for_each_safe (it
, &c
->hooks
[i
], next
) {
3998 ERROR("Invalid hook key: %s", key
);
4005 static inline void lxc_clear_aliens(struct lxc_conf
*conf
)
4007 struct lxc_list
*it
, *next
;
4009 lxc_list_for_each_safe (it
, &conf
->aliens
, next
) {
4016 void lxc_clear_includes(struct lxc_conf
*conf
)
4018 struct lxc_list
*it
, *next
;
4020 lxc_list_for_each_safe (it
, &conf
->includes
, next
) {
4027 int lxc_clear_apparmor_raw(struct lxc_conf
*c
)
4029 struct lxc_list
*it
, *next
;
4031 lxc_list_for_each_safe (it
, &c
->lsm_aa_raw
, next
) {
4040 void lxc_conf_free(struct lxc_conf
*conf
)
4045 if (current_config
== conf
)
4046 current_config
= NULL
;
4047 lxc_terminal_conf_free(&conf
->console
);
4048 free(conf
->rootfs
.mount
);
4049 free(conf
->rootfs
.bdev_type
);
4050 free(conf
->rootfs
.options
);
4051 free(conf
->rootfs
.path
);
4052 free(conf
->logfile
);
4053 if (conf
->logfd
!= -1)
4055 free(conf
->utsname
);
4056 free(conf
->ttys
.dir
);
4057 free(conf
->ttys
.tty_names
);
4060 free(conf
->execute_cmd
);
4061 free(conf
->init_cmd
);
4062 free(conf
->init_cwd
);
4063 free(conf
->unexpanded_config
);
4065 lxc_free_networks(&conf
->network
);
4066 free(conf
->lsm_aa_profile
);
4067 free(conf
->lsm_aa_profile_computed
);
4068 free(conf
->lsm_se_context
);
4069 lxc_seccomp_free(conf
);
4070 lxc_clear_config_caps(conf
);
4071 lxc_clear_config_keepcaps(conf
);
4072 lxc_clear_cgroups(conf
, "lxc.cgroup", CGROUP_SUPER_MAGIC
);
4073 lxc_clear_cgroups(conf
, "lxc.cgroup2", CGROUP2_SUPER_MAGIC
);
4074 lxc_clear_hooks(conf
, "lxc.hook");
4075 lxc_clear_mount_entries(conf
);
4076 lxc_clear_idmaps(conf
);
4077 lxc_clear_groups(conf
);
4078 lxc_clear_includes(conf
);
4079 lxc_clear_aliens(conf
);
4080 lxc_clear_environment(conf
);
4081 lxc_clear_limits(conf
, "lxc.prlimit");
4082 lxc_clear_sysctls(conf
, "lxc.sysctl");
4083 lxc_clear_procs(conf
, "lxc.proc");
4084 lxc_clear_apparmor_raw(conf
);
4085 lxc_clear_namespace(conf
);
4086 free(conf
->cgroup_meta
.dir
);
4087 free(conf
->cgroup_meta
.controllers
);
4088 free(conf
->shmount
.path_host
);
4089 free(conf
->shmount
.path_cont
);
4093 struct userns_fn_data
{
4095 const char *fn_name
;
4100 static int run_userns_fn(void *data
)
4104 struct userns_fn_data
*d
= data
;
4106 /* Close write end of the pipe. */
4109 /* Wait for parent to finish establishing a new mapping in the user
4110 * namespace we are executing in.
4112 ret
= lxc_read_nointr(d
->p
[0], &c
, 1);
4113 /* Close read end of the pipe. */
4119 TRACE("Calling function \"%s\"", d
->fn_name
);
4121 /* Call function to run. */
4122 return d
->fn(d
->arg
);
4125 static struct id_map
*mapped_nsid_add(struct lxc_conf
*conf
, unsigned id
,
4128 const struct id_map
*map
;
4129 struct id_map
*retmap
;
4131 map
= find_mapped_nsid_entry(conf
, id
, idtype
);
4135 retmap
= malloc(sizeof(*retmap
));
4139 memcpy(retmap
, map
, sizeof(*retmap
));
4143 static struct id_map
*find_mapped_hostid_entry(struct lxc_conf
*conf
,
4144 unsigned id
, enum idtype idtype
)
4147 struct lxc_list
*it
;
4148 struct id_map
*retmap
= NULL
;
4150 lxc_list_for_each (it
, &conf
->id_map
) {
4152 if (map
->idtype
!= idtype
)
4155 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
4164 /* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
4165 * existing one or establish a new one.
4167 static struct id_map
*mapped_hostid_add(struct lxc_conf
*conf
, uid_t id
,
4171 struct id_map
*entry
= NULL
, *tmp
= NULL
;
4173 entry
= malloc(sizeof(*entry
));
4177 /* Reuse existing mapping. */
4178 tmp
= find_mapped_hostid_entry(conf
, id
, type
);
4180 return memcpy(entry
, tmp
, sizeof(*entry
));
4182 /* Find new mapping. */
4183 hostid_mapped
= find_unmapped_nsid(conf
, type
);
4184 if (hostid_mapped
< 0) {
4185 DEBUG("Failed to find free mapping for id %d", id
);
4190 entry
->idtype
= type
;
4191 entry
->nsid
= hostid_mapped
;
4192 entry
->hostid
= (unsigned long)id
;
4198 struct lxc_list
*get_minimal_idmap(struct lxc_conf
*conf
)
4200 __do_free
struct id_map
*container_root_uid
= NULL
,
4201 *container_root_gid
= NULL
,
4202 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4203 __do_free
struct lxc_list
*idmap
= NULL
;
4205 uid_t nsuid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
4206 gid_t nsgid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
4207 struct lxc_list
*tmplist
= NULL
;
4209 /* Find container root mappings. */
4210 container_root_uid
= mapped_nsid_add(conf
, nsuid
, ID_TYPE_UID
);
4211 if (!container_root_uid
) {
4212 DEBUG("Failed to find mapping for namespace uid %d", 0);
4216 if (euid
>= container_root_uid
->hostid
&&
4217 euid
< (container_root_uid
->hostid
+ container_root_uid
->range
))
4218 host_uid_map
= container_root_uid
;
4220 container_root_gid
= mapped_nsid_add(conf
, nsgid
, ID_TYPE_GID
);
4221 if (!container_root_gid
) {
4222 DEBUG("Failed to find mapping for namespace gid %d", 0);
4226 if (egid
>= container_root_gid
->hostid
&&
4227 egid
< (container_root_gid
->hostid
+ container_root_gid
->range
))
4228 host_gid_map
= container_root_gid
;
4230 /* Check whether the {g,u}id of the user has a mapping. */
4232 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4233 if (!host_uid_map
) {
4234 DEBUG("Failed to find mapping for uid %d", euid
);
4239 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4240 if (!host_gid_map
) {
4241 DEBUG("Failed to find mapping for gid %d", egid
);
4245 /* Allocate new {g,u}id map list. */
4246 idmap
= malloc(sizeof(*idmap
));
4249 lxc_list_init(idmap
);
4251 /* Add container root to the map. */
4252 tmplist
= malloc(sizeof(*tmplist
));
4255 lxc_list_add_elem(tmplist
, container_root_uid
);
4256 lxc_list_add_tail(idmap
, tmplist
);
4258 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4259 /* idmap will now keep track of that memory. */
4260 move_ptr(container_root_uid
);
4262 /* Add container root to the map. */
4263 tmplist
= malloc(sizeof(*tmplist
));
4266 lxc_list_add_elem(tmplist
, host_uid_map
);
4267 lxc_list_add_tail(idmap
, tmplist
);
4269 /* idmap will now keep track of that memory. */
4270 move_ptr(container_root_uid
);
4271 /* idmap will now keep track of that memory. */
4272 move_ptr(host_uid_map
);
4274 tmplist
= malloc(sizeof(*tmplist
));
4277 lxc_list_add_elem(tmplist
, container_root_gid
);
4278 lxc_list_add_tail(idmap
, tmplist
);
4280 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4281 /* idmap will now keep track of that memory. */
4282 move_ptr(container_root_gid
);
4284 tmplist
= malloc(sizeof(*tmplist
));
4287 lxc_list_add_elem(tmplist
, host_gid_map
);
4288 lxc_list_add_tail(idmap
, tmplist
);
4290 /* idmap will now keep track of that memory. */
4291 move_ptr(container_root_gid
);
4292 /* idmap will now keep track of that memory. */
4293 move_ptr(host_gid_map
);
4295 TRACE("Allocated minimal idmapping");
4296 return move_ptr(idmap
);
4299 /* Run a function in a new user namespace.
4300 * The caller's euid/egid will be mapped if it is not already.
4301 * Afaict, userns_exec_1() is only used to operate based on privileges for the
4302 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
4303 * This means we require only to establish a mapping from:
4304 * - the container root {g,u}id as seen from the host > user's host {g,u}id
4305 * - the container root -> some sub{g,u}id
4306 * The former we add, if the user did not specify a mapping. The latter we
4307 * retrieve from the container's configured {g,u}id mappings as it must have been
4308 * there to start the container in the first place.
4310 int userns_exec_1(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4311 const char *fn_name
)
4315 struct userns_fn_data d
;
4316 struct lxc_list
*idmap
;
4317 int ret
= -1, status
= -1;
4323 idmap
= get_minimal_idmap(conf
);
4327 ret
= pipe2(p
, O_CLOEXEC
);
4329 SYSERROR("Failed to create pipe");
4333 d
.fn_name
= fn_name
;
4338 /* Clone child in new user namespace. */
4339 pid
= lxc_raw_clone_cb(run_userns_fn
, &d
, CLONE_NEWUSER
);
4341 ERROR("Failed to clone process in new user namespace");
4348 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4349 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4351 struct lxc_list
*it
;
4353 lxc_list_for_each (it
, idmap
) {
4355 TRACE("Establishing %cid mapping for \"%d\" in new "
4356 "user namespace: nsuid %lu - hostid %lu - range "
4358 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4359 map
->nsid
, map
->hostid
, map
->range
);
4363 /* Set up {g,u}id mapping for user namespace of child process. */
4364 ret
= lxc_map_ids(idmap
, pid
);
4366 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
4370 /* Tell child to proceed. */
4371 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4372 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4381 /* Wait for child to finish. */
4383 status
= wait_for_pid(pid
);
4391 int userns_exec_full(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4392 const char *fn_name
)
4398 struct lxc_list
*cur
;
4399 struct userns_fn_data d
;
4402 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
4403 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
4404 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4409 ret
= pipe2(p
, O_CLOEXEC
);
4411 SYSERROR("opening pipe");
4415 d
.fn_name
= fn_name
;
4420 /* Clone child in new user namespace. */
4421 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
);
4423 ERROR("Failed to clone process in new user namespace");
4433 /* Allocate new {g,u}id map list. */
4434 idmap
= malloc(sizeof(*idmap
));
4437 lxc_list_init(idmap
);
4439 /* Find container root. */
4440 lxc_list_for_each (cur
, &conf
->id_map
) {
4441 struct id_map
*tmpmap
;
4443 tmplist
= malloc(sizeof(*tmplist
));
4447 tmpmap
= malloc(sizeof(*tmpmap
));
4453 memset(tmpmap
, 0, sizeof(*tmpmap
));
4454 memcpy(tmpmap
, cur
->elem
, sizeof(*tmpmap
));
4455 tmplist
->elem
= tmpmap
;
4457 lxc_list_add_tail(idmap
, tmplist
);
4461 if (map
->idtype
== ID_TYPE_UID
)
4462 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
4465 if (map
->idtype
== ID_TYPE_GID
)
4466 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
4472 if (map
->idtype
== ID_TYPE_UID
)
4473 if (container_root_uid
== NULL
)
4474 container_root_uid
= map
;
4476 if (map
->idtype
== ID_TYPE_GID
)
4477 if (container_root_gid
== NULL
)
4478 container_root_gid
= map
;
4481 if (!container_root_uid
|| !container_root_gid
) {
4482 ERROR("No mapping for container root found");
4486 /* Check whether the {g,u}id of the user has a mapping. */
4488 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4490 host_uid_map
= container_root_uid
;
4493 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4495 host_gid_map
= container_root_gid
;
4497 if (!host_uid_map
) {
4498 DEBUG("Failed to find mapping for uid %d", euid
);
4502 if (!host_gid_map
) {
4503 DEBUG("Failed to find mapping for gid %d", egid
);
4507 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4508 /* Add container root to the map. */
4509 tmplist
= malloc(sizeof(*tmplist
));
4512 lxc_list_add_elem(tmplist
, host_uid_map
);
4513 lxc_list_add_tail(idmap
, tmplist
);
4515 /* idmap will now keep track of that memory. */
4516 host_uid_map
= NULL
;
4518 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4519 tmplist
= malloc(sizeof(*tmplist
));
4522 lxc_list_add_elem(tmplist
, host_gid_map
);
4523 lxc_list_add_tail(idmap
, tmplist
);
4525 /* idmap will now keep track of that memory. */
4526 host_gid_map
= NULL
;
4528 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4529 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4530 lxc_list_for_each (cur
, idmap
) {
4532 TRACE("establishing %cid mapping for \"%d\" in new "
4533 "user namespace: nsuid %lu - hostid %lu - range "
4535 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4536 map
->nsid
, map
->hostid
, map
->range
);
4540 /* Set up {g,u}id mapping for user namespace of child process. */
4541 ret
= lxc_map_ids(idmap
, pid
);
4543 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid
);
4547 /* Tell child to proceed. */
4548 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4549 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4558 /* Wait for child to finish. */
4560 ret
= wait_for_pid(pid
);
4563 lxc_free_idmap(idmap
);
4567 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
4569 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
4575 /* not thread-safe, do not use from api without first forking */
4576 static char *getuname(void)
4578 __do_free
char *buf
= NULL
;
4579 struct passwd pwent
;
4580 struct passwd
*pwentp
= NULL
;
4584 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
4588 buf
= malloc(bufsize
);
4592 ret
= getpwuid_r(geteuid(), &pwent
, buf
, bufsize
, &pwentp
);
4595 WARN("Could not find matched password record.");
4597 ERROR("Failed to get password record - %u", geteuid());
4601 return strdup(pwent
.pw_name
);
4604 /* not thread-safe, do not use from api without first forking */
4605 static char *getgname(void)
4607 __do_free
char *buf
= NULL
;
4609 struct group
*grentp
= NULL
;
4613 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
4617 buf
= malloc(bufsize
);
4621 ret
= getgrgid_r(getegid(), &grent
, buf
, bufsize
, &grentp
);
4624 WARN("Could not find matched group record");
4626 ERROR("Failed to get group record - %u", getegid());
4630 return strdup(grent
.gr_name
);
4633 /* not thread-safe, do not use from api without first forking */
4634 void suggest_default_idmap(void)
4636 __do_free
char *gname
= NULL
, *line
= NULL
, *uname
= NULL
;
4637 __do_fclose
FILE *subuid_f
= NULL
, *subgid_f
= NULL
;
4638 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
4649 subuid_f
= fopen(subuidfile
, "r");
4651 ERROR("Your system is not configured with subuids");
4655 while (getline(&line
, &len
, subuid_f
) != -1) {
4657 size_t no_newline
= 0;
4659 p
= strchr(line
, ':');
4667 if (strcmp(line
, uname
))
4670 p2
= strchr(p
, ':');
4677 no_newline
= strcspn(p2
, "\n");
4678 p2
[no_newline
] = '\0';
4680 if (lxc_safe_uint(p
, &uid
) < 0)
4681 WARN("Could not parse UID");
4682 if (lxc_safe_uint(p2
, &urange
) < 0)
4683 WARN("Could not parse UID range");
4686 subgid_f
= fopen(subgidfile
, "r");
4688 ERROR("Your system is not configured with subgids");
4692 while (getline(&line
, &len
, subgid_f
) != -1) {
4694 size_t no_newline
= 0;
4696 p
= strchr(line
, ':');
4704 if (strcmp(line
, uname
))
4707 p2
= strchr(p
, ':');
4714 no_newline
= strcspn(p2
, "\n");
4715 p2
[no_newline
] = '\0';
4717 if (lxc_safe_uint(p
, &gid
) < 0)
4718 WARN("Could not parse GID");
4719 if (lxc_safe_uint(p2
, &grange
) < 0)
4720 WARN("Could not parse GID range");
4723 if (!urange
|| !grange
) {
4724 ERROR("You do not have subuids or subgids allocated");
4725 ERROR("Unprivileged containers require subuids and subgids");
4729 ERROR("You must either run as root, or define uid mappings");
4730 ERROR("To pass uid mappings to lxc-create, you could create");
4731 ERROR("~/.config/lxc/default.conf:");
4732 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
4733 ERROR("lxc.idmap = u 0 %u %u", uid
, urange
);
4734 ERROR("lxc.idmap = g 0 %u %u", gid
, grange
);
4737 static void free_cgroup_settings(struct lxc_list
*result
)
4739 struct lxc_list
*iterator
, *next
;
4741 lxc_list_for_each_safe (iterator
, result
, next
) {
4742 lxc_list_del(iterator
);
4748 /* Return the list of cgroup_settings sorted according to the following rules
4749 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4751 struct lxc_list
*sort_cgroup_settings(struct lxc_list
*cgroup_settings
)
4753 struct lxc_list
*result
;
4754 struct lxc_cgroup
*cg
= NULL
;
4755 struct lxc_list
*it
= NULL
, *item
= NULL
, *memsw_limit
= NULL
;
4757 result
= malloc(sizeof(*result
));
4760 lxc_list_init(result
);
4762 /* Iterate over the cgroup settings and copy them to the output list. */
4763 lxc_list_for_each (it
, cgroup_settings
) {
4764 item
= malloc(sizeof(*item
));
4766 free_cgroup_settings(result
);
4770 item
->elem
= it
->elem
;
4772 if (strcmp(cg
->subsystem
, "memory.memsw.limit_in_bytes") == 0) {
4773 /* Store the memsw_limit location */
4775 } else if (strcmp(cg
->subsystem
, "memory.limit_in_bytes") == 0 &&
4776 memsw_limit
!= NULL
) {
4777 /* lxc.cgroup.memory.memsw.limit_in_bytes is found
4778 * before lxc.cgroup.memory.limit_in_bytes, swap these
4780 item
->elem
= memsw_limit
->elem
;
4781 memsw_limit
->elem
= it
->elem
;
4783 lxc_list_add_tail(result
, item
);