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