]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/attach.c
attach: rework attaching to namespace fds
[mirror_lxc.git] / src / lxc / attach.c
CommitLineData
cc73685d 1/* SPDX-License-Identifier: LGPL-2.1+ */
e0732705 2
d38dd64a
CB
3#ifndef _GNU_SOURCE
4#define _GNU_SOURCE 1
5#endif
e0732705
CS
6#include <errno.h>
7#include <fcntl.h>
c476bdce 8#include <grp.h>
604ca1c0 9#include <linux/unistd.h>
6f4f1937 10#include <pwd.h>
0bece477 11#include <pthread.h>
6f4f1937
CB
12#include <signal.h>
13#include <stdio.h>
14#include <stdlib.h>
15#include <string.h>
6f4f1937 16#include <sys/mount.h>
e0732705
CS
17#include <sys/param.h>
18#include <sys/prctl.h>
5ec27989 19#include <sys/socket.h>
1ba0013f 20#include <sys/syscall.h>
905022f7 21#include <sys/wait.h>
604ca1c0
CB
22#include <termios.h>
23#include <unistd.h>
6f4f1937
CB
24
25#include <lxc/lxccontainer.h>
e0732705 26
81f466d0 27#include "af_unix.h"
e0732705
CS
28#include "attach.h"
29#include "caps.h"
9c4693b8 30#include "cgroup.h"
6f4f1937 31#include "commands.h"
2c4ea790 32#include "conf.h"
6f4f1937 33#include "config.h"
9b8e3c96 34#include "confile.h"
6f4f1937
CB
35#include "log.h"
36#include "lsm/lsm.h"
37#include "lxclock.h"
38#include "lxcseccomp.h"
604ca1c0 39#include "macro.h"
ba2be1a8 40#include "mainloop.h"
cd8f5663 41#include "memory_utils.h"
657256e0 42#include "mount_utils.h"
6f4f1937 43#include "namespace.h"
f40988c7 44#include "process_utils.h"
a9f0cecf 45#include "sync.h"
59524108 46#include "syscall_wrappers.h"
0ed9b1bc 47#include "terminal.h"
6f4f1937 48#include "utils.h"
9c4693b8
CS
49
50#if HAVE_SYS_PERSONALITY_H
51#include <sys/personality.h>
52#endif
e0732705 53
ac2cecc4 54lxc_log_define(attach, lxc);
e0732705 55
ef05d368
CB
56/* Define default options if no options are supplied by the user. */
57static lxc_attach_options_t attach_static_default_options = LXC_ATTACH_OPTIONS_DEFAULT;
58
ab919e5f 59struct attach_context {
500ed813 60 int init_pid;
0e304baa
CB
61 char *lsm_label;
62 struct lxc_container *container;
63 signed long personality;
64 unsigned long long capability_mask;
65 int ns_inherited;
66 int ns_fd[LXC_NS_MAX];
67 struct lsm_ops *lsm_ops;
68};
69
6e36c297
CB
70static inline bool sync_wake_pid(int fd, pid_t pid)
71{
72 return lxc_write_nointr(fd, &pid, sizeof(pid_t)) == sizeof(pid_t);
73}
74
75static inline bool sync_wait_pid(int fd, pid_t *pid)
76{
77 return lxc_read_nointr(fd, pid, sizeof(pid_t)) == sizeof(pid_t);
78}
79
80static inline bool sync_wake_fd(int fd, int fd_send)
81{
82 return lxc_abstract_unix_send_fds(fd, &fd_send, 1, NULL, 0) > 0;
83}
84
85static inline bool sync_wait_fd(int fd, int *fd_recv)
86{
87 return lxc_abstract_unix_recv_fds(fd, fd_recv, 1, NULL, 0) > 0;
88}
89
9745eb8a
CB
90static struct attach_context *alloc_attach_context(void)
91{
92 return zalloc(sizeof(struct attach_context));
93}
94
ee142207
CB
95static int get_personality(const char *name, const char *lxcpath,
96 signed long *personality)
d92c8e40
CB
97{
98 __do_free char *p = NULL;
ee142207 99 signed long per;
d92c8e40
CB
100
101 p = lxc_cmd_get_config_item(name, "lxc.arch", lxcpath);
ee142207
CB
102 if (!p) {
103 *personality = LXC_ARCH_UNCHANGED;
104 return 0;
105 }
d92c8e40 106
ee142207
CB
107 per = lxc_config_parse_arch(p);
108 if (per == LXC_ARCH_UNCHANGED)
109 return ret_errno(EINVAL);
110
111 *personality = per;
112 return 0;
d92c8e40
CB
113}
114
500ed813
CB
115static int get_attach_context(struct attach_context *ctx,
116 struct lxc_container *container)
e0732705 117{
cd8f5663
CB
118 __do_free char *line = NULL;
119 __do_fclose FILE *proc_file = NULL;
6f4f1937
CB
120 int ret;
121 bool found;
604ca1c0 122 char proc_fn[LXC_PROC_STATUS_LEN];
e0732705 123 size_t line_bufsz = 0;
e0732705 124
500ed813
CB
125 ctx->container = container;
126
127 ctx->init_pid = lxc_cmd_get_init_pid(container->name, container->config_path);
128 if (ctx->init_pid < 0)
129 return log_error(-1, "Failed to get init pid");
130
8ce83369 131 /* Read capabilities. */
500ed813 132 ret = snprintf(proc_fn, LXC_PROC_STATUS_LEN, "/proc/%d/status", ctx->init_pid);
604ca1c0 133 if (ret < 0 || ret >= LXC_PROC_STATUS_LEN)
9745eb8a 134 return -EIO;
e0732705 135
ffeeed8b
CB
136 proc_file = fopen(proc_fn, "re");
137 if (!proc_file)
9745eb8a 138 return log_error_errno(-errno, errno, "Failed to open %s", proc_fn);
8ce83369
CB
139
140 found = false;
ea918412 141
e0732705 142 while (getline(&line, &line_bufsz, proc_file) != -1) {
9745eb8a 143 ret = sscanf(line, "CapBnd: %llx", &ctx->capability_mask);
8ce83369
CB
144 if (ret != EOF && ret == 1) {
145 found = true;
e0732705
CS
146 break;
147 }
148 }
149
ffeeed8b 150 if (!found)
9745eb8a 151 return log_error_errno(-ENOENT, ENOENT, "Failed to read capability bounding set from %s", proc_fn);
e0732705 152
4eb19ac0 153 ctx->lsm_ops = lsm_init_static();
d701d729 154
500ed813 155 ctx->lsm_label = ctx->lsm_ops->process_label_get(ctx->lsm_ops, ctx->init_pid);
9745eb8a 156 ctx->ns_inherited = 0;
b87ee312 157 for (int i = 0; i < LXC_NS_MAX; i++)
9745eb8a 158 ctx->ns_fd[i] = -EBADF;
e0732705 159
ee142207
CB
160 ret = get_personality(container->name, container->config_path, &ctx->personality);
161 if (ret)
162 return log_error_errno(ret, errno, "Failed to get personality of the container");
d92c8e40 163
1874ef74
CB
164 if (!ctx->container->lxc_conf) {
165 ctx->container->lxc_conf = lxc_conf_init();
166 if (!ctx->container->lxc_conf)
167 return log_error_errno(-ENOMEM, ENOMEM, "Failed to allocate new lxc config");
168 }
169
9745eb8a 170 return 0;
e0732705
CS
171}
172
299d1198
CB
173/**
174 * in_same_namespace - Check whether two processes are in the same namespace.
175 * @pid1 - PID of the first process.
176 * @pid2 - PID of the second process.
177 * @ns - Name of the namespace to check. Must correspond to one of the names
178 * for the namespaces as shown in /proc/<pid/ns/
179 *
180 * If the two processes are not in the same namespace returns an fd to the
181 * namespace of the second process identified by @pid2. If the two processes are
182 * in the same namespace returns -EINVAL, -1 if an error occurred.
183 */
184static int in_same_namespace(pid_t pid1, pid_t pid2, const char *ns)
185{
644e7393 186 __do_close int ns_fd1 = -EBADF, ns_fd2 = -EBADF;
3cc629fe 187 int ret = -1;
299d1198
CB
188 struct stat ns_st1, ns_st2;
189
190 ns_fd1 = lxc_preserve_ns(pid1, ns);
134284c3
CB
191 if (ns_fd1 < 0) {
192 /* The kernel does not support this namespace. This is not an
193 * error.
194 */
195 if (errno == ENOENT)
196 return -EINVAL;
197
3cc629fe 198 return -1;
134284c3 199 }
299d1198
CB
200
201 ns_fd2 = lxc_preserve_ns(pid2, ns);
21d0acc2 202 if (ns_fd2 < 0)
3cc629fe 203 return -1;
299d1198
CB
204
205 ret = fstat(ns_fd1, &ns_st1);
21d0acc2 206 if (ret < 0)
3cc629fe 207 return -1;
299d1198
CB
208
209 ret = fstat(ns_fd2, &ns_st2);
21d0acc2 210 if (ret < 0)
3cc629fe 211 return -1;
299d1198
CB
212
213 /* processes are in the same namespace */
3cc629fe
CB
214 if ((ns_st1.st_dev == ns_st2.st_dev) && (ns_st1.st_ino == ns_st2.st_ino))
215 return -EINVAL;
299d1198
CB
216
217 /* processes are in different namespaces */
3cc629fe 218 return move_fd(ns_fd2);
299d1198
CB
219}
220
b7873c95
CB
221static int get_attach_context_nsfds(struct attach_context *ctx,
222 lxc_attach_options_t *options)
223{
224
225 pid_t pid_self = lxc_raw_getpid();
226
227 for (int i = 0; i < LXC_NS_MAX; i++) {
228 int j;
229
230 if (options->namespaces & ns_info[i].clone_flag)
231 ctx->ns_fd[i] = lxc_preserve_ns(ctx->init_pid, ns_info[i].proc_name);
232 else if (ctx->ns_inherited & ns_info[i].clone_flag)
233 ctx->ns_fd[i] = in_same_namespace(pid_self, ctx->init_pid, ns_info[i].proc_name);
234 else
235 continue;
236
237 if (ctx->ns_fd[i] >= 0)
238 continue;
239
240 if (ctx->ns_fd[i] == -EINVAL) {
241 DEBUG("Inheriting %s namespace from %d", ns_info[i].proc_name, pid_self);
242 ctx->ns_inherited &= ~ns_info[i].clone_flag;
243 continue;
244 }
245
246 /* We failed to preserve the namespace. */
247 SYSERROR("Failed to attach to %s namespace of %d", ns_info[i].proc_name, pid_self);
248
249 /* Close all already opened file descriptors before we return an
250 * error, so we don't leak them.
251 */
252 for (j = 0; j < i; j++)
253 close_prot_errno_disarm(ctx->ns_fd[j]);
254
255 return -1;
256 }
257
258 return 0;
259}
260
7e995801 261static inline void close_nsfds(struct attach_context *ctx)
b7873c95
CB
262{
263 for (int i = 0; i < LXC_NS_MAX; i++)
264 close_prot_errno_disarm(ctx->ns_fd[i]);
265}
266
267static void put_attach_context(struct attach_context *ctx)
268{
269 free_disarm(ctx->lsm_label);
270
271 if (ctx->container) {
272 lxc_container_put(ctx->container);
273 ctx->container = NULL;
274 }
275
7e995801 276 close_nsfds(ctx);
b7873c95
CB
277 free(ctx);
278}
279
39b3b69b 280static int attach_nsfds(struct attach_context *ctx)
99d50954 281{
ffeeed8b
CB
282 for (int i = 0; i < LXC_NS_MAX; i++) {
283 int ret;
99d50954 284
877f3a04 285 if (ctx->ns_fd[i] < 0)
26818618
CB
286 continue;
287
21d0acc2 288 ret = setns(ctx->ns_fd[i], ns_info[i].clone_flag);
ffeeed8b 289 if (ret < 0)
39b3b69b
CB
290 return log_error_errno(-1, errno,
291 "Failed to attach to %s namespace of %d",
292 ns_info[i].proc_name, ctx->init_pid);
99d50954 293
39b3b69b
CB
294 DEBUG("Attached to %s namespace of %d",
295 ns_info[i].proc_name, ctx->init_pid);
99d50954
CS
296 }
297
298 return 0;
299}
300
e4103cf6 301int lxc_attach_remount_sys_proc(void)
7a0b0b56
CS
302{
303 int ret;
304
305 ret = unshare(CLONE_NEWNS);
ffeeed8b
CB
306 if (ret < 0)
307 return log_error_errno(-1, errno, "Failed to unshare mount namespace");
7a0b0b56 308
9e61fb1f
CB
309 if (detect_shared_rootfs() && mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL))
310 SYSERROR("Failed to recursively turn root mount tree into dependent mount. Continuing...");
2c6f3fc9 311
8ce83369 312 /* Assume /proc is always mounted, so remount it. */
7a0b0b56 313 ret = umount2("/proc", MNT_DETACH);
ffeeed8b
CB
314 if (ret < 0)
315 return log_error_errno(-1, errno, "Failed to unmount /proc");
7a0b0b56 316
657256e0 317 ret = mount_filesystem("proc", "/proc", 0);
ffeeed8b
CB
318 if (ret < 0)
319 return log_error_errno(-1, errno, "Failed to remount /proc");
7a0b0b56 320
ffeeed8b
CB
321 /*
322 * Try to umount /sys. If it's not a mount point, we'll get EINVAL, then
8ce83369 323 * we ignore it because it may not have been mounted in the first place.
7a0b0b56
CS
324 */
325 ret = umount2("/sys", MNT_DETACH);
ffeeed8b
CB
326 if (ret < 0 && errno != EINVAL)
327 return log_error_errno(-1, errno, "Failed to unmount /sys");
328
329 /* Remount it. */
657256e0 330 if (ret == 0 && mount_filesystem("sysfs", "/sys", 0))
ffeeed8b 331 return log_error_errno(-1, errno, "Failed to remount /sys");
7a0b0b56
CS
332
333 return 0;
334}
335
677e1d27 336static int drop_capabilities(struct attach_context *ctx)
e0732705 337{
ffeeed8b 338 int last_cap;
e0732705 339
6f4f1937 340 last_cap = lxc_caps_last_cap();
ffeeed8b 341 for (int cap = 0; cap <= last_cap; cap++) {
e0732705
CS
342 if (ctx->capability_mask & (1LL << cap))
343 continue;
344
b81689a1 345 if (prctl(PR_CAPBSET_DROP, prctl_arg(cap), prctl_arg(0),
ffeeed8b
CB
346 prctl_arg(0), prctl_arg(0)))
347 return log_error_errno(-1, errno, "Failed to drop capability %d", cap);
ea918412 348
94ac256f 349 TRACE("Dropped capability %d", cap);
e0732705
CS
350 }
351
352 return 0;
353}
905022f7 354
ab919e5f 355static int lxc_attach_set_environment(struct attach_context *ctx,
7385273f 356 enum lxc_attach_env_policy_t policy,
6f4f1937 357 char **extra_env, char **extra_keep)
b3a39ba6 358{
3d55242a 359 int ret;
7385273f 360 struct lxc_list *iterator;
361
799f96fd 362 if (policy == LXC_ATTACH_CLEAR_ENV) {
3d5e9f48 363 int path_kept = 0;
6f4f1937 364 char **extra_keep_store = NULL;
3d5e9f48
CS
365
366 if (extra_keep) {
367 size_t count, i;
368
3d55242a
CB
369 for (count = 0; extra_keep[count]; count++)
370 ;
3d5e9f48 371
89b7bfe3 372 extra_keep_store = zalloc(count * sizeof(char *));
3d55242a 373 if (!extra_keep_store)
3d5e9f48 374 return -1;
3d55242a 375
3d5e9f48
CS
376 for (i = 0; i < count; i++) {
377 char *v = getenv(extra_keep[i]);
378 if (v) {
379 extra_keep_store[i] = strdup(v);
380 if (!extra_keep_store[i]) {
3d5e9f48
CS
381 while (i > 0)
382 free(extra_keep_store[--i]);
ea918412 383
3d5e9f48
CS
384 free(extra_keep_store);
385 return -1;
386 }
3d55242a 387
3d5e9f48
CS
388 if (strcmp(extra_keep[i], "PATH") == 0)
389 path_kept = 1;
390 }
3d5e9f48
CS
391 }
392 }
393
799f96fd 394 if (clearenv()) {
a9cab7e3 395 if (extra_keep_store) {
3d55242a
CB
396 char **p;
397
a9cab7e3
CS
398 for (p = extra_keep_store; *p; p++)
399 free(*p);
3d55242a 400
a9cab7e3
CS
401 free(extra_keep_store);
402 }
3d55242a 403
ffeeed8b 404 return log_error(-1, "Failed to clear environment");
3d5e9f48
CS
405 }
406
407 if (extra_keep_store) {
408 size_t i;
6f4f1937 409
3d5e9f48 410 for (i = 0; extra_keep[i]; i++) {
acd4922e 411 if (extra_keep_store[i]) {
3d55242a
CB
412 ret = setenv(extra_keep[i], extra_keep_store[i], 1);
413 if (ret < 0)
a24c5678 414 SYSWARN("Failed to set environment variable");
acd4922e 415 }
ea918412 416
3d5e9f48
CS
417 free(extra_keep_store[i]);
418 }
ea918412 419
3d5e9f48
CS
420 free(extra_keep_store);
421 }
422
8ce83369
CB
423 /* Always set a default path; shells and execlp tend to be fine
424 * without it, but there is a disturbing number of C programs
425 * out there that just assume that getenv("PATH") is never NULL
426 * and then die a painful segfault death.
427 */
3d55242a
CB
428 if (!path_kept) {
429 ret = setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
430 if (ret < 0)
a24c5678 431 SYSWARN("Failed to set environment variable");
3d55242a 432 }
b3a39ba6
DW
433 }
434
3d55242a 435 ret = putenv("container=lxc");
ffeeed8b 436 if (ret < 0)
818a57fc 437 return log_warn(-1, "Failed to set environment variable");
b3a39ba6 438
7385273f 439 /* Set container environment variables.*/
ab919e5f
CB
440 if (ctx && ctx->container && ctx->container->lxc_conf) {
441 lxc_list_for_each(iterator, &ctx->container->lxc_conf->environment) {
3d55242a
CB
442 char *env_tmp;
443
444 env_tmp = strdup((char *)iterator->elem);
445 if (!env_tmp)
7385273f 446 return -1;
7385273f 447
3d55242a 448 ret = putenv(env_tmp);
ffeeed8b
CB
449 if (ret < 0)
450 return log_error_errno(-1, errno, "Failed to set environment variable: %s", (char *)iterator->elem);
7385273f 451 }
452 }
453
8ce83369 454 /* Set extra environment variables. */
3d5e9f48
CS
455 if (extra_env) {
456 for (; *extra_env; extra_env++) {
3d55242a 457 char *p;
ea918412 458
8ce83369
CB
459 /* We just assume the user knows what they are doing, so
460 * we don't do any checks.
461 */
3d55242a
CB
462 p = strdup(*extra_env);
463 if (!p)
3d5e9f48 464 return -1;
3d55242a
CB
465
466 ret = putenv(p);
467 if (ret < 0)
a24c5678 468 SYSWARN("Failed to set environment variable");
3d5e9f48
CS
469 }
470 }
471
b3a39ba6
DW
472 return 0;
473}
474
74a3920a 475static char *lxc_attach_getpwshell(uid_t uid)
905022f7 476{
1b9c9f5b 477 __do_free char *line = NULL, *result = NULL;
cd8f5663 478 __do_fclose FILE *pipe_f = NULL;
6f4f1937 479 int fd, ret;
905022f7
CS
480 pid_t pid;
481 int pipes[2];
3fa23ac3
CB
482 bool found = false;
483 size_t line_bufsz = 0;
905022f7 484
8ce83369
CB
485 /* We need to fork off a process that runs the getent program, and we
486 * need to capture its output, so we use a pipe for that purpose.
905022f7 487 */
3fa23ac3 488 ret = pipe2(pipes, O_CLOEXEC);
905022f7
CS
489 if (ret < 0)
490 return NULL;
491
492 pid = fork();
493 if (pid < 0) {
494 close(pipes[0]);
495 close(pipes[1]);
496 return NULL;
497 }
498
3fa23ac3 499 if (!pid) {
905022f7
CS
500 char uid_buf[32];
501 char *arguments[] = {
502 "getent",
503 "passwd",
504 uid_buf,
505 NULL
506 };
507
508 close(pipes[0]);
509
8ce83369 510 /* We want to capture stdout. */
3fa23ac3 511 ret = dup2(pipes[1], STDOUT_FILENO);
905022f7 512 close(pipes[1]);
3fa23ac3 513 if (ret < 0)
ea918412 514 _exit(EXIT_FAILURE);
905022f7 515
8ce83369
CB
516 /* Get rid of stdin/stderr, so we try to associate it with
517 * /dev/null.
905022f7 518 */
3fa23ac3 519 fd = open_devnull();
905022f7 520 if (fd < 0) {
3fa23ac3
CB
521 close(STDIN_FILENO);
522 close(STDERR_FILENO);
905022f7 523 } else {
3fa23ac3 524 (void)dup3(fd, STDIN_FILENO, O_CLOEXEC);
59f0e209 525 (void)dup3(fd, STDERR_FILENO, O_CLOEXEC);
905022f7
CS
526 close(fd);
527 }
528
8ce83369 529 /* Finish argument list. */
3fa23ac3
CB
530 ret = snprintf(uid_buf, sizeof(uid_buf), "%ld", (long)uid);
531 if (ret <= 0 || ret >= sizeof(uid_buf))
ea918412 532 _exit(EXIT_FAILURE);
905022f7 533
8ce83369 534 /* Try to run getent program. */
3fa23ac3 535 (void)execvp("getent", arguments);
ea918412 536 _exit(EXIT_FAILURE);
905022f7 537 }
3fa23ac3
CB
538
539 close(pipes[1]);
540
4110345b 541 pipe_f = fdopen(pipes[0], "re");
cf4026f1
CB
542 if (!pipe_f) {
543 close(pipes[0]);
544 goto reap_child;
545 }
546 /* Transfer ownership of pipes[0] to pipe_f. */
547 move_fd(pipes[0]);
548
3fa23ac3
CB
549 while (getline(&line, &line_bufsz, pipe_f) != -1) {
550 int i;
551 long value;
552 char *token;
553 char *endptr = NULL, *saveptr = NULL;
554
555 /* If we already found something, just continue to read
556 * until the pipe doesn't deliver any more data, but
557 * don't modify the existing data structure.
558 */
559 if (found)
560 continue;
561
18d4ffde 562 if (!line)
563 continue;
564
3fa23ac3
CB
565 /* Trim line on the right hand side. */
566 for (i = strlen(line); i > 0 && (line[i - 1] == '\n' || line[i - 1] == '\r'); --i)
567 line[i - 1] = '\0';
568
569 /* Split into tokens: first: user name. */
570 token = strtok_r(line, ":", &saveptr);
571 if (!token)
572 continue;
573
574 /* next: dummy password field */
575 token = strtok_r(NULL, ":", &saveptr);
576 if (!token)
577 continue;
578
579 /* next: user id */
580 token = strtok_r(NULL, ":", &saveptr);
581 value = token ? strtol(token, &endptr, 10) : 0;
582 if (!token || !endptr || *endptr || value == LONG_MIN ||
ea918412 583 value == LONG_MAX)
3fa23ac3
CB
584 continue;
585
586 /* dummy sanity check: user id matches */
587 if ((uid_t)value != uid)
588 continue;
589
590 /* skip fields: gid, gecos, dir, go to next field 'shell' */
591 for (i = 0; i < 4; i++) {
592 token = strtok_r(NULL, ":", &saveptr);
593 if (!token)
594 continue;
595 }
ea918412 596
3fa23ac3
CB
597 if (!token)
598 continue;
ea918412 599
1b9c9f5b 600 free_disarm(result);
3fa23ac3
CB
601 result = strdup(token);
602
603 /* Sanity check that there are no fields after that. */
604 token = strtok_r(NULL, ":", &saveptr);
605 if (token)
606 continue;
607
608 found = true;
609 }
ea918412 610
cf4026f1 611reap_child:
3fa23ac3 612 ret = wait_for_pid(pid);
1b9c9f5b 613 if (ret < 0)
3fa23ac3 614 return NULL;
3fa23ac3 615
1b9c9f5b 616 if (!found)
3fa23ac3 617 return NULL;
3fa23ac3 618
1b9c9f5b 619 return move_ptr(result);
905022f7 620}
cb3e61fa 621
6f4f1937 622static void lxc_attach_get_init_uidgid(uid_t *init_uid, gid_t *init_gid)
cb3e61fa 623{
cd8f5663
CB
624 __do_free char *line = NULL;
625 __do_fclose FILE *proc_file = NULL;
604ca1c0 626 char proc_fn[LXC_PROC_STATUS_LEN];
8ce83369 627 int ret;
cb3e61fa 628 size_t line_bufsz = 0;
cb3e61fa 629 long value = -1;
a5d657d3
CB
630 uid_t uid = LXC_INVALID_UID;
631 gid_t gid = LXC_INVALID_GID;
cb3e61fa 632
604ca1c0
CB
633 ret = snprintf(proc_fn, LXC_PROC_STATUS_LEN, "/proc/%d/status", 1);
634 if (ret < 0 || ret >= LXC_PROC_STATUS_LEN)
7fb45c93 635 return;
cb3e61fa 636
4110345b 637 proc_file = fopen(proc_fn, "re");
cb3e61fa
CS
638 if (!proc_file)
639 return;
640
641 while (getline(&line, &line_bufsz, proc_file) != -1) {
8ce83369
CB
642 /* Format is: real, effective, saved set user, fs we only care
643 * about real uid.
cb3e61fa
CS
644 */
645 ret = sscanf(line, "Uid: %ld", &value);
8ce83369 646 if (ret != EOF && ret == 1) {
6f4f1937 647 uid = (uid_t)value;
cb3e61fa
CS
648 } else {
649 ret = sscanf(line, "Gid: %ld", &value);
8ce83369 650 if (ret != EOF && ret == 1)
6f4f1937 651 gid = (gid_t)value;
cb3e61fa 652 }
ea918412 653
a5d657d3 654 if (uid != LXC_INVALID_UID && gid != LXC_INVALID_GID)
cb3e61fa
CS
655 break;
656 }
657
8ce83369 658 /* Only override arguments if we found something. */
a5d657d3 659 if (uid != LXC_INVALID_UID)
cb3e61fa 660 *init_uid = uid;
ea918412 661
a5d657d3 662 if (gid != LXC_INVALID_GID)
cb3e61fa
CS
663 *init_gid = gid;
664
665 /* TODO: we should also parse supplementary groups and use
8ce83369
CB
666 * setgroups() to set them.
667 */
cb3e61fa 668}
9c4693b8 669
d4db3d14 670static bool fetch_seccomp(struct lxc_container *c, lxc_attach_options_t *options)
2c4ea790 671{
cd8f5663 672 __do_free char *path = NULL;
d4db3d14
CB
673 int ret;
674 bool bret;
2eef2bda 675
6f4f1937
CB
676 if (!(options->namespaces & CLONE_NEWNS) ||
677 !(options->attach_flags & LXC_ATTACH_LSM)) {
cca66e06 678 free_disarm(c->lxc_conf->seccomp.seccomp);
2c4ea790 679 return true;
bd4307f0 680 }
bd7b4e28 681
2e812c16 682 /* Remove current setting. */
d4db3d14 683 if (!c->set_config_item(c, "lxc.seccomp.profile", "") &&
ea918412 684 !c->set_config_item(c, "lxc.seccomp", ""))
2c4ea790 685 return false;
bd7b4e28 686
8ce83369 687 /* Fetch the current profile path over the cmd interface. */
0b427da0 688 path = c->get_running_config_item(c, "lxc.seccomp.profile");
bd7b4e28 689 if (!path) {
d4db3d14 690 INFO("Failed to retrieve lxc.seccomp.profile");
ea918412 691
0b427da0 692 path = c->get_running_config_item(c, "lxc.seccomp");
cca66e06
CB
693 if (!path)
694 return log_info(true, "Failed to retrieve lxc.seccomp");
bd7b4e28
SG
695 }
696
8ce83369 697 /* Copy the value into the new lxc_conf. */
d4db3d14 698 bret = c->set_config_item(c, "lxc.seccomp.profile", path);
d4db3d14
CB
699 if (!bret)
700 return false;
bd7b4e28 701
8ce83369 702 /* Attempt to parse the resulting config. */
d4db3d14 703 ret = lxc_read_seccomp_config(c->lxc_conf);
cca66e06
CB
704 if (ret < 0)
705 return log_error(false, "Failed to retrieve seccomp policy");
2c4ea790 706
cca66e06 707 return log_info(true, "Retrieved seccomp policy");
2e812c16
CB
708}
709
6f4f1937 710static bool no_new_privs(struct lxc_container *c, lxc_attach_options_t *options)
2e812c16 711{
cd8f5663 712 __do_free char *val = NULL;
2e812c16 713
2e812c16 714 /* Remove current setting. */
02d3b72b
CB
715 if (!c->set_config_item(c, "lxc.no_new_privs", ""))
716 return log_info(false, "Failed to unset lxc.no_new_privs");
2e812c16
CB
717
718 /* Retrieve currently active setting. */
719 val = c->get_running_config_item(c, "lxc.no_new_privs");
02d3b72b
CB
720 if (!val)
721 return log_info(false, "Failed to retrieve lxc.no_new_privs");
2e812c16
CB
722
723 /* Set currently active setting. */
cd8f5663 724 return c->set_config_item(c, "lxc.no_new_privs", val);
2c4ea790
SH
725}
726
338b230f 727struct attach_payload {
a998454a 728 int ipc_socket;
cecf3e83 729 int terminal_pts_fd;
a998454a 730 lxc_attach_options_t *options;
ab919e5f 731 struct attach_context *ctx;
a998454a
CB
732 lxc_attach_exec_t exec_function;
733 void *exec_payload;
734};
735
338b230f 736static void put_attach_payload(struct attach_payload *p)
ba2be1a8 737{
81102768 738 close_prot_errno_disarm(p->ipc_socket);
cecf3e83 739 close_prot_errno_disarm(p->terminal_pts_fd);
ab919e5f 740 if (p->ctx) {
dd53c8af 741 put_attach_context(p->ctx);
ab919e5f 742 p->ctx = NULL;
b21da190 743 }
ba2be1a8
CB
744}
745
338b230f 746__noreturn static void do_attach(struct attach_payload *ap)
a998454a 747{
427a8067 748 int lsm_fd, ret;
a998454a
CB
749 uid_t new_uid;
750 gid_t new_gid;
936efc72
CB
751 uid_t ns_root_uid = 0;
752 gid_t ns_root_gid = 0;
338b230f
CB
753 lxc_attach_options_t* options = ap->options;
754 struct attach_context *ctx = ap->ctx;
ab919e5f 755 struct lxc_conf *conf = ctx->container->lxc_conf;
57de839f
CB
756 bool needs_lsm = (options->namespaces & CLONE_NEWNS) &&
757 (options->attach_flags & LXC_ATTACH_LSM) &&
ab919e5f 758 ctx->lsm_label;
8455e39e 759 char *lsm_label = NULL;
a998454a
CB
760
761 /* A description of the purpose of this functionality is provided in the
762 * lxc-attach(1) manual page. We have to remount here and not in the
763 * parent process, otherwise /proc may not properly reflect the new pid
764 * namespace.
765 */
766 if (!(options->namespaces & CLONE_NEWNS) &&
767 (options->attach_flags & LXC_ATTACH_REMOUNT_PROC_SYS)) {
768 ret = lxc_attach_remount_sys_proc();
b75c344c
CB
769 if (ret < 0)
770 goto on_error;
ea918412 771
b75c344c 772 TRACE("Remounted \"/proc\" and \"/sys\"");
a998454a
CB
773 }
774
5b514ce3 775 /* Now perform additional attachments. */
a998454a 776#if HAVE_SYS_PERSONALITY_H
a998454a 777 if (options->attach_flags & LXC_ATTACH_SET_PERSONALITY) {
b75c344c
CB
778 long new_personality;
779
780 if (options->personality < 0)
ab919e5f 781 new_personality = ctx->personality;
b75c344c
CB
782 else
783 new_personality = options->personality;
ea918412 784
ee142207
CB
785 if (new_personality != LXC_ARCH_UNCHANGED) {
786 ret = personality(new_personality);
787 if (ret < 0)
788 goto on_error;
ea918412 789
ee142207
CB
790 TRACE("Set new personality");
791 }
a998454a
CB
792 }
793#endif
794
795 if (options->attach_flags & LXC_ATTACH_DROP_CAPABILITIES) {
677e1d27 796 ret = drop_capabilities(ctx);
b75c344c
CB
797 if (ret < 0)
798 goto on_error;
ea918412 799
b75c344c 800 TRACE("Dropped capabilities");
a998454a
CB
801 }
802
803 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
804 * if you want this to be a no-op).
805 */
ab919e5f 806 ret = lxc_attach_set_environment(ctx,
7385273f 807 options->env_policy,
a998454a
CB
808 options->extra_env_vars,
809 options->extra_keep_env);
b75c344c
CB
810 if (ret < 0)
811 goto on_error;
ea918412 812
b75c344c 813 TRACE("Set up environment");
a998454a 814
57de839f
CB
815 /* This remark only affects fully unprivileged containers:
816 * Receive fd for LSM security module before we set{g,u}id(). The reason
817 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
818 * we will change our effective uid. This means our effective uid will
819 * be different from the effective uid of the process that created us
820 * which means that this processs no longer has capabilities in our
821 * namespace including CAP_SYS_PTRACE. This means we will not be able to
822 * read and /proc/<pid> files for the process anymore when /proc is
823 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
824 * set{g,u}id().
825 */
826 if (needs_lsm) {
f8e88e94 827 if (!sync_wait_fd(ap->ipc_socket, ATTACH_SYNC_LSM(&lsm_fd))) {
6e36c297 828 SYSERROR("Failed to receive lsm label fd");
b75c344c 829 goto on_error;
9044b79e 830 }
831
57de839f
CB
832 TRACE("Received LSM label file descriptor %d from parent", lsm_fd);
833 }
834
08ea9270 835 if (options->stdin_fd > 0 && isatty(options->stdin_fd)) {
cd0a2b2f 836 ret = lxc_make_controlling_terminal(options->stdin_fd);
08ea9270
CB
837 if (ret < 0)
838 goto on_error;
839 }
840
b58214ac
CB
841 if (!lxc_setgroups(0, NULL) && errno != EPERM)
842 goto on_error;
843
936efc72
CB
844 if (options->namespaces & CLONE_NEWUSER) {
845 /* Check whether nsuid 0 has a mapping. */
846 ns_root_uid = get_ns_uid(0);
ea918412 847
936efc72
CB
848 /* Check whether nsgid 0 has a mapping. */
849 ns_root_gid = get_ns_gid(0);
a998454a 850
936efc72
CB
851 /* If there's no mapping for nsuid 0 try to retrieve the nsuid
852 * init was started with.
853 */
854 if (ns_root_uid == LXC_INVALID_UID)
855 lxc_attach_get_init_uidgid(&ns_root_uid, &ns_root_gid);
ea918412 856
936efc72
CB
857 if (ns_root_uid == LXC_INVALID_UID)
858 goto on_error;
a998454a 859
464c4611 860 if (!lxc_switch_uid_gid(ns_root_uid, ns_root_gid))
b75c344c 861 goto on_error;
a998454a
CB
862 }
863
936efc72
CB
864 /* Set {u,g}id. */
865 if (options->uid != LXC_INVALID_UID)
866 new_uid = options->uid;
867 else
868 new_uid = ns_root_uid;
869
870 if (options->gid != LXC_INVALID_GID)
871 new_gid = options->gid;
872 else
873 new_gid = ns_root_gid;
874
57de839f 875 if (needs_lsm) {
d3ba7c98 876 bool on_exec;
a998454a
CB
877
878 /* Change into our new LSM profile. */
d3ba7c98 879 on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? true : false;
65129087
CB
880 if (options->attach_flags & LXC_ATTACH_LSM_LABEL)
881 lsm_label = options->lsm_label;
882 if (!lsm_label)
ab919e5f
CB
883 lsm_label = ctx->lsm_label;
884 ret = ctx->lsm_ops->process_label_set_at(ctx->lsm_ops, lsm_fd,
885 lsm_label, on_exec);
cb2420df 886 close_prot_errno_disarm(lsm_fd);
b75c344c
CB
887 if (ret < 0)
888 goto on_error;
ea918412 889
ab919e5f 890 TRACE("Set %s LSM label to \"%s\"", ctx->lsm_ops->name, ctx->lsm_label);
a998454a
CB
891 }
892
ab919e5f 893 if ((ctx->container && conf && conf->no_new_privs) ||
6ce8e678
AL
894 (options->attach_flags & LXC_ATTACH_NO_NEW_PRIVS)) {
895 ret = prctl(PR_SET_NO_NEW_PRIVS, prctl_arg(1), prctl_arg(0),
896 prctl_arg(0), prctl_arg(0));
897 if (ret < 0)
898 goto on_error;
899
900 TRACE("Set PR_SET_NO_NEW_PRIVS");
901 }
902
ab919e5f 903 if (ctx->container && conf && conf->seccomp.seccomp) {
cdb2a47f 904 ret = lxc_seccomp_load(conf);
b75c344c
CB
905 if (ret < 0)
906 goto on_error;
ea918412 907
b75c344c 908 TRACE("Loaded seccomp profile");
cdb2a47f 909
338b230f 910 ret = lxc_seccomp_send_notifier_fd(&conf->seccomp, ap->ipc_socket);
c3e3c21a
CB
911 if (ret < 0)
912 goto on_error;
a998454a 913 }
ea918412 914
338b230f 915 close_prot_errno_disarm(ap->ipc_socket);
dd53c8af 916 put_attach_context(ctx);
338b230f 917 ap->ctx = NULL;
a998454a
CB
918
919 /* The following is done after the communication socket is shut down.
920 * That way, all errors that might (though unlikely) occur up until this
921 * point will have their messages printed to the original stderr (if
922 * logging is so configured) and not the fd the user supplied, if any.
923 */
924
925 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
926 * may want to make sure the fds are closed, for example.
927 */
08ea9270 928 if (options->stdin_fd >= 0 && options->stdin_fd != STDIN_FILENO)
b4959848
CB
929 if (dup2(options->stdin_fd, STDIN_FILENO))
930 DEBUG("Failed to replace stdin with %d", options->stdin_fd);
08ea9270
CB
931
932 if (options->stdout_fd >= 0 && options->stdout_fd != STDOUT_FILENO)
b4959848
CB
933 if (dup2(options->stdout_fd, STDOUT_FILENO))
934 DEBUG("Failed to replace stdout with %d", options->stdin_fd);
08ea9270
CB
935
936 if (options->stderr_fd >= 0 && options->stderr_fd != STDERR_FILENO)
b4959848
CB
937 if (dup2(options->stderr_fd, STDERR_FILENO))
938 DEBUG("Failed to replace stderr with %d", options->stdin_fd);
a998454a
CB
939
940 /* close the old fds */
08ea9270 941 if (options->stdin_fd > STDERR_FILENO)
a998454a 942 close(options->stdin_fd);
08ea9270
CB
943
944 if (options->stdout_fd > STDERR_FILENO)
a998454a 945 close(options->stdout_fd);
08ea9270
CB
946
947 if (options->stderr_fd > STDERR_FILENO)
a998454a
CB
948 close(options->stderr_fd);
949
427a8067
CB
950 /*
951 * Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
a998454a
CB
952 * here, ignore errors.
953 */
427a8067 954 for (int fd = STDIN_FILENO; fd <= STDERR_FILENO; fd++) {
3f62938a 955 ret = fd_cloexec(fd, false);
b75c344c
CB
956 if (ret < 0) {
957 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd);
958 goto on_error;
959 }
a998454a
CB
960 }
961
9e84479f 962 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
338b230f 963 ret = lxc_terminal_prepare_login(ap->terminal_pts_fd);
ba2be1a8 964 if (ret < 0) {
338b230f 965 SYSERROR("Failed to prepare terminal file descriptor %d", ap->terminal_pts_fd);
ba2be1a8
CB
966 goto on_error;
967 }
ea918412 968
338b230f 969 TRACE("Prepared terminal file descriptor %d", ap->terminal_pts_fd);
ba2be1a8
CB
970 }
971
936efc72
CB
972 /* Avoid unnecessary syscalls. */
973 if (new_uid == ns_root_uid)
974 new_uid = LXC_INVALID_UID;
975
976 if (new_gid == ns_root_gid)
977 new_gid = LXC_INVALID_GID;
c353b0b9 978
6aff5157 979 /* Make sure that the processes STDIO is correctly owned by the user that we are switching to */
c353b0b9
CB
980 ret = fix_stdio_permissions(new_uid);
981 if (ret)
a2c26bef 982 INFO("Failed to adjust stdio permissions");
936efc72 983
464c4611 984 if (!lxc_switch_uid_gid(new_uid, new_gid))
936efc72
CB
985 goto on_error;
986
a998454a 987 /* We're done, so we can now do whatever the user intended us to do. */
338b230f 988 _exit(ap->exec_function(ap->exec_payload));
b75c344c
CB
989
990on_error:
338b230f 991 put_attach_payload(ap);
dab02267 992 ERROR("Failed to attach to container");
c7ac2e1c 993 _exit(EXIT_FAILURE);
a998454a
CB
994}
995
f797f05e 996static int lxc_attach_terminal(const char *name, const char *lxcpath, struct lxc_conf *conf,
9e84479f 997 struct lxc_terminal *terminal)
ba2be1a8
CB
998{
999 int ret;
1000
9e84479f 1001 lxc_terminal_init(terminal);
ba2be1a8 1002
8ea93a0f 1003 ret = lxc_terminal_create(name, lxcpath, conf, terminal);
c2af3a15
CB
1004 if (ret < 0)
1005 return log_error(-1, "Failed to create terminal");
ba2be1a8 1006
ba2be1a8 1007 return 0;
ba2be1a8
CB
1008}
1009
9e84479f
CB
1010static int lxc_attach_terminal_mainloop_init(struct lxc_terminal *terminal,
1011 struct lxc_epoll_descr *descr)
ba2be1a8
CB
1012{
1013 int ret;
1014
1015 ret = lxc_mainloop_open(descr);
c2af3a15
CB
1016 if (ret < 0)
1017 return log_error(-1, "Failed to create mainloop");
ba2be1a8 1018
9e84479f 1019 ret = lxc_terminal_mainloop_add(descr, terminal);
ba2be1a8 1020 if (ret < 0) {
ba2be1a8 1021 lxc_mainloop_close(descr);
c2af3a15 1022 return log_error(-1, "Failed to add handlers to mainloop");
ba2be1a8
CB
1023 }
1024
1025 return 0;
1026}
1027
36a94ce8 1028static inline void lxc_attach_terminal_close_ptx(struct lxc_terminal *terminal)
ba2be1a8 1029{
36a94ce8 1030 close_prot_errno_disarm(terminal->ptx);
ba2be1a8
CB
1031}
1032
cecf3e83 1033static inline void lxc_attach_terminal_close_pts(struct lxc_terminal *terminal)
ba2be1a8 1034{
41808e20 1035 close_prot_errno_disarm(terminal->pty);
ba2be1a8
CB
1036}
1037
9e84479f 1038static inline void lxc_attach_terminal_close_peer(struct lxc_terminal *terminal)
ba2be1a8 1039{
19a3e906 1040 close_prot_errno_disarm(terminal->peer);
ba2be1a8
CB
1041}
1042
9e84479f 1043static inline void lxc_attach_terminal_close_log(struct lxc_terminal *terminal)
ba2be1a8 1044{
19a3e906 1045 close_prot_errno_disarm(terminal->log_fd);
ba2be1a8
CB
1046}
1047
908fbc1a
CB
1048int lxc_attach(struct lxc_container *container, lxc_attach_exec_t exec_function,
1049 void *exec_payload, lxc_attach_options_t *options,
1050 pid_t *attached_process)
9c4693b8 1051{
6f9fe5d0 1052 int ret_parent = -1;
6f9fe5d0 1053 struct lxc_epoll_descr descr = {};
a9f0cecf 1054 int ret;
26abd7ea 1055 char *name, *lxcpath;
9c4693b8 1056 int ipc_sockets[2];
500ed813 1057 pid_t attached_pid, pid, to_cleanup_pid;
ab919e5f 1058 struct attach_context *ctx;
9e84479f 1059 struct lxc_terminal terminal;
1cce35e6 1060 struct lxc_conf *conf;
9c4693b8 1061
908fbc1a 1062 if (!container)
540a2f70 1063 return ret_set_errno(-1, EINVAL);
908fbc1a
CB
1064
1065 if (!lxc_container_get(container))
540a2f70 1066 return ret_set_errno(-1, EINVAL);
908fbc1a
CB
1067
1068 name = container->name;
1069 lxcpath = container->config_path;
1070
9c4693b8
CS
1071 if (!options)
1072 options = &attach_static_default_options;
1073
9745eb8a 1074 ctx = alloc_attach_context();
ab919e5f 1075 if (!ctx) {
9745eb8a
CB
1076 lxc_container_put(container);
1077 return log_error_errno(-ENOMEM, ENOMEM, "Failed to allocate attach context");
1078 }
1079
500ed813 1080 ret = get_attach_context(ctx, container);
9745eb8a 1081 if (ret) {
7e995801 1082 put_attach_context(ctx);
74ce42b5 1083 return log_error(-1, "Failed to get attach context");
9c4693b8
CS
1084 }
1085
ab919e5f 1086 conf = ctx->container->lxc_conf;
ba773996 1087
ab919e5f 1088 if (!fetch_seccomp(ctx->container, options))
ae026f55 1089 WARN("Failed to get seccomp policy");
2c4ea790 1090
ab919e5f 1091 if (!no_new_privs(ctx->container, options))
ae026f55 1092 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set");
2e812c16 1093
74ce42b5 1094 /* Determine which namespaces the container was created with. */
9c4693b8
CS
1095 if (options->namespaces == -1) {
1096 options->namespaces = lxc_cmd_get_clone_flags(name, lxcpath);
9c4693b8 1097 if (options->namespaces == -1) {
dd53c8af 1098 put_attach_context(ctx);
74ce42b5 1099 return log_error(-1, "Failed to automatically determine the namespaces which the container uses");
9c4693b8 1100 }
877f3a04 1101
74ce42b5 1102 for (int i = 0; i < LXC_NS_MAX; i++) {
877f3a04
CB
1103 if (ns_info[i].clone_flag & CLONE_NEWCGROUP)
1104 if (!(options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) ||
1105 !cgns_supported())
1106 continue;
1107
1108 if (ns_info[i].clone_flag & options->namespaces)
1109 continue;
1110
ab919e5f 1111 ctx->ns_inherited |= ns_info[i].clone_flag;
877f3a04
CB
1112 }
1113 }
1114
b7873c95
CB
1115 ret = get_attach_context_nsfds(ctx, options);
1116 if (ret) {
b7873c95 1117 lxc_container_put(container);
74ce42b5 1118 return log_error(-1, "Failed to get namespace file descriptors");
9c4693b8
CS
1119 }
1120
9e84479f 1121 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
f797f05e 1122 ret = lxc_attach_terminal(name, lxcpath, conf, &terminal);
ba2be1a8 1123 if (ret < 0) {
dd53c8af 1124 put_attach_context(ctx);
74ce42b5 1125 return log_error(-1, "Failed to setup new terminal");
ba2be1a8
CB
1126 }
1127
9e84479f 1128 terminal.log_fd = options->log_fd;
c948657b 1129 } else {
9e84479f 1130 lxc_terminal_init(&terminal);
ba2be1a8
CB
1131 }
1132
8ce83369
CB
1133 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1134 * to make sure we don't irritate other threads that want to fork+exec
1135 * away
9c4693b8
CS
1136 *
1137 * IMPORTANT: if the initial process is multithreaded and another call
1138 * just fork()s away without exec'ing directly after, the socket fd will
1139 * exist in the forked process from the other thread and any close() in
8ce83369 1140 * our own child process will not really cause the socket to close
1d801260 1141 * properly, potentially causing the parent to hang.
9c4693b8
CS
1142 *
1143 * For this reason, while IPC is still active, we have to use shutdown()
8ce83369
CB
1144 * if the child exits prematurely in order to signal that the socket is
1145 * closed and cannot assume that the child exiting will automatically do
1146 * that.
9c4693b8
CS
1147 *
1148 * IPC mechanism: (X is receiver)
1149 * initial process intermediate attached
1150 * X <--- send pid of
1151 * attached proc,
1152 * then exit
1153 * send 0 ------------------------------------> X
1154 * [do initialization]
1155 * X <------------------------------------ send 1
1156 * [add to cgroup, ...]
1157 * send 2 ------------------------------------> X
81f466d0
CB
1158 * [set LXC_ATTACH_NO_NEW_PRIVS]
1159 * X <------------------------------------ send 3
1160 * [open LSM label fd]
1161 * send 4 ------------------------------------> X
1162 * [set LSM label]
9c4693b8
CS
1163 * close socket close socket
1164 * run program
1165 */
1166 ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, ipc_sockets);
1167 if (ret < 0) {
dd53c8af 1168 put_attach_context(ctx);
74ce42b5 1169 return log_error_errno(-1, errno, "Could not set up required IPC mechanism for attaching");
9c4693b8
CS
1170 }
1171
e3f0e436
CB
1172 /* Create intermediate subprocess, two reasons:
1173 * 1. We can't setns() in the child itself, since we want to make
8ce83369 1174 * sure we are properly attached to the pidns.
e3f0e436 1175 * 2. Also, the initial thread has to put the attached process
8ce83369
CB
1176 * into the cgroup, which we can only do if we didn't already
1177 * setns() (otherwise, user namespaces will hate us).
9c4693b8
CS
1178 */
1179 pid = fork();
9c4693b8 1180 if (pid < 0) {
dd53c8af 1181 put_attach_context(ctx);
74ce42b5 1182 return log_error_errno(-1, errno, "Failed to create first subprocess");
9c4693b8
CS
1183 }
1184
4f25e72f 1185 if (pid == 0) {
26abd7ea 1186 char *cwd, *new_cwd;
a588a482 1187
ba2be1a8 1188 /* close unneeded file descriptors */
4f25e72f 1189 close_prot_errno_disarm(ipc_sockets[0]);
2202afc9 1190
4f25e72f
CB
1191 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1192 lxc_attach_terminal_close_ptx(&terminal);
1193 lxc_attach_terminal_close_peer(&terminal);
1194 lxc_attach_terminal_close_log(&terminal);
f4364484
SG
1195 }
1196
4f25e72f 1197 /* Wait for the parent to have setup cgroups. */
6e48e7c5 1198 if (!sync_wait(ipc_sockets[1], ATTACH_SYNC_CGROUP)) {
4f25e72f 1199 shutdown(ipc_sockets[1], SHUT_RDWR);
dd53c8af 1200 put_attach_context(ctx);
4f25e72f 1201 _exit(EXIT_FAILURE);
bb2ada6f
CB
1202 }
1203
4f25e72f
CB
1204 TRACE("Intermediate process starting to initialize");
1205
a588a482
CB
1206 cwd = getcwd(NULL, 0);
1207
4f25e72f
CB
1208 /* Attach now, create another subprocess later, since pid namespaces
1209 * only really affect the children of the current process.
1210 */
39b3b69b 1211 ret = attach_nsfds(ctx);
4f25e72f
CB
1212 if (ret < 0) {
1213 ERROR("Failed to enter namespaces");
1214 shutdown(ipc_sockets[1], SHUT_RDWR);
dd53c8af 1215 put_attach_context(ctx);
4f25e72f 1216 _exit(EXIT_FAILURE);
ba2be1a8
CB
1217 }
1218
4f25e72f 1219 /* close namespace file descriptors */
7e995801 1220 close_nsfds(ctx);
ea918412 1221
4f25e72f
CB
1222 /* Attach succeeded, try to cwd. */
1223 if (options->initial_cwd)
1224 new_cwd = options->initial_cwd;
1225 else
1226 new_cwd = cwd;
1227 if (new_cwd) {
1228 ret = chdir(new_cwd);
1229 if (ret < 0)
1230 WARN("Could not change directory to \"%s\"", new_cwd);
ba2be1a8 1231 }
a588a482 1232 free_disarm(cwd);
c6d09e15 1233
4f25e72f 1234 /* Create attached process. */
4f25e72f
CB
1235 pid = lxc_raw_clone(CLONE_PARENT, NULL);
1236 if (pid < 0) {
1237 SYSERROR("Failed to clone attached process");
1238 shutdown(ipc_sockets[1], SHUT_RDWR);
dd53c8af 1239 put_attach_context(ctx);
4f25e72f
CB
1240 _exit(EXIT_FAILURE);
1241 }
f4364484 1242
4f25e72f 1243 if (pid == 0) {
338b230f 1244 struct attach_payload ap = {
a64902ab
CB
1245 .ipc_socket = ipc_sockets[1],
1246 .options = options,
1247 .ctx = ctx,
1248 .terminal_pts_fd = terminal.pty,
1249 .exec_function = exec_function,
1250 .exec_payload = exec_payload,
1251 };
1252
4f25e72f
CB
1253 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1254 ret = lxc_terminal_signal_sigmask_safe_blocked(&terminal);
1255 if (ret < 0) {
1256 SYSERROR("Failed to reset signal mask");
1257 _exit(EXIT_FAILURE);
1258 }
1259 }
ea918412 1260
a64902ab 1261 /* Does not return. */
338b230f 1262 do_attach(&ap);
62183f1a 1263 }
2eef2bda 1264
4f25e72f
CB
1265 if (options->attach_flags & LXC_ATTACH_TERMINAL)
1266 lxc_attach_terminal_close_pts(&terminal);
ea918412 1267
4f25e72f 1268 /* Tell grandparent the pid of the pid of the newly created child. */
f8e88e94 1269 if (!sync_wake_pid(ipc_sockets[1], ATTACH_SYNC_PID(pid))) {
4f25e72f
CB
1270 /* If this really happens here, this is very unfortunate, since
1271 * the parent will not know the pid of the attached process and
1272 * will not be able to wait for it (and we won't either due to
1273 * CLONE_PARENT) so the parent won't be able to reap it and the
1274 * attached process will remain a zombie.
1275 */
1276 shutdown(ipc_sockets[1], SHUT_RDWR);
dd53c8af 1277 put_attach_context(ctx);
4f25e72f
CB
1278 _exit(EXIT_FAILURE);
1279 }
9c4693b8 1280
4f25e72f 1281 TRACE("Sending pid %d of attached process", pid);
9c4693b8 1282
4f25e72f 1283 /* The rest is in the hands of the initial and the attached process. */
dd53c8af 1284 put_attach_context(ctx);
4f25e72f
CB
1285 _exit(EXIT_SUCCESS);
1286 }
6f4f1937 1287
4f25e72f 1288 to_cleanup_pid = pid;
ea918412 1289
4f25e72f 1290 /* close unneeded file descriptors */
cb2420df 1291 close_prot_errno_disarm(ipc_sockets[1]);
7e995801 1292 close_nsfds(ctx);
4f25e72f
CB
1293 if (options->attach_flags & LXC_ATTACH_TERMINAL)
1294 lxc_attach_terminal_close_pts(&terminal);
81f466d0 1295
4f25e72f
CB
1296 /* Attach to cgroup, if requested. */
1297 if (options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) {
1298 /*
1299 * If this is the unified hierarchy cgroup_attach() is
1300 * enough.
1301 */
1302 ret = cgroup_attach(conf, name, lxcpath, pid);
1303 if (ret) {
1304 call_cleaner(cgroup_exit) struct cgroup_ops *cgroup_ops = NULL;
9044b79e 1305
4f25e72f
CB
1306 cgroup_ops = cgroup_init(conf);
1307 if (!cgroup_ops)
1308 goto on_error;
9044b79e 1309
4f25e72f
CB
1310 if (!cgroup_ops->attach(cgroup_ops, conf, name, lxcpath, pid))
1311 goto on_error;
81f466d0 1312 }
4f25e72f
CB
1313 TRACE("Moved intermediate process %d into container's cgroups", pid);
1314 }
81f466d0 1315
4f25e72f
CB
1316 /* Setup /proc limits */
1317 if (!lxc_list_empty(&conf->procs)) {
1318 ret = setup_proc_filesystem(&conf->procs, pid);
1319 if (ret < 0)
1320 goto on_error;
4f3b6a85
CB
1321
1322 TRACE("Setup /proc/%d settings", pid);
4f25e72f 1323 }
cdb2a47f 1324
4f25e72f
CB
1325 /* Setup resource limits */
1326 if (!lxc_list_empty(&conf->limits)) {
1327 ret = setup_resource_limits(&conf->limits, pid);
1328 if (ret < 0)
1329 goto on_error;
4f3b6a85
CB
1330
1331 TRACE("Setup resource limits");
4f25e72f 1332 }
cdb2a47f 1333
4f25e72f
CB
1334 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1335 ret = lxc_attach_terminal_mainloop_init(&terminal, &descr);
1336 if (ret < 0)
1337 goto on_error;
9c4693b8 1338
4f25e72f
CB
1339 TRACE("Initialized terminal mainloop");
1340 }
9c4693b8 1341
4f25e72f 1342 /* Let the child process know to go ahead. */
6e48e7c5 1343 if (!sync_wake(ipc_sockets[0], ATTACH_SYNC_CGROUP))
4f25e72f 1344 goto close_mainloop;
ba2be1a8 1345
4f25e72f 1346 TRACE("Told intermediate process to start initializing");
ea918412 1347
4f25e72f 1348 /* Get pid of attached process from intermediate process. */
f8e88e94 1349 if (!sync_wait_pid(ipc_sockets[0], ATTACH_SYNC_PID(&attached_pid)))
4f25e72f 1350 goto close_mainloop;
ba2be1a8 1351
4f25e72f 1352 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid);
ba2be1a8 1353
4f25e72f 1354 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
5d2b46fb 1355 if (options->stdin_fd == STDIN_FILENO) {
4f25e72f
CB
1356 signal(SIGINT, SIG_IGN);
1357 signal(SIGQUIT, SIG_IGN);
1358 }
ba2be1a8 1359
4f25e72f
CB
1360 /* Reap intermediate process. */
1361 ret = wait_for_pid(pid);
1362 if (ret < 0)
1363 goto close_mainloop;
ba2be1a8 1364
4f25e72f 1365 TRACE("Intermediate process %d exited", pid);
ea918412 1366
4f25e72f
CB
1367 /* We will always have to reap the attached process now. */
1368 to_cleanup_pid = attached_pid;
9c4693b8 1369
4f25e72f
CB
1370 /* Open LSM fd and send it to child. */
1371 if ((options->namespaces & CLONE_NEWNS) &&
ab919e5f 1372 (options->attach_flags & LXC_ATTACH_LSM) && ctx->lsm_label) {
ad001fb6 1373 __do_close int labelfd = -EBADF;
4f25e72f 1374 bool on_exec;
ea918412 1375
4f25e72f 1376 on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? true : false;
ab919e5f
CB
1377 labelfd = ctx->lsm_ops->process_label_fd_get(ctx->lsm_ops,
1378 attached_pid, on_exec);
4f25e72f
CB
1379 if (labelfd < 0)
1380 goto close_mainloop;
9c4693b8 1381
4f25e72f 1382 TRACE("Opened LSM label file descriptor %d", labelfd);
ea918412 1383
4f25e72f 1384 /* Send child fd of the LSM security module to write to. */
f8e88e94 1385 if (!sync_wake_fd(ipc_sockets[0], ATTACH_SYNC_LSM(labelfd))) {
6e36c297 1386 SYSERROR("Failed to send lsm label fd");
4f25e72f
CB
1387 goto close_mainloop;
1388 }
1389
4f25e72f 1390 TRACE("Sent LSM label file descriptor %d to child", labelfd);
9c4693b8 1391 }
ea918412 1392
4f25e72f
CB
1393 if (conf->seccomp.seccomp) {
1394 ret = lxc_seccomp_recv_notifier_fd(&conf->seccomp, ipc_sockets[0]);
1395 if (ret < 0)
1396 goto close_mainloop;
9c4693b8 1397
4f25e72f 1398 ret = lxc_seccomp_add_notifier(name, lxcpath, &conf->seccomp);
d6d979bc 1399 if (ret < 0)
4f25e72f 1400 goto close_mainloop;
d6d979bc 1401 }
9c4693b8 1402
4f25e72f
CB
1403 /* We're done, the child process should now execute whatever it
1404 * is that the user requested. The parent can now track it with
1405 * waitpid() or similar.
1406 */
9c4693b8 1407
4f25e72f 1408 *attached_process = attached_pid;
a998454a 1409
4f25e72f
CB
1410 /* Now shut down communication with child, we're done. */
1411 shutdown(ipc_sockets[0], SHUT_RDWR);
cb2420df 1412 close_prot_errno_disarm(ipc_sockets[0]);
f157b056 1413
4f25e72f
CB
1414 ret_parent = 0;
1415 to_cleanup_pid = -1;
ea918412 1416
4f25e72f
CB
1417 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1418 ret = lxc_mainloop(&descr, -1);
1419 if (ret < 0) {
1420 ret_parent = -1;
1421 to_cleanup_pid = attached_pid;
1422 }
a998454a 1423 }
ea918412 1424
4f25e72f 1425close_mainloop:
9e84479f 1426 if (options->attach_flags & LXC_ATTACH_TERMINAL)
4f25e72f 1427 lxc_mainloop_close(&descr);
9c4693b8 1428
4f25e72f
CB
1429on_error:
1430 if (ipc_sockets[0] >= 0) {
1431 shutdown(ipc_sockets[0], SHUT_RDWR);
cb2420df 1432 close_prot_errno_disarm(ipc_sockets[0]);
9c4693b8 1433 }
ea918412 1434
4f25e72f
CB
1435 if (to_cleanup_pid > 0)
1436 (void)wait_for_pid(to_cleanup_pid);
1437
1438 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1439 lxc_terminal_delete(&terminal);
1440 lxc_terminal_conf_free(&terminal);
1441 }
9c4693b8 1442
dd53c8af 1443 put_attach_context(ctx);
4f25e72f 1444 return ret_parent;
9c4693b8
CS
1445}
1446
06346bb0 1447int lxc_attach_run_command(void *payload)
9c4693b8 1448{
06346bb0
CB
1449 int ret = -1;
1450 lxc_attach_command_t *cmd = payload;
9c4693b8 1451
06346bb0
CB
1452 ret = execvp(cmd->program, cmd->argv);
1453 if (ret < 0) {
1454 switch (errno) {
1455 case ENOEXEC:
1456 ret = 126;
cf0fd972 1457 break;
06346bb0
CB
1458 case ENOENT:
1459 ret = 127;
cf0fd972 1460 break;
06346bb0
CB
1461 }
1462 }
ea918412 1463
c2af3a15 1464 return log_error_errno(ret, errno, "Failed to exec \"%s\"", cmd->program);
9c4693b8
CS
1465}
1466
1467int lxc_attach_run_shell(void* payload)
1468{
cd8f5663 1469 __do_free char *buf = NULL;
9c4693b8 1470 uid_t uid;
cb7aa5e8
DJ
1471 struct passwd pwent;
1472 struct passwd *pwentp = NULL;
9c4693b8 1473 char *user_shell;
cb7aa5e8
DJ
1474 size_t bufsize;
1475 int ret;
9c4693b8 1476
8ce83369 1477 /* Ignore payload parameter. */
9c4693b8
CS
1478 (void)payload;
1479
1480 uid = getuid();
cb7aa5e8
DJ
1481
1482 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1483 if (bufsize == -1)
1484 bufsize = 1024;
1485
1486 buf = malloc(bufsize);
1487 if (buf) {
1488 ret = getpwuid_r(uid, &pwent, buf, bufsize, &pwentp);
1489 if (!pwentp) {
1490 if (ret == 0)
ea918412 1491 WARN("Could not find matched password record");
cb7aa5e8
DJ
1492
1493 WARN("Failed to get password record - %u", uid);
1494 }
1495 }
9c4693b8 1496
8ce83369
CB
1497 /* This probably happens because of incompatible nss implementations in
1498 * host and container (remember, this code is still using the host's
1499 * glibc but our mount namespace is in the container) we may try to get
1500 * the information by spawning a [getent passwd uid] process and parsing
1501 * the result.
9c4693b8 1502 */
cb7aa5e8 1503 if (!pwentp)
9c4693b8
CS
1504 user_shell = lxc_attach_getpwshell(uid);
1505 else
cb7aa5e8 1506 user_shell = pwent.pw_shell;
ea918412 1507
9c4693b8 1508 if (user_shell)
acf47e1b 1509 execlp(user_shell, user_shell, (char *)NULL);
9c4693b8 1510
8ce83369
CB
1511 /* Executed if either no passwd entry or execvp fails, we will fall back
1512 * on /bin/sh as a default shell.
9c4693b8 1513 */
acf47e1b 1514 execlp("/bin/sh", "/bin/sh", (char *)NULL);
ea918412 1515
edeb1836 1516 SYSERROR("Failed to execute shell");
cb7aa5e8 1517 if (!pwentp)
edeb1836 1518 free(user_shell);
ea918412 1519
9c4693b8
CS
1520 return -1;
1521}