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