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