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