]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/attach.c
coverity: #1425840
[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
DE
174 free(ctx);
175}
176
299d1198
CB
177/**
178 * in_same_namespace - Check whether two processes are in the same namespace.
179 * @pid1 - PID of the first process.
180 * @pid2 - PID of the second process.
181 * @ns - Name of the namespace to check. Must correspond to one of the names
182 * for the namespaces as shown in /proc/<pid/ns/
183 *
184 * If the two processes are not in the same namespace returns an fd to the
185 * namespace of the second process identified by @pid2. If the two processes are
186 * in the same namespace returns -EINVAL, -1 if an error occurred.
187 */
188static int in_same_namespace(pid_t pid1, pid_t pid2, const char *ns)
189{
190 int ns_fd1 = -1, ns_fd2 = -1, ret = -1;
191 struct stat ns_st1, ns_st2;
192
193 ns_fd1 = lxc_preserve_ns(pid1, ns);
134284c3
CB
194 if (ns_fd1 < 0) {
195 /* The kernel does not support this namespace. This is not an
196 * error.
197 */
198 if (errno == ENOENT)
199 return -EINVAL;
200
299d1198 201 goto out;
134284c3 202 }
299d1198
CB
203
204 ns_fd2 = lxc_preserve_ns(pid2, ns);
205 if (ns_fd2 < 0)
206 goto out;
207
208 ret = fstat(ns_fd1, &ns_st1);
209 if (ret < 0)
210 goto out;
211
212 ret = fstat(ns_fd2, &ns_st2);
213 if (ret < 0)
214 goto out;
215
216 /* processes are in the same namespace */
217 ret = -EINVAL;
218 if ((ns_st1.st_dev == ns_st2.st_dev ) && (ns_st1.st_ino == ns_st2.st_ino))
219 goto out;
220
221 /* processes are in different namespaces */
222 ret = ns_fd2;
223 ns_fd2 = -1;
224
225out:
226
227 if (ns_fd1 >= 0)
228 close(ns_fd1);
229 if (ns_fd2 >= 0)
230 close(ns_fd2);
231
232 return ret;
233}
234
877f3a04 235static int lxc_attach_to_ns(pid_t pid, struct lxc_proc_context_info *ctx)
99d50954 236{
877f3a04 237 int i, ret;
99d50954 238
26818618 239 for (i = 0; i < LXC_NS_MAX; i++) {
877f3a04 240 if (ctx->ns_fd[i] < 0)
26818618
CB
241 continue;
242
877f3a04
CB
243 ret = setns(ctx->ns_fd[i], ns_info[i].clone_flag);
244 if (ret < 0) {
299d1198
CB
245 SYSERROR("Failed to attach to %s namespace of %d",
246 ns_info[i].proc_name, pid);
99d50954
CS
247 return -1;
248 }
249
299d1198 250 DEBUG("Attached to %s namespace of %d", ns_info[i].proc_name, pid);
99d50954
CS
251 }
252
253 return 0;
254}
255
74a3920a 256static int lxc_attach_remount_sys_proc(void)
7a0b0b56
CS
257{
258 int ret;
259
260 ret = unshare(CLONE_NEWNS);
261 if (ret < 0) {
8ce83369 262 SYSERROR("Failed to unshare mount namespace.");
7a0b0b56
CS
263 return -1;
264 }
265
2c6f3fc9 266 if (detect_shared_rootfs()) {
6f4f1937 267 if (mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL)) {
8ce83369 268 SYSERROR("Failed to make / rslave.");
2c6f3fc9
SH
269 ERROR("Continuing...");
270 }
271 }
272
8ce83369 273 /* Assume /proc is always mounted, so remount it. */
7a0b0b56
CS
274 ret = umount2("/proc", MNT_DETACH);
275 if (ret < 0) {
8ce83369 276 SYSERROR("Failed to unmount /proc.");
7a0b0b56
CS
277 return -1;
278 }
279
280 ret = mount("none", "/proc", "proc", 0, NULL);
281 if (ret < 0) {
8ce83369 282 SYSERROR("Failed to remount /proc.");
7a0b0b56
CS
283 return -1;
284 }
285
8ce83369
CB
286 /* Try to umount /sys. If it's not a mount point, we'll get EINVAL, then
287 * we ignore it because it may not have been mounted in the first place.
7a0b0b56
CS
288 */
289 ret = umount2("/sys", MNT_DETACH);
290 if (ret < 0 && errno != EINVAL) {
8ce83369 291 SYSERROR("Failed to unmount /sys.");
7a0b0b56
CS
292 return -1;
293 } else if (ret == 0) {
8ce83369 294 /* Remount it. */
7a0b0b56
CS
295 ret = mount("none", "/sys", "sysfs", 0, NULL);
296 if (ret < 0) {
8ce83369 297 SYSERROR("Failed to remount /sys.");
7a0b0b56
CS
298 return -1;
299 }
300 }
301
302 return 0;
303}
304
74a3920a 305static int lxc_attach_drop_privs(struct lxc_proc_context_info *ctx)
e0732705 306{
6f4f1937 307 int cap, last_cap;
e0732705 308
6f4f1937 309 last_cap = lxc_caps_last_cap();
e0732705
CS
310 for (cap = 0; cap <= last_cap; cap++) {
311 if (ctx->capability_mask & (1LL << cap))
312 continue;
313
314 if (prctl(PR_CAPBSET_DROP, cap, 0, 0, 0)) {
94ac256f 315 SYSERROR("Failed to drop capability %d", cap);
e0732705
CS
316 return -1;
317 }
94ac256f 318 TRACE("Dropped capability %d", cap);
e0732705
CS
319 }
320
321 return 0;
322}
905022f7 323
7385273f 324static int lxc_attach_set_environment(struct lxc_proc_context_info *init_ctx,
325 enum lxc_attach_env_policy_t policy,
6f4f1937 326 char **extra_env, char **extra_keep)
b3a39ba6 327{
3d55242a 328 int ret;
7385273f 329 struct lxc_list *iterator;
330
799f96fd 331 if (policy == LXC_ATTACH_CLEAR_ENV) {
3d5e9f48 332 int path_kept = 0;
6f4f1937 333 char **extra_keep_store = NULL;
3d5e9f48
CS
334
335 if (extra_keep) {
336 size_t count, i;
337
3d55242a
CB
338 for (count = 0; extra_keep[count]; count++)
339 ;
3d5e9f48
CS
340
341 extra_keep_store = calloc(count, sizeof(char *));
3d55242a 342 if (!extra_keep_store)
3d5e9f48 343 return -1;
3d55242a 344
3d5e9f48
CS
345 for (i = 0; i < count; i++) {
346 char *v = getenv(extra_keep[i]);
347 if (v) {
348 extra_keep_store[i] = strdup(v);
349 if (!extra_keep_store[i]) {
3d5e9f48
CS
350 while (i > 0)
351 free(extra_keep_store[--i]);
352 free(extra_keep_store);
353 return -1;
354 }
3d55242a 355
3d5e9f48
CS
356 if (strcmp(extra_keep[i], "PATH") == 0)
357 path_kept = 1;
358 }
3d5e9f48
CS
359 }
360 }
361
799f96fd 362 if (clearenv()) {
a9cab7e3 363 if (extra_keep_store) {
3d55242a
CB
364 char **p;
365
a9cab7e3
CS
366 for (p = extra_keep_store; *p; p++)
367 free(*p);
3d55242a 368
a9cab7e3
CS
369 free(extra_keep_store);
370 }
3d55242a
CB
371
372 SYSERROR("Failed to clear environment");
3d5e9f48
CS
373 return -1;
374 }
375
376 if (extra_keep_store) {
377 size_t i;
6f4f1937 378
3d5e9f48 379 for (i = 0; extra_keep[i]; i++) {
acd4922e 380 if (extra_keep_store[i]) {
3d55242a
CB
381 ret = setenv(extra_keep[i], extra_keep_store[i], 1);
382 if (ret < 0)
383 WARN("%s - Failed to set environment variable", strerror(errno));
acd4922e 384 }
3d5e9f48
CS
385 free(extra_keep_store[i]);
386 }
387 free(extra_keep_store);
388 }
389
8ce83369
CB
390 /* Always set a default path; shells and execlp tend to be fine
391 * without it, but there is a disturbing number of C programs
392 * out there that just assume that getenv("PATH") is never NULL
393 * and then die a painful segfault death.
394 */
3d55242a
CB
395 if (!path_kept) {
396 ret = setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
397 if (ret < 0)
398 WARN("%s - Failed to set environment variable", strerror(errno));
399 }
b3a39ba6
DW
400 }
401
3d55242a
CB
402 ret = putenv("container=lxc");
403 if (ret < 0) {
404 WARN("%s - Failed to set environment variable", strerror(errno));
b3a39ba6
DW
405 return -1;
406 }
407
7385273f 408 /* Set container environment variables.*/
409 if (init_ctx && init_ctx->container && init_ctx->container->lxc_conf) {
410 lxc_list_for_each(iterator, &init_ctx->container->lxc_conf->environment) {
3d55242a
CB
411 char *env_tmp;
412
413 env_tmp = strdup((char *)iterator->elem);
414 if (!env_tmp)
7385273f 415 return -1;
7385273f 416
3d55242a
CB
417 ret = putenv(env_tmp);
418 if (ret < 0) {
419 SYSERROR("Failed to set environment variable: %s", (char *)iterator->elem);
7385273f 420 return -1;
421 }
422 }
423 }
424
8ce83369 425 /* Set extra environment variables. */
3d5e9f48
CS
426 if (extra_env) {
427 for (; *extra_env; extra_env++) {
3d55242a 428 char *p;
8ce83369
CB
429 /* We just assume the user knows what they are doing, so
430 * we don't do any checks.
431 */
3d55242a
CB
432 p = strdup(*extra_env);
433 if (!p)
3d5e9f48 434 return -1;
3d55242a
CB
435
436 ret = putenv(p);
437 if (ret < 0)
438 WARN("%s - Failed to set environment variable", strerror(errno));
3d5e9f48
CS
439 }
440 }
441
b3a39ba6
DW
442 return 0;
443}
444
74a3920a 445static char *lxc_attach_getpwshell(uid_t uid)
905022f7 446{
6f4f1937 447 int fd, ret;
905022f7
CS
448 pid_t pid;
449 int pipes[2];
905022f7
CS
450 char *result = NULL;
451
8ce83369
CB
452 /* We need to fork off a process that runs the getent program, and we
453 * need to capture its output, so we use a pipe for that purpose.
905022f7
CS
454 */
455 ret = pipe(pipes);
456 if (ret < 0)
457 return NULL;
458
459 pid = fork();
460 if (pid < 0) {
461 close(pipes[0]);
462 close(pipes[1]);
463 return NULL;
464 }
465
466 if (pid) {
6f4f1937 467 int status;
905022f7 468 FILE *pipe_f;
905022f7 469 int found = 0;
6f4f1937
CB
470 size_t line_bufsz = 0;
471 char *line = NULL;
905022f7
CS
472
473 close(pipes[1]);
474
475 pipe_f = fdopen(pipes[0], "r");
476 while (getline(&line, &line_bufsz, pipe_f) != -1) {
905022f7 477 int i;
6f4f1937
CB
478 long value;
479 char *token;
480 char *endptr = NULL, *saveptr = NULL;
905022f7 481
8ce83369
CB
482 /* If we already found something, just continue to read
483 * until the pipe doesn't deliver any more data, but
484 * don't modify the existing data structure.
905022f7
CS
485 */
486 if (found)
487 continue;
488
8ce83369 489 /* Trim line on the right hand side. */
bbb8a488 490 for (i = strlen(line); i > 0 && (line[i - 1] == '\n' || line[i - 1] == '\r'); --i)
905022f7
CS
491 line[i - 1] = '\0';
492
8ce83369 493 /* Split into tokens: first: user name. */
905022f7
CS
494 token = strtok_r(line, ":", &saveptr);
495 if (!token)
496 continue;
497 /* next: dummy password field */
498 token = strtok_r(NULL, ":", &saveptr);
499 if (!token)
500 continue;
501 /* next: user id */
502 token = strtok_r(NULL, ":", &saveptr);
503 value = token ? strtol(token, &endptr, 10) : 0;
504 if (!token || !endptr || *endptr || value == LONG_MIN || value == LONG_MAX)
505 continue;
506 /* dummy sanity check: user id matches */
507 if ((uid_t) value != uid)
508 continue;
509 /* skip fields: gid, gecos, dir, go to next field 'shell' */
510 for (i = 0; i < 4; i++) {
511 token = strtok_r(NULL, ":", &saveptr);
512 if (!token)
513 break;
514 }
515 if (!token)
516 continue;
f10fad2f 517 free(result);
905022f7
CS
518 result = strdup(token);
519
8ce83369 520 /* Sanity check that there are no fields after that. */
905022f7
CS
521 token = strtok_r(NULL, ":", &saveptr);
522 if (token)
523 continue;
524
525 found = 1;
526 }
527
528 free(line);
529 fclose(pipe_f);
530 again:
531 if (waitpid(pid, &status, 0) < 0) {
532 if (errno == EINTR)
533 goto again;
f4e1fa60 534 free(result);
905022f7
CS
535 return NULL;
536 }
537
8ce83369
CB
538 /* Some sanity checks. If anything even hinted at going wrong,
539 * we can't be sure we have a valid result, so we assume we
540 * don't.
905022f7
CS
541 */
542
f4e1fa60
CB
543 if (!WIFEXITED(status)) {
544 free(result);
905022f7 545 return NULL;
f4e1fa60 546 }
905022f7 547
f4e1fa60
CB
548 if (WEXITSTATUS(status) != 0) {
549 free(result);
905022f7 550 return NULL;
f4e1fa60 551 }
905022f7 552
f4e1fa60
CB
553 if (!found) {
554 free(result);
905022f7 555 return NULL;
f4e1fa60 556 }
905022f7
CS
557
558 return result;
559 } else {
905022f7
CS
560 char uid_buf[32];
561 char *arguments[] = {
562 "getent",
563 "passwd",
564 uid_buf,
565 NULL
566 };
567
568 close(pipes[0]);
569
8ce83369 570 /* We want to capture stdout. */
905022f7
CS
571 dup2(pipes[1], 1);
572 close(pipes[1]);
573
8ce83369
CB
574 /* Get rid of stdin/stderr, so we try to associate it with
575 * /dev/null.
905022f7
CS
576 */
577 fd = open("/dev/null", O_RDWR);
578 if (fd < 0) {
579 close(0);
580 close(2);
581 } else {
582 dup2(fd, 0);
583 dup2(fd, 2);
584 close(fd);
585 }
586
8ce83369 587 /* Finish argument list. */
905022f7
CS
588 ret = snprintf(uid_buf, sizeof(uid_buf), "%ld", (long) uid);
589 if (ret <= 0)
590 exit(-1);
591
8ce83369 592 /* Try to run getent program. */
905022f7
CS
593 (void) execvp("getent", arguments);
594 exit(-1);
595 }
596}
cb3e61fa 597
6f4f1937 598static void lxc_attach_get_init_uidgid(uid_t *init_uid, gid_t *init_gid)
cb3e61fa
CS
599{
600 FILE *proc_file;
8ce83369
CB
601 char proc_fn[__PROC_STATUS_LEN];
602 int ret;
cb3e61fa
CS
603 char *line = NULL;
604 size_t line_bufsz = 0;
cb3e61fa
CS
605 long value = -1;
606 uid_t uid = (uid_t)-1;
607 gid_t gid = (gid_t)-1;
608
8ce83369
CB
609 /* Read capabilities. */
610 snprintf(proc_fn, __PROC_STATUS_LEN, "/proc/%d/status", 1);
cb3e61fa
CS
611
612 proc_file = fopen(proc_fn, "r");
613 if (!proc_file)
614 return;
615
616 while (getline(&line, &line_bufsz, proc_file) != -1) {
8ce83369
CB
617 /* Format is: real, effective, saved set user, fs we only care
618 * about real uid.
cb3e61fa
CS
619 */
620 ret = sscanf(line, "Uid: %ld", &value);
8ce83369 621 if (ret != EOF && ret == 1) {
6f4f1937 622 uid = (uid_t)value;
cb3e61fa
CS
623 } else {
624 ret = sscanf(line, "Gid: %ld", &value);
8ce83369 625 if (ret != EOF && ret == 1)
6f4f1937 626 gid = (gid_t)value;
cb3e61fa
CS
627 }
628 if (uid != (uid_t)-1 && gid != (gid_t)-1)
629 break;
630 }
631
632 fclose(proc_file);
633 free(line);
634
8ce83369 635 /* Only override arguments if we found something. */
cb3e61fa
CS
636 if (uid != (uid_t)-1)
637 *init_uid = uid;
638 if (gid != (gid_t)-1)
639 *init_gid = gid;
640
641 /* TODO: we should also parse supplementary groups and use
8ce83369
CB
642 * setgroups() to set them.
643 */
cb3e61fa 644}
9c4693b8 645
8ce83369 646/* Help the optimizer along if it doesn't know that exit always exits. */
6f4f1937
CB
647#define rexit(c) \
648 do { \
649 int __c = (c); \
650 _exit(__c); \
651 return __c; \
652 } while (0)
9c4693b8 653
8ce83369 654/* Define default options if no options are supplied by the user. */
9c4693b8
CS
655static lxc_attach_options_t attach_static_default_options = LXC_ATTACH_OPTIONS_DEFAULT;
656
bd4307f0 657static bool fetch_seccomp(struct lxc_container *c,
ff07d7bb 658 lxc_attach_options_t *options)
2c4ea790 659{
bd7b4e28 660 char *path;
2eef2bda 661
6f4f1937
CB
662 if (!(options->namespaces & CLONE_NEWNS) ||
663 !(options->attach_flags & LXC_ATTACH_LSM)) {
bd4307f0
CB
664 free(c->lxc_conf->seccomp);
665 c->lxc_conf->seccomp = NULL;
2c4ea790 666 return true;
bd4307f0 667 }
bd7b4e28 668
2e812c16 669 /* Remove current setting. */
0b427da0
CB
670 if (!c->set_config_item(c, "lxc.seccomp", "") &&
671 !c->set_config_item(c, "lxc.seccomp.profile", "")) {
2c4ea790 672 return false;
bd7b4e28
SG
673 }
674
8ce83369 675 /* Fetch the current profile path over the cmd interface. */
0b427da0 676 path = c->get_running_config_item(c, "lxc.seccomp.profile");
bd7b4e28 677 if (!path) {
0b427da0
CB
678 INFO("Failed to get running config item for lxc.seccomp.profile");
679 path = c->get_running_config_item(c, "lxc.seccomp");
680 }
681 if (!path) {
682 INFO("Failed to get running config item for lxc.seccomp");
bd7b4e28
SG
683 return true;
684 }
685
8ce83369 686 /* Copy the value into the new lxc_conf. */
0b427da0 687 if (!c->set_config_item(c, "lxc.seccomp.profile", path)) {
bd7b4e28
SG
688 free(path);
689 return false;
690 }
691 free(path);
692
8ce83369 693 /* Attempt to parse the resulting config. */
2c4ea790 694 if (lxc_read_seccomp_config(c->lxc_conf) < 0) {
8ce83369 695 ERROR("Error reading seccomp policy.");
2c4ea790
SH
696 return false;
697 }
698
2e812c16
CB
699 INFO("Retrieved seccomp policy.");
700 return true;
701}
702
6f4f1937 703static bool no_new_privs(struct lxc_container *c, lxc_attach_options_t *options)
2e812c16 704{
2e812c16
CB
705 char *val;
706
2e812c16 707 /* Remove current setting. */
6f4f1937 708 if (!c->set_config_item(c, "lxc.no_new_privs", ""))
2e812c16 709 return false;
2e812c16
CB
710
711 /* Retrieve currently active setting. */
712 val = c->get_running_config_item(c, "lxc.no_new_privs");
713 if (!val) {
714 INFO("Failed to get running config item for lxc.no_new_privs.");
715 return false;
716 }
717
718 /* Set currently active setting. */
719 if (!c->set_config_item(c, "lxc.no_new_privs", val)) {
720 free(val);
721 return false;
722 }
723 free(val);
724
2c4ea790
SH
725 return true;
726}
727
9b8e3c96
SH
728static signed long get_personality(const char *name, const char *lxcpath)
729{
6f4f1937 730 char *p;
9b8e3c96
SH
731 signed long ret;
732
6f4f1937 733 p = lxc_cmd_get_config_item(name, "lxc.arch", lxcpath);
9b8e3c96
SH
734 if (!p)
735 return -1;
6f4f1937 736
9b8e3c96
SH
737 ret = lxc_config_parse_arch(p);
738 free(p);
6f4f1937 739
9b8e3c96
SH
740 return ret;
741}
742
a998454a
CB
743struct attach_clone_payload {
744 int ipc_socket;
9e84479f 745 int terminal_slave_fd;
a998454a
CB
746 lxc_attach_options_t *options;
747 struct lxc_proc_context_info *init_ctx;
748 lxc_attach_exec_t exec_function;
749 void *exec_payload;
750};
751
ba2be1a8
CB
752static void lxc_put_attach_clone_payload(struct attach_clone_payload *p)
753{
754 if (p->ipc_socket >= 0) {
755 shutdown(p->ipc_socket, SHUT_RDWR);
756 close(p->ipc_socket);
757 p->ipc_socket = -EBADF;
758 }
759
9e84479f
CB
760 if (p->terminal_slave_fd >= 0) {
761 close(p->terminal_slave_fd);
762 p->terminal_slave_fd = -EBADF;
ba2be1a8
CB
763 }
764
b21da190 765 if (p->init_ctx) {
ba2be1a8 766 lxc_proc_put_context_info(p->init_ctx);
b21da190
CB
767 p->init_ctx = NULL;
768 }
ba2be1a8
CB
769}
770
a998454a
CB
771static int attach_child_main(struct attach_clone_payload *payload)
772{
57de839f 773 int fd, lsm_fd, ret;
a998454a
CB
774 uid_t new_uid;
775 gid_t new_gid;
a998454a
CB
776 lxc_attach_options_t* options = payload->options;
777 struct lxc_proc_context_info* init_ctx = payload->init_ctx;
57de839f
CB
778 bool needs_lsm = (options->namespaces & CLONE_NEWNS) &&
779 (options->attach_flags & LXC_ATTACH_LSM) &&
780 init_ctx->lsm_label;
a998454a
CB
781
782 /* A description of the purpose of this functionality is provided in the
783 * lxc-attach(1) manual page. We have to remount here and not in the
784 * parent process, otherwise /proc may not properly reflect the new pid
785 * namespace.
786 */
787 if (!(options->namespaces & CLONE_NEWNS) &&
788 (options->attach_flags & LXC_ATTACH_REMOUNT_PROC_SYS)) {
789 ret = lxc_attach_remount_sys_proc();
b75c344c
CB
790 if (ret < 0)
791 goto on_error;
792 TRACE("Remounted \"/proc\" and \"/sys\"");
a998454a
CB
793 }
794
b75c344c 795/* Now perform additional attachments. */
a998454a 796#if HAVE_SYS_PERSONALITY_H
a998454a 797 if (options->attach_flags & LXC_ATTACH_SET_PERSONALITY) {
b75c344c
CB
798 long new_personality;
799
800 if (options->personality < 0)
801 new_personality = init_ctx->personality;
802 else
803 new_personality = options->personality;
a998454a 804 ret = personality(new_personality);
b75c344c
CB
805 if (ret < 0)
806 goto on_error;
807 TRACE("Set new personality");
a998454a
CB
808 }
809#endif
810
811 if (options->attach_flags & LXC_ATTACH_DROP_CAPABILITIES) {
812 ret = lxc_attach_drop_privs(init_ctx);
b75c344c
CB
813 if (ret < 0)
814 goto on_error;
815 TRACE("Dropped capabilities");
a998454a
CB
816 }
817
818 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
819 * if you want this to be a no-op).
820 */
7385273f 821 ret = lxc_attach_set_environment(init_ctx,
822 options->env_policy,
a998454a
CB
823 options->extra_env_vars,
824 options->extra_keep_env);
b75c344c
CB
825 if (ret < 0)
826 goto on_error;
827 TRACE("Set up environment");
a998454a 828
57de839f
CB
829 /* This remark only affects fully unprivileged containers:
830 * Receive fd for LSM security module before we set{g,u}id(). The reason
831 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
832 * we will change our effective uid. This means our effective uid will
833 * be different from the effective uid of the process that created us
834 * which means that this processs no longer has capabilities in our
835 * namespace including CAP_SYS_PTRACE. This means we will not be able to
836 * read and /proc/<pid> files for the process anymore when /proc is
837 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
838 * set{g,u}id().
839 */
840 if (needs_lsm) {
b75c344c
CB
841 ret = lxc_abstract_unix_recv_fds(payload->ipc_socket, &lsm_fd, 1, NULL, 0);
842 if (ret <= 0)
843 goto on_error;
57de839f
CB
844 TRACE("Received LSM label file descriptor %d from parent", lsm_fd);
845 }
846
08ea9270 847 if (options->stdin_fd > 0 && isatty(options->stdin_fd)) {
cd0a2b2f 848 ret = lxc_make_controlling_terminal(options->stdin_fd);
08ea9270
CB
849 if (ret < 0)
850 goto on_error;
851 }
852
a998454a
CB
853 /* Set {u,g}id. */
854 new_uid = 0;
855 new_gid = 0;
856 /* Ignore errors, we will fall back to root in that case (/proc was not
857 * mounted etc.).
858 */
859 if (options->namespaces & CLONE_NEWUSER)
860 lxc_attach_get_init_uidgid(&new_uid, &new_gid);
861
862 if (options->uid != (uid_t)-1)
863 new_uid = options->uid;
864 if (options->gid != (gid_t)-1)
865 new_gid = options->gid;
866
a998454a 867 /* Try to set the {u,g}id combination. */
b75c344c
CB
868 if (new_uid != 0 || new_gid != 0 || options->namespaces & CLONE_NEWUSER) {
869 ret = lxc_switch_uid_gid(new_uid, new_gid);
870 if (ret < 0)
871 goto on_error;
a998454a
CB
872 }
873
d26615b6 874 ret = lxc_setgroups(0, NULL);
315350e3 875 if (ret < 0 && errno != EPERM)
d26615b6
CB
876 goto on_error;
877
a998454a
CB
878 if ((init_ctx->container && init_ctx->container->lxc_conf &&
879 init_ctx->container->lxc_conf->no_new_privs) ||
880 (options->attach_flags & LXC_ATTACH_NO_NEW_PRIVS)) {
b75c344c
CB
881 ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
882 if (ret < 0)
883 goto on_error;
884 TRACE("Set PR_SET_NO_NEW_PRIVS");
a998454a
CB
885 }
886
57de839f 887 if (needs_lsm) {
d3ba7c98 888 bool on_exec;
a998454a
CB
889
890 /* Change into our new LSM profile. */
d3ba7c98
CB
891 on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? true : false;
892 ret = lsm_process_label_set_at(lsm_fd, init_ctx->lsm_label, on_exec);
57de839f 893 close(lsm_fd);
b75c344c
CB
894 if (ret < 0)
895 goto on_error;
d3ba7c98 896 TRACE("Set %s LSM label to \"%s\"", lsm_name(), init_ctx->lsm_label);
a998454a
CB
897 }
898
899 if (init_ctx->container && init_ctx->container->lxc_conf &&
b75c344c
CB
900 init_ctx->container->lxc_conf->seccomp) {
901 ret = lxc_seccomp_load(init_ctx->container->lxc_conf);
902 if (ret < 0)
903 goto on_error;
904 TRACE("Loaded seccomp profile");
a998454a 905 }
b75c344c
CB
906 shutdown(payload->ipc_socket, SHUT_RDWR);
907 close(payload->ipc_socket);
ba2be1a8
CB
908 payload->ipc_socket = -EBADF;
909 lxc_proc_put_context_info(init_ctx);
8ae2c3cc 910 payload->init_ctx = NULL;
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) {
893b660c
CB
1275 struct cgroup_ops *cgroup_ops;
1276
1277 cgroup_ops = cgroup_init(NULL);
1278 if (!cgroup_ops)
1279 goto on_error;
1280
1281 if (!cgroup_ops->attach(cgroup_ops, name, lxcpath, pid))
8ce83369 1282 goto on_error;
893b660c
CB
1283
1284 cgroup_exit(cgroup_ops);
1285 TRACE("Moved intermediate process %d into container's cgroups", pid);
f4364484
SG
1286 }
1287
bb2ada6f 1288 /* Setup /proc limits */
1cce35e6
CB
1289 if (!lxc_list_empty(&conf->procs)) {
1290 ret = setup_proc_filesystem(&conf->procs, pid);
bb2ada6f
CB
1291 if (ret < 0)
1292 goto on_error;
1293 }
1294
c6d09e15 1295 /* Setup resource limits */
1cce35e6
CB
1296 if (!lxc_list_empty(&conf->limits)) {
1297 ret = setup_resource_limits(&conf->limits, pid);
ba2be1a8
CB
1298 if (ret < 0)
1299 goto on_error;
1300 }
1301
9e84479f
CB
1302 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1303 ret = lxc_attach_terminal_mainloop_init(&terminal, &descr);
ba2be1a8 1304 if (ret < 0)
6f4f1937 1305 goto on_error;
9e84479f 1306 TRACE("Initialized terminal mainloop");
ba2be1a8 1307 }
c6d09e15 1308
8ce83369 1309 /* Let the child process know to go ahead. */
f4364484
SG
1310 status = 0;
1311 ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status));
94ac256f 1312 if (ret != sizeof(status))
ba2be1a8 1313 goto close_mainloop;
94ac256f 1314 TRACE("Told intermediate process to start initializing");
f4364484 1315
8ce83369 1316 /* Get pid of attached process from intermediate process. */
94ac256f
CB
1317 ret = lxc_read_nointr(ipc_sockets[0], &attached_pid, sizeof(attached_pid));
1318 if (ret != sizeof(attached_pid))
ba2be1a8 1319 goto close_mainloop;
94ac256f 1320 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid);
9c4693b8 1321
8ce83369 1322 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
62183f1a
SH
1323 if (options->stdin_fd == 0) {
1324 signal(SIGINT, SIG_IGN);
1325 signal(SIGQUIT, SIG_IGN);
1326 }
2eef2bda 1327
8ce83369 1328 /* Reap intermediate process. */
9c4693b8
CS
1329 ret = wait_for_pid(pid);
1330 if (ret < 0)
ba2be1a8 1331 goto close_mainloop;
94ac256f 1332 TRACE("Intermediate process %d exited", pid);
9c4693b8 1333
8ce83369 1334 /* We will always have to reap the attached process now. */
9c4693b8
CS
1335 to_cleanup_pid = attached_pid;
1336
81f466d0 1337 /* Open LSM fd and send it to child. */
6f4f1937
CB
1338 if ((options->namespaces & CLONE_NEWNS) &&
1339 (options->attach_flags & LXC_ATTACH_LSM) &&
1340 init_ctx->lsm_label) {
94ac256f 1341 int ret = -1;
47ce2cb7
CB
1342 int labelfd;
1343 bool on_exec;
6f4f1937 1344
47ce2cb7
CB
1345 on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? true : false;
1346 labelfd = lsm_process_label_fd_get(attached_pid, on_exec);
81f466d0 1347 if (labelfd < 0)
ba2be1a8 1348 goto close_mainloop;
94ac256f 1349 TRACE("Opened LSM label file descriptor %d", labelfd);
81f466d0
CB
1350
1351 /* Send child fd of the LSM security module to write to. */
ae467c54 1352 ret = lxc_abstract_unix_send_fds(ipc_sockets[0], &labelfd, 1, NULL, 0);
1d8e5ca2 1353 close(labelfd);
81f466d0 1354 if (ret <= 0) {
94ac256f 1355 SYSERROR("%d", (int)ret);
ba2be1a8 1356 goto close_mainloop;
81f466d0 1357 }
94ac256f 1358 TRACE("Sent LSM label file descriptor %d to child", labelfd);
81f466d0
CB
1359 }
1360
8ce83369
CB
1361 /* We're done, the child process should now execute whatever it
1362 * is that the user requested. The parent can now track it with
1363 * waitpid() or similar.
9c4693b8
CS
1364 */
1365
1366 *attached_process = attached_pid;
9c4693b8 1367
ba2be1a8 1368 /* Now shut down communication with child, we're done. */
9c4693b8
CS
1369 shutdown(ipc_sockets[0], SHUT_RDWR);
1370 close(ipc_sockets[0]);
ba2be1a8
CB
1371 ipc_sockets[0] = -1;
1372
1373 ret_parent = 0;
1374 to_cleanup_pid = -1;
9e84479f 1375 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
ba2be1a8
CB
1376 ret = lxc_mainloop(&descr, -1);
1377 if (ret < 0) {
1378 ret_parent = -1;
1379 to_cleanup_pid = attached_pid;
1380 }
1381 }
1382
1383 close_mainloop:
9e84479f 1384 if (options->attach_flags & LXC_ATTACH_TERMINAL)
ba2be1a8
CB
1385 lxc_mainloop_close(&descr);
1386
1387 on_error:
1388 if (ipc_sockets[0] >= 0) {
1389 shutdown(ipc_sockets[0], SHUT_RDWR);
1390 close(ipc_sockets[0]);
1391 }
1392
1393 if (to_cleanup_pid > 0)
6f4f1937 1394 (void)wait_for_pid(to_cleanup_pid);
ba2be1a8 1395
9e84479f
CB
1396 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1397 lxc_terminal_delete(&terminal);
1398 lxc_terminal_conf_free(&terminal);
ba2be1a8 1399 }
fe4de9a6 1400 lxc_proc_put_context_info(init_ctx);
ba2be1a8 1401 return ret_parent;
9c4693b8
CS
1402 }
1403
ba2be1a8 1404 /* close unneeded file descriptors */
9c4693b8 1405 close(ipc_sockets[0]);
ba2be1a8 1406 ipc_sockets[0] = -EBADF;
9e84479f
CB
1407 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1408 lxc_attach_terminal_close_master(&terminal);
1409 lxc_attach_terminal_close_peer(&terminal);
1410 lxc_attach_terminal_close_log(&terminal);
ba2be1a8 1411 }
9c4693b8 1412
8ce83369 1413 /* Wait for the parent to have setup cgroups. */
94ac256f 1414 ret = lxc_read_nointr(ipc_sockets[1], &status, sizeof(status));
ba2be1a8 1415 if (ret != sizeof(status)) {
f4364484 1416 shutdown(ipc_sockets[1], SHUT_RDWR);
62de1db6 1417 lxc_proc_put_context_info(init_ctx);
f4364484
SG
1418 rexit(-1);
1419 }
94ac256f 1420 TRACE("Intermediate process starting to initialize");
f4364484 1421
8ce83369
CB
1422 /* Attach now, create another subprocess later, since pid namespaces
1423 * only really affect the children of the current process.
9c4693b8 1424 */
877f3a04 1425 ret = lxc_attach_to_ns(init_pid, init_ctx);
9c4693b8 1426 if (ret < 0) {
94ac256f 1427 ERROR("Failed to enter namespaces");
9c4693b8 1428 shutdown(ipc_sockets[1], SHUT_RDWR);
62de1db6 1429 lxc_proc_put_context_info(init_ctx);
9c4693b8
CS
1430 rexit(-1);
1431 }
877f3a04
CB
1432 /* close namespace file descriptors */
1433 lxc_proc_close_ns_fd(init_ctx);
9c4693b8 1434
8ce83369 1435 /* Attach succeeded, try to cwd. */
9c4693b8
CS
1436 if (options->initial_cwd)
1437 new_cwd = options->initial_cwd;
1438 else
1439 new_cwd = cwd;
d6d979bc
CB
1440 if (new_cwd) {
1441 ret = chdir(new_cwd);
1442 if (ret < 0)
1443 WARN("Could not change directory to \"%s\"", new_cwd);
1444 }
9c4693b8
CS
1445 free(cwd);
1446
a998454a
CB
1447 /* Create attached process. */
1448 payload.ipc_socket = ipc_sockets[1];
1449 payload.options = options;
1450 payload.init_ctx = init_ctx;
9e84479f 1451 payload.terminal_slave_fd = terminal.slave;
a998454a
CB
1452 payload.exec_function = exec_function;
1453 payload.exec_payload = exec_payload;
9c4693b8 1454
a998454a
CB
1455 pid = lxc_raw_clone(CLONE_PARENT);
1456 if (pid < 0) {
94ac256f 1457 SYSERROR("Failed to clone attached process");
9c4693b8 1458 shutdown(ipc_sockets[1], SHUT_RDWR);
62de1db6 1459 lxc_proc_put_context_info(init_ctx);
9c4693b8
CS
1460 rexit(-1);
1461 }
a998454a
CB
1462
1463 if (pid == 0) {
1464 ret = attach_child_main(&payload);
1465 if (ret < 0)
1466 ERROR("Failed to exec");
1467 _exit(EXIT_FAILURE);
1468 }
9e84479f
CB
1469 if (options->attach_flags & LXC_ATTACH_TERMINAL)
1470 lxc_attach_terminal_close_slave(&terminal);
9c4693b8 1471
8ce83369 1472 /* Tell grandparent the pid of the pid of the newly created child. */
9c4693b8
CS
1473 ret = lxc_write_nointr(ipc_sockets[1], &pid, sizeof(pid));
1474 if (ret != sizeof(pid)) {
8ce83369
CB
1475 /* If this really happens here, this is very unfortunate, since
1476 * the parent will not know the pid of the attached process and
1477 * will not be able to wait for it (and we won't either due to
1478 * CLONE_PARENT) so the parent won't be able to reap it and the
1479 * attached process will remain a zombie.
9c4693b8 1480 */
9c4693b8 1481 shutdown(ipc_sockets[1], SHUT_RDWR);
62de1db6 1482 lxc_proc_put_context_info(init_ctx);
9c4693b8
CS
1483 rexit(-1);
1484 }
94ac256f 1485 TRACE("Sending pid %d of attached process", pid);
9c4693b8 1486
8ce83369 1487 /* The rest is in the hands of the initial and the attached process. */
62de1db6 1488 lxc_proc_put_context_info(init_ctx);
9c4693b8
CS
1489 rexit(0);
1490}
1491
9c4693b8
CS
1492int lxc_attach_run_command(void* payload)
1493{
1494 lxc_attach_command_t* cmd = (lxc_attach_command_t*)payload;
1495
1496 execvp(cmd->program, cmd->argv);
8ce83369 1497 SYSERROR("Failed to exec \"%s\".", cmd->program);
9c4693b8
CS
1498 return -1;
1499}
1500
1501int lxc_attach_run_shell(void* payload)
1502{
1503 uid_t uid;
ef6ed2a5
DJ
1504 struct passwd pwent;
1505 struct passwd *pwentp = NULL;
9c4693b8 1506 char *user_shell;
ef6ed2a5
DJ
1507 char *buf;
1508 size_t bufsize;
1509 int ret;
9c4693b8 1510
8ce83369 1511 /* Ignore payload parameter. */
9c4693b8
CS
1512 (void)payload;
1513
1514 uid = getuid();
ef6ed2a5
DJ
1515
1516 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1517 if (bufsize == -1)
1518 bufsize = 1024;
1519
1520 buf = malloc(bufsize);
1521 if (buf) {
1522 ret = getpwuid_r(uid, &pwent, buf, bufsize, &pwentp);
1523 if (!pwentp) {
1524 if (ret == 0)
1525 WARN("Could not find matched password record.");
1526
1527 WARN("Failed to get password record - %u", uid);
1528 }
1529 }
9c4693b8 1530
8ce83369
CB
1531 /* This probably happens because of incompatible nss implementations in
1532 * host and container (remember, this code is still using the host's
1533 * glibc but our mount namespace is in the container) we may try to get
1534 * the information by spawning a [getent passwd uid] process and parsing
1535 * the result.
9c4693b8 1536 */
ef6ed2a5 1537 if (!pwentp)
9c4693b8
CS
1538 user_shell = lxc_attach_getpwshell(uid);
1539 else
ef6ed2a5 1540 user_shell = pwent.pw_shell;
9c4693b8 1541 if (user_shell)
acf47e1b 1542 execlp(user_shell, user_shell, (char *)NULL);
9c4693b8 1543
8ce83369
CB
1544 /* Executed if either no passwd entry or execvp fails, we will fall back
1545 * on /bin/sh as a default shell.
9c4693b8 1546 */
acf47e1b 1547 execlp("/bin/sh", "/bin/sh", (char *)NULL);
edeb1836 1548 SYSERROR("Failed to execute shell");
ef6ed2a5 1549 if (!pwentp)
edeb1836 1550 free(user_shell);
ef6ed2a5 1551 free(buf);
9c4693b8
CS
1552 return -1;
1553}