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