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