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