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