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"
85 #include <sys/mkdev.h>
89 #include <sys/statvfs.h>
95 #include <../include/openpty.h>
99 #include <sys/capability.h>
102 #if HAVE_SYS_PERSONALITY_H
103 #include <sys/personality.h>
107 #include "include/strlcat.h"
111 #include <../include/lxcmntent.h>
116 #if !defined(HAVE_PRLIMIT) && defined(HAVE_PRLIMIT64)
117 #include <../include/prlimit.h>
120 lxc_log_define(conf
, lxc
);
122 /* The lxc_conf of the container currently being worked on in an API call.
123 * This is used in the error calls.
126 thread_local
struct lxc_conf
*current_config
;
128 struct lxc_conf
*current_config
;
131 char *lxchook_names
[NUM_LXC_HOOKS
] = {
160 static struct mount_opt mount_opt
[] = {
161 { "async", 1, MS_SYNCHRONOUS
},
162 { "atime", 1, MS_NOATIME
},
163 { "bind", 0, MS_BIND
},
164 { "defaults", 0, 0 },
165 { "dev", 1, MS_NODEV
},
166 { "diratime", 1, MS_NODIRATIME
},
167 { "dirsync", 0, MS_DIRSYNC
},
168 { "exec", 1, MS_NOEXEC
},
169 { "lazytime", 0, MS_LAZYTIME
},
170 { "mand", 0, MS_MANDLOCK
},
171 { "noatime", 0, MS_NOATIME
},
172 { "nodev", 0, MS_NODEV
},
173 { "nodiratime", 0, MS_NODIRATIME
},
174 { "noexec", 0, MS_NOEXEC
},
175 { "nomand", 1, MS_MANDLOCK
},
176 { "norelatime", 1, MS_RELATIME
},
177 { "nostrictatime", 1, MS_STRICTATIME
},
178 { "nosuid", 0, MS_NOSUID
},
179 { "rbind", 0, MS_BIND
|MS_REC
},
180 { "relatime", 0, MS_RELATIME
},
181 { "remount", 0, MS_REMOUNT
},
182 { "ro", 0, MS_RDONLY
},
183 { "rw", 1, MS_RDONLY
},
184 { "strictatime", 0, MS_STRICTATIME
},
185 { "suid", 1, MS_NOSUID
},
186 { "sync", 0, MS_SYNCHRONOUS
},
190 static struct mount_opt propagation_opt
[] = {
191 { "private", 0, MS_PRIVATE
},
192 { "shared", 0, MS_SHARED
},
193 { "slave", 0, MS_SLAVE
},
194 { "unbindable", 0, MS_UNBINDABLE
},
195 { "rprivate", 0, MS_PRIVATE
|MS_REC
},
196 { "rshared", 0, MS_SHARED
|MS_REC
},
197 { "rslave", 0, MS_SLAVE
|MS_REC
},
198 { "runbindable", 0, MS_UNBINDABLE
|MS_REC
},
202 static struct caps_opt caps_opt
[] = {
204 { "chown", CAP_CHOWN
},
205 { "dac_override", CAP_DAC_OVERRIDE
},
206 { "dac_read_search", CAP_DAC_READ_SEARCH
},
207 { "fowner", CAP_FOWNER
},
208 { "fsetid", CAP_FSETID
},
209 { "kill", CAP_KILL
},
210 { "setgid", CAP_SETGID
},
211 { "setuid", CAP_SETUID
},
212 { "setpcap", CAP_SETPCAP
},
213 { "linux_immutable", CAP_LINUX_IMMUTABLE
},
214 { "net_bind_service", CAP_NET_BIND_SERVICE
},
215 { "net_broadcast", CAP_NET_BROADCAST
},
216 { "net_admin", CAP_NET_ADMIN
},
217 { "net_raw", CAP_NET_RAW
},
218 { "ipc_lock", CAP_IPC_LOCK
},
219 { "ipc_owner", CAP_IPC_OWNER
},
220 { "sys_module", CAP_SYS_MODULE
},
221 { "sys_rawio", CAP_SYS_RAWIO
},
222 { "sys_chroot", CAP_SYS_CHROOT
},
223 { "sys_ptrace", CAP_SYS_PTRACE
},
224 { "sys_pacct", CAP_SYS_PACCT
},
225 { "sys_admin", CAP_SYS_ADMIN
},
226 { "sys_boot", CAP_SYS_BOOT
},
227 { "sys_nice", CAP_SYS_NICE
},
228 { "sys_resource", CAP_SYS_RESOURCE
},
229 { "sys_time", CAP_SYS_TIME
},
230 { "sys_tty_config", CAP_SYS_TTY_CONFIG
},
231 { "mknod", CAP_MKNOD
},
232 { "lease", CAP_LEASE
},
233 #ifdef CAP_AUDIT_READ
234 { "audit_read", CAP_AUDIT_READ
},
236 #ifdef CAP_AUDIT_WRITE
237 { "audit_write", CAP_AUDIT_WRITE
},
239 #ifdef CAP_AUDIT_CONTROL
240 { "audit_control", CAP_AUDIT_CONTROL
},
242 { "setfcap", CAP_SETFCAP
},
243 { "mac_override", CAP_MAC_OVERRIDE
},
244 { "mac_admin", CAP_MAC_ADMIN
},
246 { "syslog", CAP_SYSLOG
},
248 #ifdef CAP_WAKE_ALARM
249 { "wake_alarm", CAP_WAKE_ALARM
},
251 #ifdef CAP_BLOCK_SUSPEND
252 { "block_suspend", CAP_BLOCK_SUSPEND
},
257 static struct limit_opt limit_opt
[] = {
262 { "core", RLIMIT_CORE
},
265 { "cpu", RLIMIT_CPU
},
268 { "data", RLIMIT_DATA
},
271 { "fsize", RLIMIT_FSIZE
},
274 { "locks", RLIMIT_LOCKS
},
276 #ifdef RLIMIT_MEMLOCK
277 { "memlock", RLIMIT_MEMLOCK
},
279 #ifdef RLIMIT_MSGQUEUE
280 { "msgqueue", RLIMIT_MSGQUEUE
},
283 { "nice", RLIMIT_NICE
},
286 { "nofile", RLIMIT_NOFILE
},
289 { "nproc", RLIMIT_NPROC
},
292 { "rss", RLIMIT_RSS
},
295 { "rtprio", RLIMIT_RTPRIO
},
298 { "rttime", RLIMIT_RTTIME
},
300 #ifdef RLIMIT_SIGPENDING
301 { "sigpending", RLIMIT_SIGPENDING
},
304 { "stack", RLIMIT_STACK
},
308 static int run_buffer(char *buffer
)
310 __do_free
char *output
= NULL
;
312 struct lxc_popen_FILE
*f
;
314 f
= lxc_popen(buffer
);
316 SYSERROR("Failed to popen() %s", buffer
);
320 output
= malloc(LXC_LOG_BUFFER_SIZE
);
322 ERROR("Failed to allocate memory for %s", buffer
);
329 SYSERROR("Failed to retrieve underlying file descriptor");
334 for (int i
= 0; i
< 10; i
++) {
337 bytes_read
= lxc_read_nointr(fd
, output
, LXC_LOG_BUFFER_SIZE
- 1);
338 if (bytes_read
> 0) {
339 output
[bytes_read
] = '\0';
340 DEBUG("Script %s produced output: %s", buffer
, output
);
349 SYSERROR("Script exited with error");
351 } else if (WIFEXITED(ret
) && WEXITSTATUS(ret
) != 0) {
352 ERROR("Script exited with status %d", WEXITSTATUS(ret
));
354 } else if (WIFSIGNALED(ret
)) {
355 ERROR("Script terminated by signal %d", WTERMSIG(ret
));
362 int run_script_argv(const char *name
, unsigned int hook_version
,
363 const char *section
, const char *script
,
364 const char *hookname
, char **argv
)
366 __do_free
char *buffer
= NULL
;
370 if (hook_version
== 0)
371 INFO("Executing script \"%s\" for container \"%s\", config "
372 "section \"%s\"", script
, name
, section
);
374 INFO("Executing script \"%s\" for container \"%s\"", script
, name
);
376 for (i
= 0; argv
&& argv
[i
]; i
++)
377 size
+= strlen(argv
[i
]) + 1;
379 size
+= STRLITERALLEN("exec");
381 size
+= strlen(script
);
387 if (hook_version
== 0) {
388 size
+= strlen(hookname
);
391 size
+= strlen(name
);
394 size
+= strlen(section
);
401 buffer
= malloc(size
);
405 if (hook_version
== 0)
406 buf_pos
= snprintf(buffer
, size
, "exec %s %s %s %s", script
, name
, section
, hookname
);
408 buf_pos
= snprintf(buffer
, size
, "exec %s", script
);
409 if (buf_pos
< 0 || (size_t)buf_pos
>= size
) {
410 ERROR("Failed to create command line for script \"%s\"", script
);
414 if (hook_version
== 1) {
415 ret
= setenv("LXC_HOOK_TYPE", hookname
, 1);
417 SYSERROR("Failed to set environment variable: "
418 "LXC_HOOK_TYPE=%s", hookname
);
421 TRACE("Set environment variable: LXC_HOOK_TYPE=%s", hookname
);
423 ret
= setenv("LXC_HOOK_SECTION", section
, 1);
425 SYSERROR("Failed to set environment variable: "
426 "LXC_HOOK_SECTION=%s", section
);
429 TRACE("Set environment variable: LXC_HOOK_SECTION=%s", section
);
431 if (strcmp(section
, "net") == 0) {
434 if (!argv
|| !argv
[0])
437 ret
= setenv("LXC_NET_TYPE", argv
[0], 1);
439 SYSERROR("Failed to set environment variable: "
440 "LXC_NET_TYPE=%s", argv
[0]);
443 TRACE("Set environment variable: LXC_NET_TYPE=%s", argv
[0]);
445 parent
= argv
[1] ? argv
[1] : "";
447 if (strcmp(argv
[0], "macvlan") == 0) {
448 ret
= setenv("LXC_NET_PARENT", parent
, 1);
450 SYSERROR("Failed to set environment "
451 "variable: LXC_NET_PARENT=%s", parent
);
454 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
455 } else if (strcmp(argv
[0], "phys") == 0) {
456 ret
= setenv("LXC_NET_PARENT", parent
, 1);
458 SYSERROR("Failed to set environment "
459 "variable: LXC_NET_PARENT=%s", parent
);
462 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
463 } else if (strcmp(argv
[0], "veth") == 0) {
464 char *peer
= argv
[2] ? argv
[2] : "";
466 ret
= setenv("LXC_NET_PEER", peer
, 1);
468 SYSERROR("Failed to set environment "
469 "variable: LXC_NET_PEER=%s", peer
);
472 TRACE("Set environment variable: LXC_NET_PEER=%s", peer
);
474 ret
= setenv("LXC_NET_PARENT", parent
, 1);
476 SYSERROR("Failed to set environment "
477 "variable: LXC_NET_PARENT=%s", parent
);
480 TRACE("Set environment variable: LXC_NET_PARENT=%s", parent
);
485 for (i
= 0; argv
&& argv
[i
]; i
++) {
486 size_t len
= size
- buf_pos
;
488 ret
= snprintf(buffer
+ buf_pos
, len
, " %s", argv
[i
]);
489 if (ret
< 0 || (size_t)ret
>= len
) {
490 ERROR("Failed to create command line for script \"%s\"", script
);
496 return run_buffer(buffer
);
499 int run_script(const char *name
, const char *section
, const char *script
, ...)
501 __do_free
char *buffer
= NULL
;
507 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\"",
508 script
, name
, section
);
510 va_start(ap
, script
);
511 while ((p
= va_arg(ap
, char *)))
512 size
+= strlen(p
) + 1;
515 size
+= STRLITERALLEN("exec");
516 size
+= strlen(script
);
517 size
+= strlen(name
);
518 size
+= strlen(section
);
524 buffer
= must_realloc(NULL
, size
);
525 ret
= snprintf(buffer
, size
, "exec %s %s %s", script
, name
, section
);
526 if (ret
< 0 || ret
>= size
)
529 va_start(ap
, script
);
530 while ((p
= va_arg(ap
, char *))) {
531 int len
= size
- ret
;
533 rc
= snprintf(buffer
+ ret
, len
, " %s", p
);
534 if (rc
< 0 || rc
>= len
) {
542 return run_buffer(buffer
);
546 * if rootfs is a directory, then open ${rootfs}/.lxc-keep for writing for
547 * the duration of the container run, to prevent the container from marking
548 * the underlying fs readonly on shutdown. unlink the file immediately so
549 * no name pollution is happens.
550 * don't unlink on NFS to avoid random named stale handles.
551 * return -1 on error.
552 * return -2 if nothing needed to be pinned.
553 * return an open fd (>=0) if we pinned it.
555 int pin_rootfs(const char *rootfs
)
557 __do_free
char *absrootfs
= NULL
;
559 char absrootfspin
[PATH_MAX
];
563 if (rootfs
== NULL
|| strlen(rootfs
) == 0)
566 absrootfs
= realpath(rootfs
, NULL
);
570 ret
= stat(absrootfs
, &s
);
574 if (!S_ISDIR(s
.st_mode
))
577 ret
= snprintf(absrootfspin
, PATH_MAX
, "%s/.lxc-keep", absrootfs
);
578 if (ret
< 0 || ret
>= PATH_MAX
)
581 fd
= open(absrootfspin
, O_CREAT
| O_RDWR
, S_IWUSR
| S_IRUSR
);
585 ret
= fstatfs (fd
, &sfs
);
589 if (sfs
.f_type
== NFS_SUPER_MAGIC
) {
590 DEBUG("Rootfs on NFS, not unlinking pin file \"%s\"", absrootfspin
);
594 (void)unlink(absrootfspin
);
599 /* If we are asking to remount something, make sure that any NOEXEC etc are
602 unsigned long add_required_remount_flags(const char *s
, const char *d
,
608 unsigned long required_flags
= 0;
616 ret
= statvfs(s
, &sb
);
620 if (flags
& MS_REMOUNT
) {
621 if (sb
.f_flag
& MS_NOSUID
)
622 required_flags
|= MS_NOSUID
;
623 if (sb
.f_flag
& MS_NODEV
)
624 required_flags
|= MS_NODEV
;
625 if (sb
.f_flag
& MS_RDONLY
)
626 required_flags
|= MS_RDONLY
;
627 if (sb
.f_flag
& MS_NOEXEC
)
628 required_flags
|= MS_NOEXEC
;
631 if (sb
.f_flag
& MS_NOATIME
)
632 required_flags
|= MS_NOATIME
;
633 if (sb
.f_flag
& MS_NODIRATIME
)
634 required_flags
|= MS_NODIRATIME
;
635 if (sb
.f_flag
& MS_LAZYTIME
)
636 required_flags
|= MS_LAZYTIME
;
637 if (sb
.f_flag
& MS_RELATIME
)
638 required_flags
|= MS_RELATIME
;
639 if (sb
.f_flag
& MS_STRICTATIME
)
640 required_flags
|= MS_STRICTATIME
;
642 return flags
| required_flags
;
648 static int add_shmount_to_list(struct lxc_conf
*conf
)
650 char new_mount
[PATH_MAX
];
651 /* Offset for the leading '/' since the path_cont
652 * is absolute inside the container.
654 int offset
= 1, ret
= -1;
656 ret
= snprintf(new_mount
, sizeof(new_mount
),
657 "%s %s none bind,create=dir 0 0", conf
->shmount
.path_host
,
658 conf
->shmount
.path_cont
+ offset
);
659 if (ret
< 0 || (size_t)ret
>= sizeof(new_mount
))
662 return add_elem_to_mount_list(new_mount
, conf
);
665 static int lxc_mount_auto_mounts(struct lxc_conf
*conf
, int flags
, struct lxc_handler
*handler
)
672 const char *destination
;
676 } default_mounts
[] = {
677 /* Read-only bind-mounting... In older kernels, doing that
678 * required to do one MS_BIND mount and then
679 * MS_REMOUNT|MS_RDONLY the same one. According to mount(2)
680 * manpage, MS_BIND honors MS_RDONLY from kernel 2.6.26
681 * onwards. However, this apparently does not work on kernel
682 * 3.8. Unfortunately, on that very same kernel, doing the same
683 * trick as above doesn't seem to work either, there one needs
684 * to ALSO specify MS_BIND for the remount, otherwise the
685 * entire fs is remounted read-only or the mount fails because
686 * it's busy... MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for
687 * kernels as low as 2.6.32...
689 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
690 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
691 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys/net", "%r/proc/tty", NULL
, MS_BIND
, NULL
},
692 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys", "%r/proc/sys", NULL
, MS_BIND
, NULL
},
693 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
694 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/tty", "%r/proc/sys/net", NULL
, MS_MOVE
, NULL
},
695 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL
, MS_BIND
, NULL
},
696 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sysrq-trigger", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
697 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_RW
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
698 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RW
, "sysfs", "%r/sys", "sysfs", 0, NULL
},
699 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RO
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
, NULL
},
700 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys", "sysfs", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
701 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/sys", "%r/sys", NULL
, MS_BIND
, NULL
},
702 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, NULL
, "%r/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
703 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys/devices/virtual/net", "sysfs", 0, NULL
},
704 { 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
},
705 { 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
},
706 { 0, 0, NULL
, NULL
, NULL
, 0, NULL
}
709 for (i
= 0; default_mounts
[i
].match_mask
; i
++) {
710 __do_free
char *destination
= NULL
, *source
= NULL
;
712 unsigned long mflags
;
713 if ((flags
& default_mounts
[i
].match_mask
) != default_mounts
[i
].match_flag
)
716 if (default_mounts
[i
].source
) {
717 /* will act like strdup if %r is not present */
718 source
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].source
);
723 if (!default_mounts
[i
].destination
) {
724 ERROR("BUG: auto mounts destination %d was NULL", i
);
728 /* will act like strdup if %r is not present */
729 destination
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].destination
);
734 mflags
= add_required_remount_flags(source
, destination
,
735 default_mounts
[i
].flags
);
736 r
= safe_mount(source
, destination
, default_mounts
[i
].fstype
,
737 mflags
, default_mounts
[i
].options
,
738 conf
->rootfs
.path
? conf
->rootfs
.mount
: NULL
);
740 if (r
< 0 && errno
== ENOENT
) {
741 INFO("Mount source or target for \"%s\" on \"%s\" does "
742 "not exist. Skipping", source
, destination
);
745 SYSERROR("Failed to mount \"%s\" on \"%s\" with flags %lu", source
, destination
, mflags
);
754 if (flags
& LXC_AUTO_CGROUP_MASK
) {
757 cg_flags
= flags
& (LXC_AUTO_CGROUP_MASK
& ~LXC_AUTO_CGROUP_FORCE
);
758 /* If the type of cgroup mount was not specified, it depends on
759 * the container's capabilities as to what makes sense: if we
760 * have CAP_SYS_ADMIN, the read-only part can be remounted
761 * read-write anyway, so we may as well default to read-write;
762 * then the admin will not be given a false sense of security.
763 * (And if they really want mixed r/o r/w, then they can
764 * explicitly specify :mixed.) OTOH, if the container lacks
765 * CAP_SYS_ADMIN, do only default to :mixed, because then the
766 * container can't remount it read-write.
768 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
|| cg_flags
== LXC_AUTO_CGROUP_FULL_NOSPEC
) {
769 int has_sys_admin
= 0;
771 if (!lxc_list_empty(&conf
->keepcaps
))
772 has_sys_admin
= in_caplist(CAP_SYS_ADMIN
, &conf
->keepcaps
);
774 has_sys_admin
= !in_caplist(CAP_SYS_ADMIN
, &conf
->caps
);
776 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
777 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_RW
: LXC_AUTO_CGROUP_MIXED
;
779 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_FULL_RW
: LXC_AUTO_CGROUP_FULL_MIXED
;
782 if (flags
& LXC_AUTO_CGROUP_FORCE
)
783 cg_flags
|= LXC_AUTO_CGROUP_FORCE
;
785 if (!handler
->cgroup_ops
->mount(handler
->cgroup_ops
,
787 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
789 SYSERROR("Failed to mount \"/sys/fs/cgroup\"");
794 if (flags
& LXC_AUTO_SHMOUNTS_MASK
) {
795 int ret
= add_shmount_to_list(conf
);
797 ERROR("Failed to add shmount entry to container config");
805 static int setup_utsname(struct utsname
*utsname
)
812 ret
= sethostname(utsname
->nodename
, strlen(utsname
->nodename
));
814 SYSERROR("Failed to set the hostname to \"%s\"", utsname
->nodename
);
818 INFO("Set hostname to \"%s\"", utsname
->nodename
);
823 struct dev_symlinks
{
828 static const struct dev_symlinks dev_symlinks
[] = {
829 { "/proc/self/fd", "fd" },
830 { "/proc/self/fd/0", "stdin" },
831 { "/proc/self/fd/1", "stdout" },
832 { "/proc/self/fd/2", "stderr" },
835 static int lxc_setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
841 for (i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
842 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
844 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s",
845 rootfs
->path
? rootfs
->mount
: "", d
->name
);
846 if (ret
< 0 || ret
>= PATH_MAX
)
849 /* Stat the path first. If we don't get an error accept it as
850 * is and don't try to create it
852 ret
= stat(path
, &s
);
856 ret
= symlink(d
->oldpath
, path
);
857 if (ret
&& errno
!= EEXIST
) {
858 if (errno
== EROFS
) {
859 WARN("Failed to create \"%s\". Read-only filesystem", path
);
861 SYSERROR("Failed to create \"%s\"", path
);
870 /* Build a space-separate list of ptys to pass to systemd. */
871 static bool append_ttyname(char **pp
, char *name
)
877 *pp
= malloc(strlen(name
) + strlen("container_ttys=") + 1);
881 sprintf(*pp
, "container_ttys=%s", name
);
885 size
= strlen(*pp
) + strlen(name
) + 2;
886 p
= realloc(*pp
, size
);
891 (void)strlcat(p
, " ", size
);
892 (void)strlcat(p
, name
, size
);
897 static int lxc_setup_ttys(struct lxc_conf
*conf
)
900 const struct lxc_tty_info
*ttys
= &conf
->ttys
;
901 char *ttydir
= ttys
->dir
;
902 char path
[PATH_MAX
], lxcpath
[PATH_MAX
];
904 if (!conf
->rootfs
.path
)
907 for (i
= 0; i
< ttys
->max
; i
++) {
908 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
910 ret
= snprintf(path
, sizeof(path
), "/dev/tty%d", i
+ 1);
911 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
915 /* create dev/lxc/tty%d" */
916 ret
= snprintf(lxcpath
, sizeof(lxcpath
),
917 "/dev/%s/tty%d", ttydir
, i
+ 1);
918 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
921 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
922 if (ret
< 0 && errno
!= EEXIST
) {
923 SYSERROR("Failed to create \"%s\"", lxcpath
);
928 if (ret
< 0 && errno
!= ENOENT
) {
929 SYSERROR("Failed to unlink \"%s\"", path
);
933 ret
= mount(tty
->name
, lxcpath
, "none", MS_BIND
, 0);
935 SYSWARN("Failed to bind mount \"%s\" onto \"%s\"",
939 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
,
942 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/tty%d",
944 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
947 ret
= symlink(lxcpath
, path
);
949 SYSERROR("Failed to create symlink \"%s\" -> \"%s\"",
954 /* If we populated /dev, then we need to create
957 ret
= mknod(path
, S_IFREG
| 0000, 0);
958 if (ret
< 0) /* this isn't fatal, continue */
959 SYSERROR("Failed to create \"%s\"", path
);
961 ret
= mount(tty
->name
, path
, "none", MS_BIND
, 0);
963 SYSERROR("Failed to mount '%s'->'%s'", tty
->name
, path
);
967 DEBUG("Bind mounted \"%s\" onto \"%s\"", tty
->name
, path
);
970 if (!append_ttyname(&conf
->ttys
.tty_names
, tty
->name
)) {
971 ERROR("Error setting up container_ttys string");
976 INFO("Finished setting up %zu /dev/tty<N> device(s)", ttys
->max
);
980 int lxc_allocate_ttys(struct lxc_conf
*conf
)
984 struct lxc_tty_info
*ttys
= &conf
->ttys
;
986 /* no tty in the configuration */
990 ttys
->tty
= malloc(sizeof(*ttys
->tty
) * ttys
->max
);
994 for (i
= 0; i
< ttys
->max
; i
++) {
995 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
997 tty
->master
= -EBADF
;
999 ret
= openpty(&tty
->master
, &tty
->slave
, NULL
, NULL
, NULL
);
1001 SYSERROR("Failed to create tty %zu", i
);
1003 lxc_delete_tty(ttys
);
1007 ret
= ttyname_r(tty
->slave
, tty
->name
, sizeof(tty
->name
));
1009 SYSERROR("Failed to retrieve name of tty %zu slave", i
);
1011 lxc_delete_tty(ttys
);
1015 DEBUG("Created tty \"%s\" with master fd %d and slave fd %d",
1016 tty
->name
, tty
->master
, tty
->slave
);
1018 /* Prevent leaking the file descriptors to the container */
1019 ret
= fd_cloexec(tty
->master
, true);
1021 SYSWARN("Failed to set FD_CLOEXEC flag on master fd %d of "
1022 "tty device \"%s\"", tty
->master
, tty
->name
);
1024 ret
= fd_cloexec(tty
->slave
, true);
1026 SYSWARN("Failed to set FD_CLOEXEC flag on slave fd %d of "
1027 "tty device \"%s\"", tty
->slave
, tty
->name
);
1032 INFO("Finished creating %zu tty devices", ttys
->max
);
1036 void lxc_delete_tty(struct lxc_tty_info
*ttys
)
1043 for (i
= 0; i
< ttys
->max
; i
++) {
1044 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1046 if (tty
->master
>= 0) {
1048 tty
->master
= -EBADF
;
1051 if (tty
->slave
>= 0) {
1053 tty
->slave
= -EBADF
;
1061 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
1065 struct lxc_conf
*conf
= handler
->conf
;
1066 struct lxc_tty_info
*ttys
= &conf
->ttys
;
1067 int sock
= handler
->data_sock
[0];
1072 for (i
= 0; i
< ttys
->max
; i
++) {
1074 struct lxc_terminal_info
*tty
= &ttys
->tty
[i
];
1076 ttyfds
[0] = tty
->master
;
1077 ttyfds
[1] = tty
->slave
;
1079 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, 2, NULL
, 0);
1083 TRACE("Sent tty \"%s\" with master fd %d and slave fd %d to "
1084 "parent", tty
->name
, tty
->master
, tty
->slave
);
1088 SYSERROR("Failed to send %zu ttys to parent", ttys
->max
);
1090 TRACE("Sent %zu ttys to parent", ttys
->max
);
1095 static int lxc_create_ttys(struct lxc_handler
*handler
)
1098 struct lxc_conf
*conf
= handler
->conf
;
1100 ret
= lxc_allocate_ttys(conf
);
1102 ERROR("Failed to allocate ttys");
1106 ret
= lxc_send_ttys_to_parent(handler
);
1108 ERROR("Failed to send ttys to parent");
1112 if (!conf
->is_execute
) {
1113 ret
= lxc_setup_ttys(conf
);
1115 ERROR("Failed to setup ttys");
1120 if (conf
->ttys
.tty_names
) {
1121 ret
= setenv("container_ttys", conf
->ttys
.tty_names
, 1);
1123 SYSERROR("Failed to set \"container_ttys=%s\"", conf
->ttys
.tty_names
);
1129 lxc_delete_tty(&conf
->ttys
);
1134 /* Just create a path for /dev under $lxcpath/$name and in rootfs If we hit an
1135 * error, log it but don't fail yet.
1137 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
,
1138 const char *lxcpath
)
1140 __do_free
char *path
= NULL
;
1145 INFO("Preparing \"/dev\"");
1147 /* $(rootfs->mount) + "/dev/pts" + '\0' */
1148 clen
= (rootfs
->path
? strlen(rootfs
->mount
) : 0) + 9;
1149 path
= must_realloc(NULL
, clen
);
1151 ret
= snprintf(path
, clen
, "%s/dev", rootfs
->path
? rootfs
->mount
: "");
1152 if (ret
< 0 || (size_t)ret
>= clen
)
1155 cur_mask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1156 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1157 if (ret
< 0 && errno
!= EEXIST
) {
1158 SYSERROR("Failed to create \"/dev\" directory");
1163 ret
= safe_mount("none", path
, "tmpfs", 0, "size=500000,mode=755",
1164 rootfs
->path
? rootfs
->mount
: NULL
);
1166 SYSERROR("Failed to mount tmpfs on \"%s\"", path
);
1169 TRACE("Mounted tmpfs on \"%s\"", path
);
1171 ret
= snprintf(path
, clen
, "%s/dev/pts", rootfs
->path
? rootfs
->mount
: "");
1172 if (ret
< 0 || (size_t)ret
>= clen
) {
1177 /* If we are running on a devtmpfs mapping, dev/pts may already exist.
1178 * If not, then create it and exit if that fails...
1180 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1181 if (ret
< 0 && errno
!= EEXIST
) {
1182 SYSERROR("Failed to create directory \"%s\"", path
);
1190 (void)umask(cur_mask
);
1192 INFO("Prepared \"/dev\"");
1196 struct lxc_device_node
{
1203 static const struct lxc_device_node lxc_devices
[] = {
1204 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1205 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1206 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1207 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1208 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1209 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1216 LXC_DEVNODE_PARTIAL
,
1220 static int lxc_fill_autodev(const struct lxc_rootfs
*rootfs
)
1223 char path
[PATH_MAX
];
1225 int use_mknod
= LXC_DEVNODE_MKNOD
;
1227 ret
= snprintf(path
, PATH_MAX
, "%s/dev",
1228 rootfs
->path
? rootfs
->mount
: "");
1229 if (ret
< 0 || ret
>= PATH_MAX
)
1232 /* ignore, just don't try to fill in */
1233 if (!dir_exists(path
))
1236 INFO("Populating \"/dev\"");
1238 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1239 for (i
= 0; i
< sizeof(lxc_devices
) / sizeof(lxc_devices
[0]); i
++) {
1240 char hostpath
[PATH_MAX
];
1241 const struct lxc_device_node
*device
= &lxc_devices
[i
];
1243 ret
= snprintf(path
, PATH_MAX
, "%s/dev/%s",
1244 rootfs
->path
? rootfs
->mount
: "", device
->name
);
1245 if (ret
< 0 || ret
>= PATH_MAX
)
1248 if (use_mknod
>= LXC_DEVNODE_MKNOD
) {
1249 ret
= mknod(path
, device
->mode
, makedev(device
->maj
, device
->min
));
1250 if (ret
== 0 || (ret
< 0 && errno
== EEXIST
)) {
1251 DEBUG("Created device node \"%s\"", path
);
1252 } else if (ret
< 0) {
1253 if (errno
!= EPERM
) {
1254 SYSERROR("Failed to create device node \"%s\"", path
);
1258 use_mknod
= LXC_DEVNODE_BIND
;
1261 /* Device nodes are fully useable. */
1262 if (use_mknod
== LXC_DEVNODE_OPEN
)
1265 if (use_mknod
== LXC_DEVNODE_MKNOD
) {
1267 * - https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=55956b59df336f6738da916dbb520b6e37df9fbd
1268 * - https://lists.linuxfoundation.org/pipermail/containers/2018-June/039176.html
1270 ret
= open(path
, O_RDONLY
| O_CLOEXEC
);
1272 close_prot_errno_disarm(ret
);
1273 /* Device nodes are fully useable. */
1274 use_mknod
= LXC_DEVNODE_OPEN
;
1278 SYSTRACE("Failed to open \"%s\" device", path
);
1279 /* Device nodes are only partially useable. */
1280 use_mknod
= LXC_DEVNODE_PARTIAL
;
1284 if (use_mknod
!= LXC_DEVNODE_PARTIAL
) {
1285 /* If we are dealing with partially functional device
1286 * nodes the prio mknod() call will have created the
1287 * device node so we can use it as a bind-mount target.
1289 ret
= mknod(path
, S_IFREG
| 0000, 0);
1290 if (ret
< 0 && errno
!= EEXIST
) {
1291 SYSERROR("Failed to create file \"%s\"", path
);
1296 /* Fallback to bind-mounting the device from the host. */
1297 ret
= snprintf(hostpath
, PATH_MAX
, "/dev/%s", device
->name
);
1298 if (ret
< 0 || ret
>= PATH_MAX
)
1301 ret
= safe_mount(hostpath
, path
, 0, MS_BIND
, NULL
,
1302 rootfs
->path
? rootfs
->mount
: NULL
);
1304 SYSERROR("Failed to bind mount host device node \"%s\" "
1305 "onto \"%s\"", hostpath
, path
);
1308 DEBUG("Bind mounted host device node \"%s\" onto \"%s\"",
1313 INFO("Populated \"/dev\"");
1317 static int lxc_mount_rootfs(struct lxc_conf
*conf
)
1320 struct lxc_storage
*bdev
;
1321 const struct lxc_rootfs
*rootfs
= &conf
->rootfs
;
1323 if (!rootfs
->path
) {
1324 ret
= mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0);
1326 SYSERROR("Failed to remount \"/\" MS_REC | MS_SLAVE");
1333 ret
= access(rootfs
->mount
, F_OK
);
1335 SYSERROR("Failed to access to \"%s\". Check it is present",
1340 bdev
= storage_init(conf
);
1342 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1343 rootfs
->path
, rootfs
->mount
,
1344 rootfs
->options
? rootfs
->options
: "(null)");
1348 ret
= bdev
->ops
->mount(bdev
);
1351 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\"",
1352 rootfs
->path
, rootfs
->mount
,
1353 rootfs
->options
? rootfs
->options
: "(null)");
1357 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\"",
1358 rootfs
->path
, rootfs
->mount
,
1359 rootfs
->options
? rootfs
->options
: "(null)");
1364 int lxc_chroot(const struct lxc_rootfs
*rootfs
)
1366 __do_free
char *nroot
= NULL
;
1368 char *root
= rootfs
->mount
;
1370 nroot
= realpath(root
, NULL
);
1372 SYSERROR("Failed to resolve \"%s\"", root
);
1380 /* We could use here MS_MOVE, but in userns this mount is locked and
1383 ret
= mount(nroot
, "/", NULL
, MS_REC
| MS_BIND
, NULL
);
1385 SYSERROR("Failed to mount \"%s\" onto \"/\" as MS_REC | MS_BIND", nroot
);
1389 ret
= mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
);
1391 SYSERROR("Failed to remount \"/\"");
1395 /* The following code cleans up inherited mounts which are not required
1398 * The mountinfo file shows not all mounts, if a few points have been
1399 * unmounted between read operations from the mountinfo. So we need to
1400 * read mountinfo a few times.
1402 * This loop can be skipped if a container uses userns, because all
1403 * inherited mounts are locked and we should live with all this trash.
1406 __do_fclose
FILE *f
= NULL
;
1407 __do_free
char *line
= NULL
;
1408 char *slider1
, *slider2
;
1412 f
= fopen("./proc/self/mountinfo", "r");
1414 SYSERROR("Failed to open \"/proc/self/mountinfo\"");
1418 while (getline(&line
, &len
, f
) > 0) {
1419 for (slider1
= line
, i
= 0; slider1
&& i
< 4; i
++)
1420 slider1
= strchr(slider1
+ 1, ' ');
1425 slider2
= strchr(slider1
+ 1, ' ');
1432 if (strcmp(slider1
+ 1, "/") == 0)
1435 if (strcmp(slider1
+ 1, "/proc") == 0)
1438 ret
= umount2(slider1
, MNT_DETACH
);
1447 /* This also can be skipped if a container uses userns. */
1448 (void)umount2("./proc", MNT_DETACH
);
1450 /* It is weird, but chdir("..") moves us in a new root */
1453 SYSERROR("Failed to chdir(\"..\")");
1459 SYSERROR("Failed to chroot(\".\")");
1466 /* (The following explanation is copied verbatim from the kernel.)
1468 * pivot_root Semantics:
1469 * Moves the root file system of the current process to the directory put_old,
1470 * makes new_root as the new root file system of the current process, and sets
1471 * root/cwd of all processes which had them on the current root to new_root.
1474 * The new_root and put_old must be directories, and must not be on the
1475 * same file system as the current process root. The put_old must be
1476 * underneath new_root, i.e. adding a non-zero number of /.. to the string
1477 * pointed to by put_old must yield the same directory as new_root. No other
1478 * file system may be mounted on put_old. After all, new_root is a mountpoint.
1480 * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
1481 * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives
1482 * in this situation.
1485 * - we don't move root/cwd if they are not at the root (reason: if something
1486 * cared enough to change them, it's probably wrong to force them elsewhere)
1487 * - it's okay to pick a root that isn't the root of a file system, e.g.
1488 * /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
1489 * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
1492 static int lxc_pivot_root(const char *rootfs
)
1494 __do_close_prot_errno
int oldroot
= -EBADF
, newroot
= -EBADF
;
1497 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1499 SYSERROR("Failed to open old root directory");
1503 newroot
= open(rootfs
, O_DIRECTORY
| O_RDONLY
| O_CLOEXEC
);
1505 SYSERROR("Failed to open new root directory");
1509 /* change into new root fs */
1510 ret
= fchdir(newroot
);
1512 SYSERROR("Failed to change to new rootfs \"%s\"", rootfs
);
1516 /* pivot_root into our new root fs */
1517 ret
= pivot_root(".", ".");
1519 SYSERROR("Failed to pivot_root()");
1523 /* At this point the old-root is mounted on top of our new-root. To
1524 * unmounted it we must not be chdir'd into it, so escape back to
1527 ret
= fchdir(oldroot
);
1529 SYSERROR("Failed to enter old root directory");
1533 /* Make oldroot rslave to make sure our umounts don't propagate to the
1536 ret
= mount("", ".", "", MS_SLAVE
| MS_REC
, NULL
);
1538 SYSERROR("Failed to make oldroot rslave");
1542 ret
= umount2(".", MNT_DETACH
);
1544 SYSERROR("Failed to detach old root directory");
1548 ret
= fchdir(newroot
);
1550 SYSERROR("Failed to re-enter new root directory");
1554 TRACE("pivot_root(\"%s\") successful", rootfs
);
1559 static int lxc_setup_rootfs_switch_root(const struct lxc_rootfs
*rootfs
)
1561 if (!rootfs
->path
) {
1562 DEBUG("Container does not have a rootfs");
1566 if (detect_ramfs_rootfs())
1567 return lxc_chroot(rootfs
);
1569 return lxc_pivot_root(rootfs
->mount
);
1572 static const struct id_map
*find_mapped_nsid_entry(struct lxc_conf
*conf
,
1576 struct lxc_list
*it
;
1578 struct id_map
*retmap
= NULL
;
1580 /* Shortcut for container's root mappings. */
1582 if (idtype
== ID_TYPE_UID
)
1583 return conf
->root_nsuid_map
;
1585 if (idtype
== ID_TYPE_GID
)
1586 return conf
->root_nsgid_map
;
1589 lxc_list_for_each(it
, &conf
->id_map
) {
1591 if (map
->idtype
!= idtype
)
1594 if (id
>= map
->nsid
&& id
< map
->nsid
+ map
->range
) {
1603 static int lxc_setup_devpts(struct lxc_conf
*conf
)
1607 char devpts_mntopts
[256];
1608 char *mntopt_sets
[5];
1609 char default_devpts_mntopts
[256] = "gid=5,newinstance,ptmxmode=0666,mode=0620";
1611 if (conf
->pty_max
<= 0) {
1612 DEBUG("No new devpts instance will be mounted since no pts "
1613 "devices are requested");
1617 ret
= snprintf(devpts_mntopts
, sizeof(devpts_mntopts
), "%s,max=%zu",
1618 default_devpts_mntopts
, conf
->pty_max
);
1619 if (ret
< 0 || (size_t)ret
>= sizeof(devpts_mntopts
))
1622 (void)umount2("/dev/pts", MNT_DETACH
);
1624 /* Create mountpoint for devpts instance. */
1625 ret
= mkdir("/dev/pts", 0755);
1626 if (ret
< 0 && errno
!= EEXIST
) {
1627 SYSERROR("Failed to create \"/dev/pts\" directory");
1632 mntopt_sets
[0] = devpts_mntopts
;
1634 /* !gid=5 && max= */
1635 mntopt_sets
[1] = devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1637 /* gid=5 && !max= */
1638 mntopt_sets
[2] = default_devpts_mntopts
;
1640 /* !gid=5 && !max= */
1641 mntopt_sets
[3] = default_devpts_mntopts
+ STRLITERALLEN("gid=5") + 1;
1644 mntopt_sets
[4] = NULL
;
1646 for (ret
= -1, opts
= mntopt_sets
; opts
&& *opts
; opts
++) {
1647 /* mount new devpts instance */
1648 ret
= mount("devpts", "/dev/pts", "devpts", MS_NOSUID
| MS_NOEXEC
, *opts
);
1654 SYSERROR("Failed to mount new devpts instance");
1657 DEBUG("Mount new devpts instance with options \"%s\"", *opts
);
1659 /* Remove any pre-existing /dev/ptmx file. */
1660 ret
= remove("/dev/ptmx");
1662 if (errno
!= ENOENT
) {
1663 SYSERROR("Failed to remove existing \"/dev/ptmx\" file");
1667 DEBUG("Removed existing \"/dev/ptmx\" file");
1670 /* Create dummy /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1671 ret
= mknod("/dev/ptmx", S_IFREG
| 0000, 0);
1672 if (ret
< 0 && errno
!= EEXIST
) {
1673 SYSERROR("Failed to create dummy \"/dev/ptmx\" file as bind mount target");
1676 DEBUG("Created dummy \"/dev/ptmx\" file as bind mount target");
1678 /* Fallback option: create symlink /dev/ptmx -> /dev/pts/ptmx */
1679 ret
= mount("/dev/pts/ptmx", "/dev/ptmx", NULL
, MS_BIND
, NULL
);
1681 DEBUG("Bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1684 /* Fallthrough and try to create a symlink. */
1685 ERROR("Failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1688 /* Remove the dummy /dev/ptmx file we created above. */
1689 ret
= remove("/dev/ptmx");
1691 SYSERROR("Failed to remove existing \"/dev/ptmx\"");
1695 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1696 ret
= symlink("/dev/pts/ptmx", "/dev/ptmx");
1698 SYSERROR("Failed to create symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1701 DEBUG("Created symlink from \"/dev/ptmx\" to \"/dev/pts/ptmx\"");
1706 static int setup_personality(int persona
)
1710 #if HAVE_SYS_PERSONALITY_H
1714 ret
= personality(persona
);
1716 SYSERROR("Failed to set personality to \"0x%x\"", persona
);
1720 INFO("Set personality to \"0x%x\"", persona
);
1726 static int lxc_setup_dev_console(const struct lxc_rootfs
*rootfs
,
1727 const struct lxc_terminal
*console
)
1730 char path
[PATH_MAX
];
1731 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1733 if (console
->path
&& !strcmp(console
->path
, "none"))
1736 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1737 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1740 /* When we are asked to setup a console we remove any previous
1741 * /dev/console bind-mounts.
1743 if (file_exists(path
)) {
1744 ret
= lxc_unstack_mountpoint(path
, false);
1746 SYSERROR("Failed to unmount \"%s\"", path
);
1749 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1753 /* For unprivileged containers autodev or automounts will already have
1754 * taken care of creating /dev/console.
1756 ret
= mknod(path
, S_IFREG
| 0000, 0);
1757 if (ret
< 0 && errno
!= EEXIST
) {
1758 SYSERROR("Failed to create console");
1762 ret
= fchmod(console
->slave
, S_IXUSR
| S_IXGRP
);
1764 SYSERROR("Failed to set mode \"0%o\" to \"%s\"",
1765 S_IXUSR
| S_IXGRP
, console
->name
);
1769 ret
= safe_mount(console
->name
, path
, "none", MS_BIND
, 0, rootfs_path
);
1771 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, path
);
1775 DEBUG("Mounted pts device \"%s\" onto \"%s\"", console
->name
, path
);
1779 static int lxc_setup_ttydir_console(const struct lxc_rootfs
*rootfs
,
1780 const struct lxc_terminal
*console
,
1784 char path
[PATH_MAX
], lxcpath
[PATH_MAX
];
1785 char *rootfs_path
= rootfs
->path
? rootfs
->mount
: "";
1787 if (console
->path
&& !strcmp(console
->path
, "none"))
1790 /* create rootfs/dev/<ttydir> directory */
1791 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs_path
, ttydir
);
1792 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1795 ret
= mkdir(path
, 0755);
1796 if (ret
&& errno
!= EEXIST
) {
1797 SYSERROR("Failed to create \"%s\"", path
);
1800 DEBUG("Created directory for console and tty devices at \"%s\"", path
);
1802 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/dev/%s/console", rootfs_path
, ttydir
);
1803 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1806 ret
= mknod(lxcpath
, S_IFREG
| 0000, 0);
1807 if (ret
< 0 && errno
!= EEXIST
) {
1808 SYSERROR("Failed to create \"%s\"", lxcpath
);
1812 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs_path
);
1813 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1816 if (file_exists(path
)) {
1817 ret
= lxc_unstack_mountpoint(path
, false);
1819 SYSERROR("Failed to unmount \"%s\"", path
);
1822 DEBUG("Cleared all (%d) mounts from \"%s\"", ret
, path
);
1826 ret
= mknod(path
, S_IFREG
| 0000, 0);
1827 if (ret
< 0 && errno
!= EEXIST
) {
1828 SYSERROR("Failed to create console");
1832 ret
= fchmod(console
->slave
, S_IXUSR
| S_IXGRP
);
1834 SYSERROR("Failed to set mode \"0%o\" to \"%s\"",
1835 S_IXUSR
| S_IXGRP
, console
->name
);
1839 /* bind mount console->name to '/dev/<ttydir>/console' */
1840 ret
= safe_mount(console
->name
, lxcpath
, "none", MS_BIND
, 0, rootfs_path
);
1842 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1845 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1847 /* bind mount '/dev/<ttydir>/console' to '/dev/console' */
1848 ret
= safe_mount(lxcpath
, path
, "none", MS_BIND
, 0, rootfs_path
);
1850 ERROR("Failed to mount \"%s\" on \"%s\"", console
->name
, lxcpath
);
1853 DEBUG("Mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1855 DEBUG("Console has been setup under \"%s\" and mounted to \"%s\"", lxcpath
, path
);
1859 static int lxc_setup_console(const struct lxc_rootfs
*rootfs
,
1860 const struct lxc_terminal
*console
, char *ttydir
)
1864 return lxc_setup_dev_console(rootfs
, console
);
1866 return lxc_setup_ttydir_console(rootfs
, console
, ttydir
);
1869 static void parse_mntopt(char *opt
, unsigned long *flags
, char **data
, size_t size
)
1871 struct mount_opt
*mo
;
1873 /* If opt is found in mount_opt, set or clear flags.
1874 * Otherwise append it to data. */
1876 for (mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
1877 if (strncmp(opt
, mo
->name
, strlen(mo
->name
)) == 0) {
1879 *flags
&= ~mo
->flag
;
1887 (void)strlcat(*data
, ",", size
);
1889 (void)strlcat(*data
, opt
, size
);
1892 int parse_mntopts(const char *mntopts
, unsigned long *mntflags
, char **mntdata
)
1894 __do_free
char *data
= NULL
, *s
= NULL
;
1904 s
= strdup(mntopts
);
1908 size
= strlen(s
) + 1;
1909 data
= malloc(size
);
1914 lxc_iterate_parts(p
, s
, ",")
1915 parse_mntopt(p
, mntflags
, &data
, size
);
1918 *mntdata
= move_ptr(data
);
1923 static void parse_propagationopt(char *opt
, unsigned long *flags
)
1925 struct mount_opt
*mo
;
1927 /* If opt is found in propagation_opt, set or clear flags. */
1928 for (mo
= &propagation_opt
[0]; mo
->name
!= NULL
; mo
++) {
1929 if (strncmp(opt
, mo
->name
, strlen(mo
->name
)) != 0)
1933 *flags
&= ~mo
->flag
;
1941 int parse_propagationopts(const char *mntopts
, unsigned long *pflags
)
1943 __do_free
char *s
= NULL
;
1949 s
= strdup(mntopts
);
1951 SYSERROR("Failed to allocate memory");
1956 lxc_iterate_parts(p
, s
, ",")
1957 parse_propagationopt(p
, pflags
);
1962 static void null_endofword(char *word
)
1964 while (*word
&& *word
!= ' ' && *word
!= '\t')
1969 /* skip @nfields spaces in @src */
1970 static char *get_field(char *src
, int nfields
)
1975 for (i
= 0; i
< nfields
; i
++) {
1976 while (*p
&& *p
!= ' ' && *p
!= '\t')
1988 static int mount_entry(const char *fsname
, const char *target
,
1989 const char *fstype
, unsigned long mountflags
,
1990 unsigned long pflags
, const char *data
, bool optional
,
1991 bool dev
, bool relative
, const char *rootfs
)
1994 char srcbuf
[PATH_MAX
];
1995 const char *srcpath
= fsname
;
2001 ret
= snprintf(srcbuf
, PATH_MAX
, "%s/%s", rootfs
? rootfs
: "/", fsname
? fsname
: "");
2002 if (ret
< 0 || ret
>= PATH_MAX
) {
2003 ERROR("source path is too long");
2009 ret
= safe_mount(srcpath
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
,
2013 SYSINFO("Failed to mount \"%s\" on \"%s\" (optional)",
2014 srcpath
? srcpath
: "(null)", target
);
2018 SYSERROR("Failed to mount \"%s\" on \"%s\"",
2019 srcpath
? srcpath
: "(null)", target
);
2023 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
2024 unsigned long rqd_flags
= 0;
2026 DEBUG("Remounting \"%s\" on \"%s\" to respect bind or remount "
2027 "options", srcpath
? srcpath
: "(none)", target
? target
: "(none)");
2029 if (mountflags
& MS_RDONLY
)
2030 rqd_flags
|= MS_RDONLY
;
2032 if (srcpath
&& statvfs(srcpath
, &sb
) == 0) {
2033 unsigned long required_flags
= rqd_flags
;
2035 if (sb
.f_flag
& MS_NOSUID
)
2036 required_flags
|= MS_NOSUID
;
2038 if (sb
.f_flag
& MS_NODEV
&& !dev
)
2039 required_flags
|= MS_NODEV
;
2041 if (sb
.f_flag
& MS_RDONLY
)
2042 required_flags
|= MS_RDONLY
;
2044 if (sb
.f_flag
& MS_NOEXEC
)
2045 required_flags
|= MS_NOEXEC
;
2047 DEBUG("Flags for \"%s\" were %lu, required extra flags "
2048 "are %lu", srcpath
, sb
.f_flag
, required_flags
);
2050 /* If this was a bind mount request, and required_flags
2051 * does not have any flags which are not already in
2052 * mountflags, then skip the remount.
2054 if (!(mountflags
& MS_REMOUNT
)) {
2055 if (!(required_flags
& ~mountflags
) &&
2057 DEBUG("Mountflags already were %lu, "
2058 "skipping remount", mountflags
);
2063 mountflags
|= required_flags
;
2067 ret
= mount(srcpath
, target
, fstype
, mountflags
| MS_REMOUNT
, data
);
2070 SYSINFO("Failed to mount \"%s\" on \"%s\" (optional)",
2071 srcpath
? srcpath
: "(null)", target
);
2075 SYSERROR("Failed to mount \"%s\" on \"%s\"",
2076 srcpath
? srcpath
: "(null)", target
);
2085 ret
= mount(NULL
, target
, NULL
, pflags
, NULL
);
2088 SYSINFO("Failed to change mount propagation "
2089 "for \"%s\" (optional)", target
);
2092 SYSERROR("Failed to change mount propagation "
2093 "for \"%s\" (optional)", target
);
2097 DEBUG("Changed mount propagation for \"%s\"", target
);
2100 DEBUG("Mounted \"%s\" on \"%s\" with filesystem type \"%s\"",
2101 srcpath
? srcpath
: "(null)", target
, fstype
);
2106 /* Remove "optional", "create=dir", and "create=file" from mntopt */
2107 static void cull_mntent_opt(struct mntent
*mntent
)
2118 for (i
= 0; list
[i
]; i
++) {
2121 p
= strstr(mntent
->mnt_opts
, list
[i
]);
2125 p2
= strchr(p
, ',');
2127 /* no more mntopts, so just chop it here */
2132 memmove(p
, p2
+ 1, strlen(p2
+ 1) + 1);
2136 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
2138 const struct lxc_rootfs
*rootfs
,
2139 const char *lxc_name
, const char *lxc_path
)
2141 __do_free
char *p1
= NULL
;
2145 if (strncmp(mntent
->mnt_type
, "overlay", 7) == 0) {
2146 ret
= ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
);
2151 if (hasmntopt(mntent
, "create=dir")) {
2152 ret
= mkdir_p(path
, 0755);
2153 if (ret
< 0 && errno
!= EEXIST
) {
2154 SYSERROR("Failed to create directory \"%s\"", path
);
2159 if (!hasmntopt(mntent
, "create=file"))
2162 ret
= access(path
, F_OK
);
2172 ret
= mkdir_p(p2
, 0755);
2173 if (ret
< 0 && errno
!= EEXIST
) {
2174 SYSERROR("Failed to create directory \"%s\"", path
);
2178 ret
= mknod(path
, S_IFREG
| 0000, 0);
2179 if (ret
< 0 && errno
!= EEXIST
)
2185 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
2186 * without a rootfs. */
2187 static inline int mount_entry_on_generic(struct mntent
*mntent
,
2189 const struct lxc_rootfs
*rootfs
,
2190 const char *lxc_name
,
2191 const char *lxc_path
)
2193 __do_free
char *mntdata
= NULL
;
2195 unsigned long mntflags
;
2196 bool dev
, optional
, relative
;
2197 unsigned long pflags
= 0;
2198 char *rootfs_path
= NULL
;
2200 optional
= hasmntopt(mntent
, "optional") != NULL
;
2201 dev
= hasmntopt(mntent
, "dev") != NULL
;
2202 relative
= hasmntopt(mntent
, "relative") != NULL
;
2204 if (rootfs
&& rootfs
->path
)
2205 rootfs_path
= rootfs
->mount
;
2207 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
,
2215 cull_mntent_opt(mntent
);
2217 ret
= parse_propagationopts(mntent
->mnt_opts
, &pflags
);
2221 ret
= parse_mntopts(mntent
->mnt_opts
, &mntflags
, &mntdata
);
2225 ret
= mount_entry(mntent
->mnt_fsname
, path
, mntent
->mnt_type
, mntflags
,
2226 pflags
, mntdata
, optional
, dev
, relative
, rootfs_path
);
2231 static inline int mount_entry_on_systemfs(struct mntent
*mntent
)
2234 char path
[PATH_MAX
];
2236 /* For containers created without a rootfs all mounts are treated as
2237 * absolute paths starting at / on the host.
2239 if (mntent
->mnt_dir
[0] != '/')
2240 ret
= snprintf(path
, sizeof(path
), "/%s", mntent
->mnt_dir
);
2242 ret
= snprintf(path
, sizeof(path
), "%s", mntent
->mnt_dir
);
2243 if (ret
< 0 || ret
>= sizeof(path
))
2246 return mount_entry_on_generic(mntent
, path
, NULL
, NULL
, NULL
);
2249 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
2250 const struct lxc_rootfs
*rootfs
,
2251 const char *lxc_name
,
2252 const char *lxc_path
)
2256 const char *lxcpath
;
2257 char path
[PATH_MAX
];
2260 lxcpath
= lxc_global_config_value("lxc.lxcpath");
2264 /* If rootfs->path is a blockdev path, allow container fstab to use
2265 * <lxcpath>/<name>/rootfs" as the target prefix.
2267 ret
= snprintf(path
, PATH_MAX
, "%s/%s/rootfs", lxcpath
, lxc_name
);
2268 if (ret
< 0 || ret
>= PATH_MAX
)
2271 aux
= strstr(mntent
->mnt_dir
, path
);
2273 offset
= strlen(path
);
2278 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
2280 WARN("Ignoring mount point \"%s\"", mntent
->mnt_dir
);
2283 offset
= strlen(rootfs
->path
);
2286 ret
= snprintf(path
, PATH_MAX
, "%s/%s", rootfs
->mount
, aux
+ offset
);
2287 if (ret
< 0 || ret
>= PATH_MAX
)
2290 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2293 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
2294 const struct lxc_rootfs
*rootfs
,
2295 const char *lxc_name
,
2296 const char *lxc_path
)
2299 char path
[PATH_MAX
];
2301 /* relative to root mount point */
2302 ret
= snprintf(path
, sizeof(path
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2303 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
2306 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2309 static int mount_file_entries(const struct lxc_conf
*conf
,
2310 const struct lxc_rootfs
*rootfs
, FILE *file
,
2311 const char *lxc_name
, const char *lxc_path
)
2314 struct mntent mntent
;
2316 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2320 ret
= mount_entry_on_systemfs(&mntent
);
2321 else if (mntent
.mnt_dir
[0] != '/')
2322 ret
= mount_entry_on_relative_rootfs(&mntent
, rootfs
,
2323 lxc_name
, lxc_path
);
2325 ret
= mount_entry_on_absolute_rootfs(&mntent
, rootfs
,
2326 lxc_name
, lxc_path
);
2331 if (!feof(file
) || ferror(file
)) {
2332 ERROR("Failed to parse mount entries");
2339 static int setup_mount(const struct lxc_conf
*conf
,
2340 const struct lxc_rootfs
*rootfs
, const char *fstab
,
2341 const char *lxc_name
, const char *lxc_path
)
2349 f
= setmntent(fstab
, "r");
2351 SYSERROR("Failed to open \"%s\"", fstab
);
2355 ret
= mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2357 ERROR("Failed to set up mount entries");
2364 * In order for nested containers to be able to mount /proc and /sys they need
2365 * to see a "pure" proc and sysfs mount points with nothing mounted on top
2367 * For this we provide proc and sysfs in /dev/.lxc/{proc,sys} while using an
2368 * apparmor rule to deny access to them. This is mostly for convenience: The
2369 * container's root user can mount them anyway and thus has access to the two
2370 * file systems. But a non-root user in the container should not be allowed to
2371 * access them as a side effect without explicitly allowing it.
2373 static const char nesting_helpers
[] =
2374 "proc dev/.lxc/proc proc create=dir,optional 0 0\n"
2375 "sys dev/.lxc/sys sysfs create=dir,optional 0 0\n";
2377 FILE *make_anonymous_mount_file(struct lxc_list
*mount
,
2378 bool include_nesting_helpers
)
2380 __do_close_prot_errno
int fd
= -EBADF
;
2383 struct lxc_list
*iterator
;
2385 fd
= memfd_create(".lxc_mount_file", MFD_CLOEXEC
);
2387 char template[] = P_tmpdir
"/.lxc_mount_file_XXXXXX";
2389 if (errno
!= ENOSYS
)
2392 fd
= lxc_make_tmpfile(template, true);
2394 SYSERROR("Could not create temporary mount file");
2398 TRACE("Created temporary mount file");
2401 lxc_list_for_each (iterator
, mount
) {
2404 mount_entry
= iterator
->elem
;
2405 len
= strlen(mount_entry
);
2407 ret
= lxc_write_nointr(fd
, mount_entry
, len
);
2411 ret
= lxc_write_nointr(fd
, "\n", 1);
2416 if (include_nesting_helpers
) {
2417 ret
= lxc_write_nointr(fd
, nesting_helpers
,
2418 STRARRAYLEN(nesting_helpers
));
2419 if (ret
!= STRARRAYLEN(nesting_helpers
))
2423 ret
= lseek(fd
, 0, SEEK_SET
);
2427 return fdopen(move_fd(fd
), "r+");
2430 static int setup_mount_entries(const struct lxc_conf
*conf
,
2431 const struct lxc_rootfs
*rootfs
,
2432 struct lxc_list
*mount
, const char *lxc_name
,
2433 const char *lxc_path
)
2435 __do_fclose
FILE *f
= NULL
;
2437 f
= make_anonymous_mount_file(mount
, conf
->lsm_aa_allow_nesting
);
2441 return mount_file_entries(conf
, rootfs
, f
, lxc_name
, lxc_path
);
2444 static int parse_cap(const char *cap
)
2448 size_t end
= sizeof(caps_opt
) / sizeof(caps_opt
[0]);
2451 if (strcmp(cap
, "none") == 0)
2454 for (i
= 0; i
< end
; i
++) {
2455 if (strcmp(cap
, caps_opt
[i
].name
))
2458 capid
= caps_opt
[i
].value
;
2463 /* Try to see if it's numeric, so the user may specify
2464 * capabilities that the running kernel knows about but we
2468 capid
= strtol(cap
, &ptr
, 10);
2469 if (!ptr
|| *ptr
!= '\0' || errno
!= 0)
2470 /* not a valid number */
2472 else if (capid
> lxc_caps_last_cap())
2473 /* we have a number but it's not a valid
2481 int in_caplist(int cap
, struct lxc_list
*caps
)
2484 struct lxc_list
*iterator
;
2486 lxc_list_for_each (iterator
, caps
) {
2487 capid
= parse_cap(iterator
->elem
);
2495 static int setup_caps(struct lxc_list
*caps
)
2499 struct lxc_list
*iterator
;
2501 lxc_list_for_each (iterator
, caps
) {
2504 drop_entry
= iterator
->elem
;
2506 capid
= parse_cap(drop_entry
);
2508 ERROR("unknown capability %s", drop_entry
);
2512 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(capid
), prctl_arg(0),
2513 prctl_arg(0), prctl_arg(0));
2515 SYSERROR("Failed to remove %s capability", drop_entry
);
2518 DEBUG("Dropped %s (%d) capability", drop_entry
, capid
);
2521 DEBUG("Capabilities have been setup");
2525 static int dropcaps_except(struct lxc_list
*caps
)
2527 __do_free
int *caplist
= NULL
;
2528 int i
, capid
, numcaps
;
2530 struct lxc_list
*iterator
;
2532 numcaps
= lxc_caps_last_cap() + 1;
2533 if (numcaps
<= 0 || numcaps
> 200)
2535 TRACE("Found %d capabilities", numcaps
);
2537 /* caplist[i] is 1 if we keep capability i */
2538 caplist
= must_realloc(NULL
, numcaps
* sizeof(int));
2539 memset(caplist
, 0, numcaps
* sizeof(int));
2541 lxc_list_for_each (iterator
, caps
) {
2542 keep_entry
= iterator
->elem
;
2544 capid
= parse_cap(keep_entry
);
2549 ERROR("Unknown capability %s", keep_entry
);
2553 DEBUG("Keep capability %s (%d)", keep_entry
, capid
);
2557 for (i
= 0; i
< numcaps
; i
++) {
2563 ret
= prctl(PR_CAPBSET_DROP
, prctl_arg(i
), prctl_arg(0),
2564 prctl_arg(0), prctl_arg(0));
2566 SYSERROR("Failed to remove capability %d", i
);
2571 DEBUG("Capabilities have been setup");
2575 static int parse_resource(const char *res
)
2581 for (i
= 0; i
< sizeof(limit_opt
) / sizeof(limit_opt
[0]); ++i
)
2582 if (strcmp(res
, limit_opt
[i
].name
) == 0)
2583 return limit_opt
[i
].value
;
2585 /* Try to see if it's numeric, so the user may specify
2586 * resources that the running kernel knows about but
2589 ret
= lxc_safe_int(res
, &resid
);
2596 int setup_resource_limits(struct lxc_list
*limits
, pid_t pid
)
2599 struct lxc_list
*it
;
2600 struct lxc_limit
*lim
;
2602 lxc_list_for_each (it
, limits
) {
2605 resid
= parse_resource(lim
->resource
);
2607 ERROR("Unknown resource %s", lim
->resource
);
2611 #if HAVE_PRLIMIT || HAVE_PRLIMIT64
2612 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0) {
2613 SYSERROR("Failed to set limit %s", lim
->resource
);
2617 TRACE("Setup \"%s\" limit", lim
->resource
);
2619 ERROR("Cannot set limit \"%s\" as prlimit is missing", lim
->resource
);
2627 int setup_sysctl_parameters(struct lxc_list
*sysctls
)
2629 __do_free
char *tmp
= NULL
;
2630 struct lxc_list
*it
;
2631 struct lxc_sysctl
*elem
;
2633 char filename
[PATH_MAX
] = {0};
2635 lxc_list_for_each (it
, sysctls
) {
2637 tmp
= lxc_string_replace(".", "/", elem
->key
);
2639 ERROR("Failed to replace key %s", elem
->key
);
2643 ret
= snprintf(filename
, sizeof(filename
), "/proc/sys/%s", tmp
);
2644 if (ret
< 0 || (size_t)ret
>= sizeof(filename
)) {
2645 ERROR("Error setting up sysctl parameters path");
2649 ret
= lxc_write_to_file(filename
, elem
->value
,
2650 strlen(elem
->value
), false, 0666);
2652 SYSERROR("Failed to setup sysctl parameters %s to %s",
2653 elem
->key
, elem
->value
);
2661 int setup_proc_filesystem(struct lxc_list
*procs
, pid_t pid
)
2663 __do_free
char *tmp
= NULL
;
2664 struct lxc_list
*it
;
2665 struct lxc_proc
*elem
;
2667 char filename
[PATH_MAX
] = {0};
2669 lxc_list_for_each (it
, procs
) {
2671 tmp
= lxc_string_replace(".", "/", elem
->filename
);
2673 ERROR("Failed to replace key %s", elem
->filename
);
2677 ret
= snprintf(filename
, sizeof(filename
), "/proc/%d/%s", pid
, tmp
);
2678 if (ret
< 0 || (size_t)ret
>= sizeof(filename
)) {
2679 ERROR("Error setting up proc filesystem path");
2683 ret
= lxc_write_to_file(filename
, elem
->value
,
2684 strlen(elem
->value
), false, 0666);
2686 SYSERROR("Failed to setup proc filesystem %s to %s",
2687 elem
->filename
, elem
->value
);
2695 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
2697 struct lxc_conf
*lxc_conf_init(void)
2700 struct lxc_conf
*new;
2702 new = malloc(sizeof(*new));
2705 memset(new, 0, sizeof(*new));
2707 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
2708 new->personality
= -1;
2710 new->console
.buffer_size
= 0;
2711 new->console
.log_path
= NULL
;
2712 new->console
.log_fd
= -1;
2713 new->console
.log_size
= 0;
2714 new->console
.path
= NULL
;
2715 new->console
.peer
= -1;
2716 new->console
.proxy
.busy
= -1;
2717 new->console
.proxy
.master
= -1;
2718 new->console
.proxy
.slave
= -1;
2719 new->console
.master
= -1;
2720 new->console
.slave
= -1;
2721 new->console
.name
[0] = '\0';
2722 memset(&new->console
.ringbuf
, 0, sizeof(struct lxc_ringbuf
));
2723 new->maincmd_fd
= -1;
2724 new->monitor_signal_pdeath
= SIGKILL
;
2726 new->rootfs
.mount
= strdup(default_rootfs_mount
);
2727 if (!new->rootfs
.mount
) {
2731 new->rootfs
.managed
= true;
2733 lxc_list_init(&new->cgroup
);
2734 lxc_list_init(&new->cgroup2
);
2735 lxc_list_init(&new->network
);
2736 lxc_list_init(&new->mount_list
);
2737 lxc_list_init(&new->caps
);
2738 lxc_list_init(&new->keepcaps
);
2739 lxc_list_init(&new->id_map
);
2740 new->root_nsuid_map
= NULL
;
2741 new->root_nsgid_map
= NULL
;
2742 lxc_list_init(&new->includes
);
2743 lxc_list_init(&new->aliens
);
2744 lxc_list_init(&new->environment
);
2745 lxc_list_init(&new->limits
);
2746 lxc_list_init(&new->sysctls
);
2747 lxc_list_init(&new->procs
);
2748 new->hooks_version
= 0;
2749 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++)
2750 lxc_list_init(&new->hooks
[i
]);
2751 lxc_list_init(&new->groups
);
2752 lxc_list_init(&new->state_clients
);
2753 new->lsm_aa_profile
= NULL
;
2754 lxc_list_init(&new->lsm_aa_raw
);
2755 new->lsm_se_context
= NULL
;
2756 new->tmp_umount_proc
= false;
2757 new->tmp_umount_proc
= 0;
2758 new->shmount
.path_host
= NULL
;
2759 new->shmount
.path_cont
= NULL
;
2761 /* if running in a new user namespace, init and COMMAND
2762 * default to running as UID/GID 0 when using lxc-execute */
2765 memset(&new->cgroup_meta
, 0, sizeof(struct lxc_cgroup
));
2766 memset(&new->ns_share
, 0, sizeof(char *) * LXC_NS_MAX
);
2767 seccomp_conf_init(new);
2772 int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
2775 __do_close_prot_errno
int fd
= -EBADF
;
2777 char path
[PATH_MAX
];
2779 if (geteuid() != 0 && idtype
== ID_TYPE_GID
) {
2780 __do_close_prot_errno
int setgroups_fd
= -EBADF
;
2782 ret
= snprintf(path
, PATH_MAX
, "/proc/%d/setgroups", pid
);
2783 if (ret
< 0 || ret
>= PATH_MAX
)
2786 setgroups_fd
= open(path
, O_WRONLY
);
2787 if (setgroups_fd
< 0 && errno
!= ENOENT
) {
2788 SYSERROR("Failed to open \"%s\"", path
);
2792 if (setgroups_fd
>= 0) {
2793 ret
= lxc_write_nointr(setgroups_fd
, "deny\n",
2794 STRLITERALLEN("deny\n"));
2795 if (ret
!= STRLITERALLEN("deny\n")) {
2796 SYSERROR("Failed to write \"deny\" to \"/proc/%d/setgroups\"", pid
);
2799 TRACE("Wrote \"deny\" to \"/proc/%d/setgroups\"", pid
);
2803 ret
= snprintf(path
, PATH_MAX
, "/proc/%d/%cid_map", pid
,
2804 idtype
== ID_TYPE_UID
? 'u' : 'g');
2805 if (ret
< 0 || ret
>= PATH_MAX
)
2808 fd
= open(path
, O_WRONLY
);
2810 SYSERROR("Failed to open \"%s\"", path
);
2814 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
2815 if (ret
!= buf_size
) {
2816 SYSERROR("Failed to write %cid mapping to \"%s\"",
2817 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
2824 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
2826 * @return 1 if functional binary was found
2827 * @return 0 if binary exists but is lacking privilege
2828 * @return -ENOENT if binary does not exist
2829 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
2831 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
2833 __do_free
char *path
= NULL
;
2838 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
2842 path
= on_path(binary
, NULL
);
2846 ret
= stat(path
, &st
);
2850 /* Check if the binary is setuid. */
2851 if (st
.st_mode
& S_ISUID
) {
2852 DEBUG("The binary \"%s\" does have the setuid bit set", path
);
2856 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
2857 /* Check if it has the CAP_SETUID capability. */
2858 if ((cap
& CAP_SETUID
) &&
2859 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
2860 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
)) {
2861 DEBUG("The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE "
2862 "and CAP_PERMITTED sets", path
);
2866 /* Check if it has the CAP_SETGID capability. */
2867 if ((cap
& CAP_SETGID
) &&
2868 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
2869 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
)) {
2870 DEBUG("The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE "
2871 "and CAP_PERMITTED sets", path
);
2875 /* If we cannot check for file capabilities we need to give the benefit
2876 * of the doubt. Otherwise we might fail even though all the necessary
2877 * file capabilities are set.
2879 DEBUG("Cannot check for file capabilities as full capability support is "
2880 "missing. Manual intervention needed");
2886 int lxc_map_ids_exec_wrapper(void *args
)
2888 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
2892 int lxc_map_ids(struct lxc_list
*idmap
, pid_t pid
)
2897 char cmd_output
[PATH_MAX
];
2899 struct lxc_list
*iterator
;
2901 /* strlen("new@idmap") = 9
2905 * INTTYPE_TO_STRLEN(uint32_t)
2909 * We add some additional space to make sure that we really have
2910 * LXC_IDMAPLEN bytes available for our the {g,u]id mapping.
2912 int ret
= 0, gidmap
= 0, uidmap
= 0;
2913 char mapbuf
[9 + 1 + INTTYPE_TO_STRLEN(uint32_t) + 1 + LXC_IDMAPLEN
] = {0};
2914 bool had_entry
= false, use_shadow
= false;
2915 int hostuid
, hostgid
;
2917 hostuid
= geteuid();
2918 hostgid
= getegid();
2920 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
2921 * ranges, then insist that root also reserve ranges in subuid. This
2922 * will protected it by preventing another user from being handed the
2925 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
2926 if (uidmap
== -ENOENT
)
2927 WARN("newuidmap binary is missing");
2929 WARN("newuidmap is lacking necessary privileges");
2931 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
2932 if (gidmap
== -ENOENT
)
2933 WARN("newgidmap binary is missing");
2935 WARN("newgidmap is lacking necessary privileges");
2937 if (uidmap
> 0 && gidmap
> 0) {
2938 DEBUG("Functional newuidmap and newgidmap binary found");
2941 /* In case unprivileged users run application containers via
2942 * execute() or a start*() there are valid cases where they may
2943 * only want to map their own {g,u}id. Let's not block them from
2944 * doing so by requiring geteuid() == 0.
2946 DEBUG("No newuidmap and newgidmap binary found. Trying to "
2947 "write directly with euid %d", hostuid
);
2950 /* Check if we really need to use newuidmap and newgidmap.
2951 * If the user is only remapping his own {g,u}id, we don't need it.
2953 if (use_shadow
&& lxc_list_len(idmap
) == 2) {
2955 lxc_list_for_each(iterator
, idmap
) {
2956 map
= iterator
->elem
;
2957 if (map
->idtype
== ID_TYPE_UID
&& map
->range
== 1 &&
2958 map
->nsid
== hostuid
&& map
->hostid
== hostuid
)
2960 if (map
->idtype
== ID_TYPE_GID
&& map
->range
== 1 &&
2961 map
->nsid
== hostgid
&& map
->hostid
== hostgid
)
2968 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
2969 type
++, u_or_g
= 'g') {
2973 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
2975 lxc_list_for_each(iterator
, idmap
) {
2976 map
= iterator
->elem
;
2977 if (map
->idtype
!= type
)
2982 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
2983 fill
= snprintf(pos
, left
, "%s%lu %lu %lu%s",
2984 use_shadow
? " " : "", map
->nsid
,
2985 map
->hostid
, map
->range
,
2986 use_shadow
? "" : "\n");
2987 if (fill
<= 0 || fill
>= left
) {
2988 /* The kernel only takes <= 4k for writes to
2989 * /proc/<pid>/{g,u}id_map
2991 SYSERROR("Too many %cid mappings defined", u_or_g
);
3000 /* Try to catch the output of new{g,u}idmap to make debugging
3004 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3005 lxc_map_ids_exec_wrapper
,
3008 ERROR("new%cidmap failed to write mapping \"%s\": %s",
3009 u_or_g
, cmd_output
, mapbuf
);
3012 TRACE("new%cidmap wrote mapping \"%s\"", u_or_g
, mapbuf
);
3014 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
3016 ERROR("Failed to write mapping: %s", mapbuf
);
3019 TRACE("Wrote mapping \"%s\"", mapbuf
);
3022 memset(mapbuf
, 0, sizeof(mapbuf
));
3028 /* Return the host uid/gid to which the container root is mapped in val.
3029 * Return true if id was found, false otherwise.
3031 bool get_mapped_rootid(struct lxc_conf
*conf
, enum idtype idtype
,
3036 struct lxc_list
*it
;
3038 if (idtype
== ID_TYPE_UID
)
3039 nsid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
3041 nsid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
3043 lxc_list_for_each (it
, &conf
->id_map
) {
3045 if (map
->idtype
!= idtype
)
3047 if (map
->nsid
!= nsid
)
3056 int mapped_hostid(unsigned id
, struct lxc_conf
*conf
, enum idtype idtype
)
3059 struct lxc_list
*it
;
3061 lxc_list_for_each (it
, &conf
->id_map
) {
3063 if (map
->idtype
!= idtype
)
3066 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
3067 return (id
- map
->hostid
) + map
->nsid
;
3073 int find_unmapped_nsid(struct lxc_conf
*conf
, enum idtype idtype
)
3076 struct lxc_list
*it
;
3077 unsigned int freeid
= 0;
3080 lxc_list_for_each (it
, &conf
->id_map
) {
3082 if (map
->idtype
!= idtype
)
3085 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
3086 freeid
= map
->nsid
+ map
->range
;
3094 int chown_mapped_root_exec_wrapper(void *args
)
3096 execvp("lxc-usernsexec", args
);
3100 /* chown_mapped_root: for an unprivileged user with uid/gid X to
3101 * chown a dir to subuid/subgid Y, he needs to run chown as root
3102 * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and
3103 * nsid Y is mapped to hostuid/hostgid X. That way, the container
3104 * root is privileged with respect to hostuid/hostgid X, allowing
3105 * him to do the chown.
3107 int chown_mapped_root(const char *path
, struct lxc_conf
*conf
)
3109 uid_t rootuid
, rootgid
;
3111 int hostuid
, hostgid
, ret
;
3113 char map1
[100], map2
[100], map3
[100], map4
[100], map5
[100];
3115 const char *args1
[] = {"lxc-usernsexec",
3120 "--", "chown", ugid
, path
,
3122 const char *args2
[] = {"lxc-usernsexec",
3128 "--", "chown", ugid
, path
,
3130 char cmd_output
[PATH_MAX
];
3132 hostuid
= geteuid();
3133 hostgid
= getegid();
3135 if (!get_mapped_rootid(conf
, ID_TYPE_UID
, &val
)) {
3136 ERROR("No uid mapping for container root");
3139 rootuid
= (uid_t
)val
;
3141 if (!get_mapped_rootid(conf
, ID_TYPE_GID
, &val
)) {
3142 ERROR("No gid mapping for container root");
3145 rootgid
= (gid_t
)val
;
3148 if (chown(path
, rootuid
, rootgid
) < 0) {
3149 ERROR("Error chowning %s", path
);
3156 if (rootuid
== hostuid
) {
3158 INFO("Container root is our uid; no need to chown");
3162 /* save the current gid of "path" */
3163 if (stat(path
, &sb
) < 0) {
3164 ERROR("Error stat %s", path
);
3168 /* Update the path argument in case this was overlayfs. */
3169 args1
[sizeof(args1
) / sizeof(args1
[0]) - 2] = path
;
3170 args2
[sizeof(args2
) / sizeof(args2
[0]) - 2] = path
;
3173 * A file has to be group-owned by a gid mapped into the
3174 * container, or the container won't be privileged over it.
3176 DEBUG("trying to chown \"%s\" to %d", path
, hostgid
);
3177 if (sb
.st_uid
== hostuid
&&
3178 mapped_hostid(sb
.st_gid
, conf
, ID_TYPE_GID
) < 0 &&
3179 chown(path
, -1, hostgid
) < 0) {
3180 ERROR("Failed chgrping %s", path
);
3184 /* "u:0:rootuid:1" */
3185 ret
= snprintf(map1
, 100, "u:0:%d:1", rootuid
);
3186 if (ret
< 0 || ret
>= 100) {
3187 ERROR("Error uid printing map string");
3191 /* "u:hostuid:hostuid:1" */
3192 ret
= snprintf(map2
, 100, "u:%d:%d:1", hostuid
, hostuid
);
3193 if (ret
< 0 || ret
>= 100) {
3194 ERROR("Error uid printing map string");
3198 /* "g:0:rootgid:1" */
3199 ret
= snprintf(map3
, 100, "g:0:%d:1", rootgid
);
3200 if (ret
< 0 || ret
>= 100) {
3201 ERROR("Error gid printing map string");
3205 /* "g:pathgid:rootgid+pathgid:1" */
3206 ret
= snprintf(map4
, 100, "g:%d:%d:1", (gid_t
)sb
.st_gid
,
3207 rootgid
+ (gid_t
)sb
.st_gid
);
3208 if (ret
< 0 || ret
>= 100) {
3209 ERROR("Error gid printing map string");
3213 /* "g:hostgid:hostgid:1" */
3214 ret
= snprintf(map5
, 100, "g:%d:%d:1", hostgid
, hostgid
);
3215 if (ret
< 0 || ret
>= 100) {
3216 ERROR("Error gid printing map string");
3220 /* "0:pathgid" (chown) */
3221 ret
= snprintf(ugid
, 100, "0:%d", (gid_t
)sb
.st_gid
);
3222 if (ret
< 0 || ret
>= 100) {
3223 ERROR("Error owner printing format string for chown");
3227 if (hostgid
== sb
.st_gid
)
3228 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3229 chown_mapped_root_exec_wrapper
,
3232 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3233 chown_mapped_root_exec_wrapper
,
3236 ERROR("lxc-usernsexec failed: %s", cmd_output
);
3241 /* NOTE: Must not be called from inside the container namespace! */
3242 int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
3246 mounted
= lxc_mount_proc_if_needed(conf
->rootfs
.path
? conf
->rootfs
.mount
: "");
3247 if (mounted
== -1) {
3248 SYSERROR("Failed to mount proc in the container");
3249 /* continue only if there is no rootfs */
3250 if (conf
->rootfs
.path
)
3252 } else if (mounted
== 1) {
3253 conf
->tmp_umount_proc
= true;
3259 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
3261 if (!lxc_conf
->tmp_umount_proc
)
3264 (void)umount2("/proc", MNT_DETACH
);
3265 lxc_conf
->tmp_umount_proc
= false;
3268 /* Walk /proc/mounts and change any shared entries to slave. */
3269 void remount_all_slave(void)
3271 __do_free
char *line
= NULL
;
3272 __do_fclose
FILE *f
= NULL
;
3273 __do_close_prot_errno
int memfd
= -EBADF
, mntinfo_fd
= -EBADF
;
3278 mntinfo_fd
= open("/proc/self/mountinfo", O_RDONLY
| O_CLOEXEC
);
3279 if (mntinfo_fd
< 0) {
3280 SYSERROR("Failed to open \"/proc/self/mountinfo\"");
3284 memfd
= memfd_create(".lxc_mountinfo", MFD_CLOEXEC
);
3286 char template[] = P_tmpdir
"/.lxc_mountinfo_XXXXXX";
3288 if (errno
!= ENOSYS
) {
3289 SYSERROR("Failed to create temporary in-memory file");
3293 memfd
= lxc_make_tmpfile(template, true);
3295 WARN("Failed to create temporary file");
3301 copied
= lxc_sendfile_nointr(memfd
, mntinfo_fd
, NULL
, LXC_SENDFILE_MAX
);
3306 SYSERROR("Failed to copy \"/proc/self/mountinfo\"");
3310 ret
= lseek(memfd
, 0, SEEK_SET
);
3312 SYSERROR("Failed to reset file descriptor offset");
3316 f
= fdopen(memfd
, "r");
3318 SYSERROR("Failed to open copy of \"/proc/self/mountinfo\" to mark all shared. Continuing");
3323 * After a successful fdopen() memfd will be closed when calling
3324 * fclose(f). Calling close(memfd) afterwards is undefined.
3328 while (getline(&line
, &len
, f
) != -1) {
3329 char *opts
, *target
;
3331 target
= get_field(line
, 4);
3335 opts
= get_field(target
, 2);
3339 null_endofword(opts
);
3340 if (!strstr(opts
, "shared"))
3343 null_endofword(target
);
3344 ret
= mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
);
3346 SYSERROR("Failed to make \"%s\" MS_SLAVE", target
);
3347 ERROR("Continuing...");
3350 TRACE("Remounted \"%s\" as MS_SLAVE", target
);
3352 TRACE("Remounted all mount table entries as MS_SLAVE");
3355 static int lxc_execute_bind_init(struct lxc_handler
*handler
)
3359 char path
[PATH_MAX
], destpath
[PATH_MAX
];
3360 struct lxc_conf
*conf
= handler
->conf
;
3362 /* If init exists in the container, don't bind mount a static one */
3363 p
= choose_init(conf
->rootfs
.mount
);
3365 __do_free
char *old
= p
;
3367 p
= strdup(old
+ strlen(conf
->rootfs
.mount
));
3371 INFO("Found existing init at \"%s\"", p
);
3375 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3376 if (ret
< 0 || ret
>= PATH_MAX
)
3379 if (!file_exists(path
)) {
3380 ERROR("The file \"%s\" does not exist on host", path
);
3384 ret
= snprintf(destpath
, PATH_MAX
, "%s" P_tmpdir
"%s", conf
->rootfs
.mount
, "/.lxc-init");
3385 if (ret
< 0 || ret
>= PATH_MAX
)
3388 if (!file_exists(destpath
)) {
3389 ret
= mknod(destpath
, S_IFREG
| 0000, 0);
3390 if (ret
< 0 && errno
!= EEXIST
) {
3391 SYSERROR("Failed to create dummy \"%s\" file as bind mount target", destpath
);
3396 ret
= safe_mount(path
, destpath
, "none", MS_BIND
, NULL
, conf
->rootfs
.mount
);
3398 SYSERROR("Failed to bind mount lxc.init.static into container");
3402 p
= strdup(destpath
+ strlen(conf
->rootfs
.mount
));
3406 INFO("Bind mounted lxc.init.static into container at \"%s\"", path
);
3408 ((struct execute_args
*)handler
->data
)->init_fd
= -1;
3409 ((struct execute_args
*)handler
->data
)->init_path
= p
;
3413 /* This does the work of remounting / if it is shared, calling the container
3414 * pre-mount hooks, and mounting the rootfs.
3416 int lxc_setup_rootfs_prepare_root(struct lxc_conf
*conf
, const char *name
,
3417 const char *lxcpath
)
3421 if (conf
->rootfs_setup
) {
3422 const char *path
= conf
->rootfs
.mount
;
3424 /* The rootfs was set up in another namespace. bind-mount it to
3425 * give us a mount in our own ns so we can pivot_root to it
3427 ret
= mount(path
, path
, "rootfs", MS_BIND
, NULL
);
3429 ERROR("Failed to bind mount container / onto itself");
3433 TRACE("Bind mounted container / onto itself");
3437 remount_all_slave();
3439 ret
= run_lxc_hooks(name
, "pre-mount", conf
, NULL
);
3441 ERROR("Failed to run pre-mount hooks");
3445 ret
= lxc_mount_rootfs(conf
);
3447 ERROR("Failed to setup rootfs for");
3451 conf
->rootfs_setup
= true;
3455 static bool verify_start_hooks(struct lxc_conf
*conf
)
3457 char path
[PATH_MAX
];
3458 struct lxc_list
*it
;
3460 lxc_list_for_each (it
, &conf
->hooks
[LXCHOOK_START
]) {
3462 char *hookname
= it
->elem
;
3464 ret
= snprintf(path
, PATH_MAX
, "%s%s",
3465 conf
->rootfs
.path
? conf
->rootfs
.mount
: "",
3467 if (ret
< 0 || ret
>= PATH_MAX
)
3470 ret
= access(path
, X_OK
);
3472 SYSERROR("Start hook \"%s\" not found in container",
3483 static bool execveat_supported(void)
3485 lxc_raw_execveat(-1, "", NULL
, NULL
, AT_EMPTY_PATH
);
3486 if (errno
== ENOSYS
)
3492 static int lxc_setup_boot_id(void)
3495 const char *boot_id_path
= "/proc/sys/kernel/random/boot_id";
3496 const char *mock_boot_id_path
= "/dev/.lxc-boot-id";
3499 if (access(boot_id_path
, F_OK
))
3502 memset(&n
, 0, sizeof(n
));
3503 if (lxc_id128_randomize(&n
)) {
3504 SYSERROR("Failed to generate random data for uuid");
3508 ret
= lxc_id128_write(mock_boot_id_path
, n
);
3510 SYSERROR("Failed to write uuid to %s", mock_boot_id_path
);
3514 ret
= chmod(mock_boot_id_path
, 0444);
3516 SYSERROR("Failed to chown %s", mock_boot_id_path
);
3517 (void)unlink(mock_boot_id_path
);
3521 ret
= mount(mock_boot_id_path
, boot_id_path
, NULL
, MS_BIND
, NULL
);
3523 SYSERROR("Failed to mount %s to %s", mock_boot_id_path
,
3525 (void)unlink(mock_boot_id_path
);
3529 ret
= mount(NULL
, boot_id_path
, NULL
,
3530 (MS_BIND
| MS_REMOUNT
| MS_RDONLY
| MS_NOSUID
| MS_NOEXEC
|
3534 SYSERROR("Failed to remount %s read-only", boot_id_path
);
3535 (void)unlink(mock_boot_id_path
);
3542 int lxc_setup(struct lxc_handler
*handler
)
3545 const char *lxcpath
= handler
->lxcpath
, *name
= handler
->name
;
3546 struct lxc_conf
*lxc_conf
= handler
->conf
;
3548 ret
= lxc_setup_rootfs_prepare_root(lxc_conf
, name
, lxcpath
);
3550 ERROR("Failed to setup rootfs");
3554 if (handler
->nsfd
[LXC_NS_UTS
] == -1) {
3555 ret
= setup_utsname(lxc_conf
->utsname
);
3557 ERROR("Failed to setup the utsname %s", name
);
3562 ret
= lxc_setup_keyring();
3566 ret
= lxc_setup_network_in_child_namespaces(lxc_conf
, &lxc_conf
->network
);
3568 ERROR("Failed to setup network");
3572 ret
= lxc_network_send_name_and_ifindex_to_parent(handler
);
3574 ERROR("Failed to send network device names and ifindices to parent");
3578 if (lxc_conf
->autodev
> 0) {
3579 ret
= mount_autodev(name
, &lxc_conf
->rootfs
, lxcpath
);
3581 ERROR("Failed to mount \"/dev\"");
3586 /* Do automatic mounts (mainly /proc and /sys), but exclude those that
3587 * need to wait until other stuff has finished.
3589 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
, handler
);
3591 ERROR("Failed to setup first automatic mounts");
3595 ret
= setup_mount(lxc_conf
, &lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
);
3597 ERROR("Failed to setup mounts");
3601 if (!lxc_list_empty(&lxc_conf
->mount_list
)) {
3602 ret
= setup_mount_entries(lxc_conf
, &lxc_conf
->rootfs
,
3603 &lxc_conf
->mount_list
, name
, lxcpath
);
3605 ERROR("Failed to setup mount entries");
3610 if (lxc_conf
->is_execute
) {
3611 if (execveat_supported()) {
3613 char path
[PATH_MAX
];
3615 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3616 if (ret
< 0 || ret
>= PATH_MAX
) {
3617 ERROR("Path to init.lxc.static too long");
3621 fd
= open(path
, O_PATH
| O_CLOEXEC
);
3623 SYSERROR("Unable to open lxc.init.static");
3627 ((struct execute_args
*)handler
->data
)->init_fd
= fd
;
3628 ((struct execute_args
*)handler
->data
)->init_path
= NULL
;
3630 ret
= lxc_execute_bind_init(handler
);
3632 ERROR("Failed to bind-mount the lxc init system");
3638 /* Now mount only cgroups, if wanted. Before, /sys could not have been
3639 * mounted. It is guaranteed to be mounted now either through
3640 * automatically or via fstab entries.
3642 ret
= lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
, handler
);
3644 ERROR("Failed to setup remaining automatic mounts");
3648 ret
= run_lxc_hooks(name
, "mount", lxc_conf
, NULL
);
3650 ERROR("Failed to run mount hooks");
3654 if (lxc_conf
->autodev
> 0) {
3655 ret
= run_lxc_hooks(name
, "autodev", lxc_conf
, NULL
);
3657 ERROR("Failed to run autodev hooks");
3661 ret
= lxc_fill_autodev(&lxc_conf
->rootfs
);
3663 ERROR("Failed to populate \"/dev\"");
3668 /* Make sure any start hooks are in the container */
3669 if (!verify_start_hooks(lxc_conf
)) {
3670 ERROR("Failed to verify start hooks");
3674 ret
= lxc_setup_console(&lxc_conf
->rootfs
, &lxc_conf
->console
,
3675 lxc_conf
->ttys
.dir
);
3677 ERROR("Failed to setup console");
3681 ret
= lxc_setup_dev_symlinks(&lxc_conf
->rootfs
);
3683 ERROR("Failed to setup \"/dev\" symlinks");
3687 ret
= lxc_create_tmp_proc_mount(lxc_conf
);
3689 ERROR("Failed to \"/proc\" LSMs");
3693 ret
= lxc_setup_rootfs_switch_root(&lxc_conf
->rootfs
);
3695 ERROR("Failed to pivot root into rootfs");
3699 /* Setting the boot-id is best-effort for now. */
3700 if (lxc_conf
->autodev
> 0)
3701 (void)lxc_setup_boot_id();
3703 ret
= lxc_setup_devpts(lxc_conf
);
3705 ERROR("Failed to setup new devpts instance");
3709 ret
= lxc_create_ttys(handler
);
3713 ret
= setup_personality(lxc_conf
->personality
);
3715 ERROR("Failed to set personality");
3719 /* Set sysctl value to a path under /proc/sys as determined from the
3720 * key. For e.g. net.ipv4.ip_forward translated to
3721 * /proc/sys/net/ipv4/ip_forward.
3723 if (!lxc_list_empty(&lxc_conf
->sysctls
)) {
3724 ret
= setup_sysctl_parameters(&lxc_conf
->sysctls
);
3726 ERROR("Failed to setup sysctl parameters");
3731 if (!lxc_list_empty(&lxc_conf
->keepcaps
)) {
3732 if (!lxc_list_empty(&lxc_conf
->caps
)) {
3733 ERROR("Container requests lxc.cap.drop and "
3734 "lxc.cap.keep: either use lxc.cap.drop or "
3735 "lxc.cap.keep, not both");
3739 if (dropcaps_except(&lxc_conf
->keepcaps
)) {
3740 ERROR("Failed to keep capabilities");
3743 } else if (setup_caps(&lxc_conf
->caps
)) {
3744 ERROR("Failed to drop capabilities");
3748 NOTICE("The container \"%s\" is set up", name
);
3753 int run_lxc_hooks(const char *name
, char *hookname
, struct lxc_conf
*conf
,
3756 struct lxc_list
*it
;
3759 if (strcmp(hookname
, "pre-start") == 0)
3760 which
= LXCHOOK_PRESTART
;
3761 else if (strcmp(hookname
, "start-host") == 0)
3762 which
= LXCHOOK_START_HOST
;
3763 else if (strcmp(hookname
, "pre-mount") == 0)
3764 which
= LXCHOOK_PREMOUNT
;
3765 else if (strcmp(hookname
, "mount") == 0)
3766 which
= LXCHOOK_MOUNT
;
3767 else if (strcmp(hookname
, "autodev") == 0)
3768 which
= LXCHOOK_AUTODEV
;
3769 else if (strcmp(hookname
, "start") == 0)
3770 which
= LXCHOOK_START
;
3771 else if (strcmp(hookname
, "stop") == 0)
3772 which
= LXCHOOK_STOP
;
3773 else if (strcmp(hookname
, "post-stop") == 0)
3774 which
= LXCHOOK_POSTSTOP
;
3775 else if (strcmp(hookname
, "clone") == 0)
3776 which
= LXCHOOK_CLONE
;
3777 else if (strcmp(hookname
, "destroy") == 0)
3778 which
= LXCHOOK_DESTROY
;
3782 lxc_list_for_each (it
, &conf
->hooks
[which
]) {
3784 char *hook
= it
->elem
;
3786 ret
= run_script_argv(name
, conf
->hooks_version
, "lxc", hook
,
3795 int lxc_clear_config_caps(struct lxc_conf
*c
)
3797 struct lxc_list
*it
, *next
;
3799 lxc_list_for_each_safe (it
, &c
->caps
, next
) {
3808 static int lxc_free_idmap(struct lxc_list
*id_map
)
3810 struct lxc_list
*it
, *next
;
3812 lxc_list_for_each_safe (it
, id_map
, next
) {
3821 int lxc_clear_idmaps(struct lxc_conf
*c
)
3823 return lxc_free_idmap(&c
->id_map
);
3826 int lxc_clear_config_keepcaps(struct lxc_conf
*c
)
3828 struct lxc_list
*it
, *next
;
3830 lxc_list_for_each_safe (it
, &c
->keepcaps
, next
) {
3839 int lxc_clear_namespace(struct lxc_conf
*c
)
3842 for (i
= 0; i
< LXC_NS_MAX
; i
++) {
3843 free(c
->ns_share
[i
]);
3844 c
->ns_share
[i
] = NULL
;
3849 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
, int version
)
3851 char *global_token
, *namespaced_token
;
3852 size_t namespaced_token_len
;
3853 struct lxc_list
*it
, *next
, *list
;
3854 const char *k
= key
;
3857 if (version
== CGROUP2_SUPER_MAGIC
) {
3858 global_token
= "lxc.cgroup2";
3859 namespaced_token
= "lxc.cgroup2.";
3860 namespaced_token_len
= STRLITERALLEN("lxc.cgroup2.");
3862 } else if (version
== CGROUP_SUPER_MAGIC
) {
3863 global_token
= "lxc.cgroup";
3864 namespaced_token
= "lxc.cgroup.";
3865 namespaced_token_len
= STRLITERALLEN("lxc.cgroup.");
3871 if (strcmp(key
, global_token
) == 0)
3873 else if (strncmp(key
, namespaced_token
, namespaced_token_len
) == 0)
3874 k
+= namespaced_token_len
;
3878 lxc_list_for_each_safe (it
, list
, next
) {
3879 struct lxc_cgroup
*cg
= it
->elem
;
3881 if (!all
&& strcmp(cg
->subsystem
, k
) != 0)
3885 free(cg
->subsystem
);
3894 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
3896 struct lxc_list
*it
, *next
;
3897 const char *k
= NULL
;
3900 if (strcmp(key
, "lxc.limit") == 0 || strcmp(key
, "lxc.prlimit") == 0)
3902 else if (strncmp(key
, "lxc.limit.", STRLITERALLEN("lxc.limit.")) == 0)
3903 k
= key
+ STRLITERALLEN("lxc.limit.");
3904 else if (strncmp(key
, "lxc.prlimit.", STRLITERALLEN("lxc.prlimit.")) == 0)
3905 k
= key
+ STRLITERALLEN("lxc.prlimit.");
3909 lxc_list_for_each_safe (it
, &c
->limits
, next
) {
3910 struct lxc_limit
*lim
= it
->elem
;
3912 if (!all
&& strcmp(lim
->resource
, k
) != 0)
3916 free(lim
->resource
);
3924 int lxc_clear_sysctls(struct lxc_conf
*c
, const char *key
)
3926 struct lxc_list
*it
, *next
;
3927 const char *k
= NULL
;
3930 if (strcmp(key
, "lxc.sysctl") == 0)
3932 else if (strncmp(key
, "lxc.sysctl.", STRLITERALLEN("lxc.sysctl.")) == 0)
3933 k
= key
+ STRLITERALLEN("lxc.sysctl.");
3937 lxc_list_for_each_safe (it
, &c
->sysctls
, next
) {
3938 struct lxc_sysctl
*elem
= it
->elem
;
3940 if (!all
&& strcmp(elem
->key
, k
) != 0)
3953 int lxc_clear_procs(struct lxc_conf
*c
, const char *key
)
3955 struct lxc_list
*it
, *next
;
3956 const char *k
= NULL
;
3959 if (strcmp(key
, "lxc.proc") == 0)
3961 else if (strncmp(key
, "lxc.proc.", STRLITERALLEN("lxc.proc.")) == 0)
3962 k
= key
+ STRLITERALLEN("lxc.proc.");
3966 lxc_list_for_each_safe (it
, &c
->procs
, next
) {
3967 struct lxc_proc
*proc
= it
->elem
;
3969 if (!all
&& strcmp(proc
->filename
, k
) != 0)
3973 free(proc
->filename
);
3982 int lxc_clear_groups(struct lxc_conf
*c
)
3984 struct lxc_list
*it
, *next
;
3986 lxc_list_for_each_safe (it
, &c
->groups
, next
) {
3995 int lxc_clear_environment(struct lxc_conf
*c
)
3997 struct lxc_list
*it
, *next
;
3999 lxc_list_for_each_safe (it
, &c
->environment
, next
) {
4008 int lxc_clear_mount_entries(struct lxc_conf
*c
)
4010 struct lxc_list
*it
, *next
;
4012 lxc_list_for_each_safe (it
, &c
->mount_list
, next
) {
4021 int lxc_clear_automounts(struct lxc_conf
*c
)
4027 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
4030 struct lxc_list
*it
, *next
;
4031 const char *k
= NULL
;
4032 bool all
= false, done
= false;
4034 if (strcmp(key
, "lxc.hook") == 0)
4036 else if (strncmp(key
, "lxc.hook.", STRLITERALLEN("lxc.hook.")) == 0)
4037 k
= key
+ STRLITERALLEN("lxc.hook.");
4041 for (i
= 0; i
< NUM_LXC_HOOKS
; i
++) {
4042 if (all
|| strcmp(k
, lxchook_names
[i
]) == 0) {
4043 lxc_list_for_each_safe (it
, &c
->hooks
[i
], next
) {
4054 ERROR("Invalid hook key: %s", key
);
4061 static inline void lxc_clear_aliens(struct lxc_conf
*conf
)
4063 struct lxc_list
*it
, *next
;
4065 lxc_list_for_each_safe (it
, &conf
->aliens
, next
) {
4072 void lxc_clear_includes(struct lxc_conf
*conf
)
4074 struct lxc_list
*it
, *next
;
4076 lxc_list_for_each_safe (it
, &conf
->includes
, next
) {
4083 int lxc_clear_apparmor_raw(struct lxc_conf
*c
)
4085 struct lxc_list
*it
, *next
;
4087 lxc_list_for_each_safe (it
, &c
->lsm_aa_raw
, next
) {
4096 void lxc_conf_free(struct lxc_conf
*conf
)
4101 if (current_config
== conf
)
4102 current_config
= NULL
;
4103 lxc_terminal_conf_free(&conf
->console
);
4104 free(conf
->rootfs
.mount
);
4105 free(conf
->rootfs
.bdev_type
);
4106 free(conf
->rootfs
.options
);
4107 free(conf
->rootfs
.path
);
4108 free(conf
->logfile
);
4109 if (conf
->logfd
!= -1)
4111 free(conf
->utsname
);
4112 free(conf
->ttys
.dir
);
4113 free(conf
->ttys
.tty_names
);
4116 free(conf
->execute_cmd
);
4117 free(conf
->init_cmd
);
4118 free(conf
->init_cwd
);
4119 free(conf
->unexpanded_config
);
4121 lxc_free_networks(&conf
->network
);
4122 free(conf
->lsm_aa_profile
);
4123 free(conf
->lsm_aa_profile_computed
);
4124 free(conf
->lsm_se_context
);
4125 lxc_seccomp_free(&conf
->seccomp
);
4126 lxc_clear_config_caps(conf
);
4127 lxc_clear_config_keepcaps(conf
);
4128 lxc_clear_cgroups(conf
, "lxc.cgroup", CGROUP_SUPER_MAGIC
);
4129 lxc_clear_cgroups(conf
, "lxc.cgroup2", CGROUP2_SUPER_MAGIC
);
4130 lxc_clear_hooks(conf
, "lxc.hook");
4131 lxc_clear_mount_entries(conf
);
4132 lxc_clear_idmaps(conf
);
4133 lxc_clear_groups(conf
);
4134 lxc_clear_includes(conf
);
4135 lxc_clear_aliens(conf
);
4136 lxc_clear_environment(conf
);
4137 lxc_clear_limits(conf
, "lxc.prlimit");
4138 lxc_clear_sysctls(conf
, "lxc.sysctl");
4139 lxc_clear_procs(conf
, "lxc.proc");
4140 lxc_clear_apparmor_raw(conf
);
4141 lxc_clear_namespace(conf
);
4142 free(conf
->cgroup_meta
.dir
);
4143 free(conf
->cgroup_meta
.controllers
);
4144 free(conf
->shmount
.path_host
);
4145 free(conf
->shmount
.path_cont
);
4149 struct userns_fn_data
{
4151 const char *fn_name
;
4156 static int run_userns_fn(void *data
)
4160 struct userns_fn_data
*d
= data
;
4162 /* Close write end of the pipe. */
4165 /* Wait for parent to finish establishing a new mapping in the user
4166 * namespace we are executing in.
4168 ret
= lxc_read_nointr(d
->p
[0], &c
, 1);
4169 /* Close read end of the pipe. */
4175 TRACE("Calling function \"%s\"", d
->fn_name
);
4177 /* Call function to run. */
4178 return d
->fn(d
->arg
);
4181 static struct id_map
*mapped_nsid_add(struct lxc_conf
*conf
, unsigned id
,
4184 const struct id_map
*map
;
4185 struct id_map
*retmap
;
4187 map
= find_mapped_nsid_entry(conf
, id
, idtype
);
4191 retmap
= malloc(sizeof(*retmap
));
4195 memcpy(retmap
, map
, sizeof(*retmap
));
4199 static struct id_map
*find_mapped_hostid_entry(struct lxc_conf
*conf
,
4200 unsigned id
, enum idtype idtype
)
4203 struct lxc_list
*it
;
4204 struct id_map
*retmap
= NULL
;
4206 lxc_list_for_each (it
, &conf
->id_map
) {
4208 if (map
->idtype
!= idtype
)
4211 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
4220 /* Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
4221 * existing one or establish a new one.
4223 static struct id_map
*mapped_hostid_add(struct lxc_conf
*conf
, uid_t id
,
4227 struct id_map
*entry
= NULL
, *tmp
= NULL
;
4229 entry
= malloc(sizeof(*entry
));
4233 /* Reuse existing mapping. */
4234 tmp
= find_mapped_hostid_entry(conf
, id
, type
);
4236 return memcpy(entry
, tmp
, sizeof(*entry
));
4238 /* Find new mapping. */
4239 hostid_mapped
= find_unmapped_nsid(conf
, type
);
4240 if (hostid_mapped
< 0) {
4241 DEBUG("Failed to find free mapping for id %d", id
);
4246 entry
->idtype
= type
;
4247 entry
->nsid
= hostid_mapped
;
4248 entry
->hostid
= (unsigned long)id
;
4254 struct lxc_list
*get_minimal_idmap(struct lxc_conf
*conf
)
4256 __do_free
struct id_map
*container_root_uid
= NULL
,
4257 *container_root_gid
= NULL
,
4258 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4259 __do_free
struct lxc_list
*idmap
= NULL
;
4261 uid_t nsuid
= (conf
->root_nsuid_map
!= NULL
) ? 0 : conf
->init_uid
;
4262 gid_t nsgid
= (conf
->root_nsgid_map
!= NULL
) ? 0 : conf
->init_gid
;
4263 struct lxc_list
*tmplist
= NULL
;
4265 /* Find container root mappings. */
4266 container_root_uid
= mapped_nsid_add(conf
, nsuid
, ID_TYPE_UID
);
4267 if (!container_root_uid
) {
4268 DEBUG("Failed to find mapping for namespace uid %d", 0);
4272 if (euid
>= container_root_uid
->hostid
&&
4273 euid
< (container_root_uid
->hostid
+ container_root_uid
->range
))
4274 host_uid_map
= container_root_uid
;
4276 container_root_gid
= mapped_nsid_add(conf
, nsgid
, ID_TYPE_GID
);
4277 if (!container_root_gid
) {
4278 DEBUG("Failed to find mapping for namespace gid %d", 0);
4282 if (egid
>= container_root_gid
->hostid
&&
4283 egid
< (container_root_gid
->hostid
+ container_root_gid
->range
))
4284 host_gid_map
= container_root_gid
;
4286 /* Check whether the {g,u}id of the user has a mapping. */
4288 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4289 if (!host_uid_map
) {
4290 DEBUG("Failed to find mapping for uid %d", euid
);
4295 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4296 if (!host_gid_map
) {
4297 DEBUG("Failed to find mapping for gid %d", egid
);
4301 /* Allocate new {g,u}id map list. */
4302 idmap
= malloc(sizeof(*idmap
));
4305 lxc_list_init(idmap
);
4307 /* Add container root to the map. */
4308 tmplist
= malloc(sizeof(*tmplist
));
4311 lxc_list_add_elem(tmplist
, container_root_uid
);
4312 lxc_list_add_tail(idmap
, tmplist
);
4314 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4315 /* idmap will now keep track of that memory. */
4316 move_ptr(container_root_uid
);
4318 /* Add container root to the map. */
4319 tmplist
= malloc(sizeof(*tmplist
));
4322 lxc_list_add_elem(tmplist
, host_uid_map
);
4323 lxc_list_add_tail(idmap
, tmplist
);
4325 /* idmap will now keep track of that memory. */
4326 move_ptr(container_root_uid
);
4327 /* idmap will now keep track of that memory. */
4328 move_ptr(host_uid_map
);
4330 tmplist
= malloc(sizeof(*tmplist
));
4333 lxc_list_add_elem(tmplist
, container_root_gid
);
4334 lxc_list_add_tail(idmap
, tmplist
);
4336 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4337 /* idmap will now keep track of that memory. */
4338 move_ptr(container_root_gid
);
4340 tmplist
= malloc(sizeof(*tmplist
));
4343 lxc_list_add_elem(tmplist
, host_gid_map
);
4344 lxc_list_add_tail(idmap
, tmplist
);
4346 /* idmap will now keep track of that memory. */
4347 move_ptr(container_root_gid
);
4348 /* idmap will now keep track of that memory. */
4349 move_ptr(host_gid_map
);
4351 TRACE("Allocated minimal idmapping");
4352 return move_ptr(idmap
);
4355 /* Run a function in a new user namespace.
4356 * The caller's euid/egid will be mapped if it is not already.
4357 * Afaict, userns_exec_1() is only used to operate based on privileges for the
4358 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
4359 * This means we require only to establish a mapping from:
4360 * - the container root {g,u}id as seen from the host > user's host {g,u}id
4361 * - the container root -> some sub{g,u}id
4362 * The former we add, if the user did not specify a mapping. The latter we
4363 * retrieve from the container's configured {g,u}id mappings as it must have been
4364 * there to start the container in the first place.
4366 int userns_exec_1(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4367 const char *fn_name
)
4371 struct userns_fn_data d
;
4372 struct lxc_list
*idmap
;
4373 int ret
= -1, status
= -1;
4379 idmap
= get_minimal_idmap(conf
);
4383 ret
= pipe2(p
, O_CLOEXEC
);
4385 SYSERROR("Failed to create pipe");
4389 d
.fn_name
= fn_name
;
4394 /* Clone child in new user namespace. */
4395 pid
= lxc_raw_clone_cb(run_userns_fn
, &d
, CLONE_NEWUSER
, NULL
);
4397 ERROR("Failed to clone process in new user namespace");
4404 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4405 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4407 struct lxc_list
*it
;
4409 lxc_list_for_each (it
, idmap
) {
4411 TRACE("Establishing %cid mapping for \"%d\" in new "
4412 "user namespace: nsuid %lu - hostid %lu - range "
4414 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4415 map
->nsid
, map
->hostid
, map
->range
);
4419 /* Set up {g,u}id mapping for user namespace of child process. */
4420 ret
= lxc_map_ids(idmap
, pid
);
4422 ERROR("Error setting up {g,u}id mappings for child process \"%d\"", pid
);
4426 /* Tell child to proceed. */
4427 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4428 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4437 /* Wait for child to finish. */
4439 status
= wait_for_pid(pid
);
4447 int userns_exec_full(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4448 const char *fn_name
)
4454 struct lxc_list
*cur
;
4455 struct userns_fn_data d
;
4458 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
4459 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
4460 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4465 ret
= pipe2(p
, O_CLOEXEC
);
4467 SYSERROR("opening pipe");
4471 d
.fn_name
= fn_name
;
4476 /* Clone child in new user namespace. */
4477 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
, NULL
);
4479 ERROR("Failed to clone process in new user namespace");
4489 /* Allocate new {g,u}id map list. */
4490 idmap
= malloc(sizeof(*idmap
));
4493 lxc_list_init(idmap
);
4495 /* Find container root. */
4496 lxc_list_for_each (cur
, &conf
->id_map
) {
4497 struct id_map
*tmpmap
;
4499 tmplist
= malloc(sizeof(*tmplist
));
4503 tmpmap
= malloc(sizeof(*tmpmap
));
4509 memset(tmpmap
, 0, sizeof(*tmpmap
));
4510 memcpy(tmpmap
, cur
->elem
, sizeof(*tmpmap
));
4511 tmplist
->elem
= tmpmap
;
4513 lxc_list_add_tail(idmap
, tmplist
);
4517 if (map
->idtype
== ID_TYPE_UID
)
4518 if (euid
>= map
->hostid
&& euid
< map
->hostid
+ map
->range
)
4521 if (map
->idtype
== ID_TYPE_GID
)
4522 if (egid
>= map
->hostid
&& egid
< map
->hostid
+ map
->range
)
4528 if (map
->idtype
== ID_TYPE_UID
)
4529 if (container_root_uid
== NULL
)
4530 container_root_uid
= map
;
4532 if (map
->idtype
== ID_TYPE_GID
)
4533 if (container_root_gid
== NULL
)
4534 container_root_gid
= map
;
4537 if (!container_root_uid
|| !container_root_gid
) {
4538 ERROR("No mapping for container root found");
4542 /* Check whether the {g,u}id of the user has a mapping. */
4544 host_uid_map
= mapped_hostid_add(conf
, euid
, ID_TYPE_UID
);
4546 host_uid_map
= container_root_uid
;
4549 host_gid_map
= mapped_hostid_add(conf
, egid
, ID_TYPE_GID
);
4551 host_gid_map
= container_root_gid
;
4553 if (!host_uid_map
) {
4554 DEBUG("Failed to find mapping for uid %d", euid
);
4558 if (!host_gid_map
) {
4559 DEBUG("Failed to find mapping for gid %d", egid
);
4563 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4564 /* Add container root to the map. */
4565 tmplist
= malloc(sizeof(*tmplist
));
4568 lxc_list_add_elem(tmplist
, host_uid_map
);
4569 lxc_list_add_tail(idmap
, tmplist
);
4571 /* idmap will now keep track of that memory. */
4572 host_uid_map
= NULL
;
4574 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4575 tmplist
= malloc(sizeof(*tmplist
));
4578 lxc_list_add_elem(tmplist
, host_gid_map
);
4579 lxc_list_add_tail(idmap
, tmplist
);
4581 /* idmap will now keep track of that memory. */
4582 host_gid_map
= NULL
;
4584 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4585 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4586 lxc_list_for_each (cur
, idmap
) {
4588 TRACE("establishing %cid mapping for \"%d\" in new "
4589 "user namespace: nsuid %lu - hostid %lu - range "
4591 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4592 map
->nsid
, map
->hostid
, map
->range
);
4596 /* Set up {g,u}id mapping for user namespace of child process. */
4597 ret
= lxc_map_ids(idmap
, pid
);
4599 ERROR("error setting up {g,u}id mappings for child process \"%d\"", pid
);
4603 /* Tell child to proceed. */
4604 if (lxc_write_nointr(p
[1], &c
, 1) != 1) {
4605 SYSERROR("Failed telling child process \"%d\" to proceed", pid
);
4614 /* Wait for child to finish. */
4616 ret
= wait_for_pid(pid
);
4619 lxc_free_idmap(idmap
);
4623 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
4625 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
4631 /* not thread-safe, do not use from api without first forking */
4632 static char *getuname(void)
4634 __do_free
char *buf
= NULL
;
4635 struct passwd pwent
;
4636 struct passwd
*pwentp
= NULL
;
4640 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
4644 buf
= malloc(bufsize
);
4648 ret
= getpwuid_r(geteuid(), &pwent
, buf
, bufsize
, &pwentp
);
4651 WARN("Could not find matched password record.");
4653 ERROR("Failed to get password record - %u", geteuid());
4657 return strdup(pwent
.pw_name
);
4660 /* not thread-safe, do not use from api without first forking */
4661 static char *getgname(void)
4663 __do_free
char *buf
= NULL
;
4665 struct group
*grentp
= NULL
;
4669 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
4673 buf
= malloc(bufsize
);
4677 ret
= getgrgid_r(getegid(), &grent
, buf
, bufsize
, &grentp
);
4680 WARN("Could not find matched group record");
4682 ERROR("Failed to get group record - %u", getegid());
4686 return strdup(grent
.gr_name
);
4689 /* not thread-safe, do not use from api without first forking */
4690 void suggest_default_idmap(void)
4692 __do_free
char *gname
= NULL
, *line
= NULL
, *uname
= NULL
;
4693 __do_fclose
FILE *subuid_f
= NULL
, *subgid_f
= NULL
;
4694 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
4705 subuid_f
= fopen(subuidfile
, "r");
4707 ERROR("Your system is not configured with subuids");
4711 while (getline(&line
, &len
, subuid_f
) != -1) {
4713 size_t no_newline
= 0;
4715 p
= strchr(line
, ':');
4723 if (strcmp(line
, uname
))
4726 p2
= strchr(p
, ':');
4733 no_newline
= strcspn(p2
, "\n");
4734 p2
[no_newline
] = '\0';
4736 if (lxc_safe_uint(p
, &uid
) < 0)
4737 WARN("Could not parse UID");
4738 if (lxc_safe_uint(p2
, &urange
) < 0)
4739 WARN("Could not parse UID range");
4742 subgid_f
= fopen(subgidfile
, "r");
4744 ERROR("Your system is not configured with subgids");
4748 while (getline(&line
, &len
, subgid_f
) != -1) {
4750 size_t no_newline
= 0;
4752 p
= strchr(line
, ':');
4760 if (strcmp(line
, uname
))
4763 p2
= strchr(p
, ':');
4770 no_newline
= strcspn(p2
, "\n");
4771 p2
[no_newline
] = '\0';
4773 if (lxc_safe_uint(p
, &gid
) < 0)
4774 WARN("Could not parse GID");
4775 if (lxc_safe_uint(p2
, &grange
) < 0)
4776 WARN("Could not parse GID range");
4779 if (!urange
|| !grange
) {
4780 ERROR("You do not have subuids or subgids allocated");
4781 ERROR("Unprivileged containers require subuids and subgids");
4785 ERROR("You must either run as root, or define uid mappings");
4786 ERROR("To pass uid mappings to lxc-create, you could create");
4787 ERROR("~/.config/lxc/default.conf:");
4788 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
4789 ERROR("lxc.idmap = u 0 %u %u", uid
, urange
);
4790 ERROR("lxc.idmap = g 0 %u %u", gid
, grange
);
4793 static void free_cgroup_settings(struct lxc_list
*result
)
4795 struct lxc_list
*iterator
, *next
;
4797 lxc_list_for_each_safe (iterator
, result
, next
) {
4798 lxc_list_del(iterator
);
4804 /* Return the list of cgroup_settings sorted according to the following rules
4805 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4807 struct lxc_list
*sort_cgroup_settings(struct lxc_list
*cgroup_settings
)
4809 struct lxc_list
*result
;
4810 struct lxc_cgroup
*cg
= NULL
;
4811 struct lxc_list
*it
= NULL
, *item
= NULL
, *memsw_limit
= NULL
;
4813 result
= malloc(sizeof(*result
));
4816 lxc_list_init(result
);
4818 /* Iterate over the cgroup settings and copy them to the output list. */
4819 lxc_list_for_each (it
, cgroup_settings
) {
4820 item
= malloc(sizeof(*item
));
4822 free_cgroup_settings(result
);
4826 item
->elem
= it
->elem
;
4828 if (strcmp(cg
->subsystem
, "memory.memsw.limit_in_bytes") == 0) {
4829 /* Store the memsw_limit location */
4831 } else if (strcmp(cg
->subsystem
, "memory.limit_in_bytes") == 0 &&
4832 memsw_limit
!= NULL
) {
4833 /* lxc.cgroup.memory.memsw.limit_in_bytes is found
4834 * before lxc.cgroup.memory.limit_in_bytes, swap these
4836 item
->elem
= memsw_limit
->elem
;
4837 memsw_limit
->elem
= it
->elem
;
4839 lxc_list_add_tail(result
, item
);