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