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