]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/attach.c
Merge pull request #3666 from brauner/2021-02-11/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"
657256e0 42#include "mount_utils.h"
6f4f1937 43#include "namespace.h"
f40988c7 44#include "process_utils.h"
a9f0cecf 45#include "sync.h"
59524108 46#include "syscall_wrappers.h"
0ed9b1bc 47#include "terminal.h"
6f4f1937 48#include "utils.h"
9c4693b8
CS
49
50#if HAVE_SYS_PERSONALITY_H
51#include <sys/personality.h>
52#endif
e0732705 53
ac2cecc4 54lxc_log_define(attach, lxc);
e0732705 55
ef05d368
CB
56/* Define default options if no options are supplied by the user. */
57static lxc_attach_options_t attach_static_default_options = LXC_ATTACH_OPTIONS_DEFAULT;
58
20718e39
CB
59/*
60 * The context used to attach to the container.
3ac4480a
CB
61 * @attach_flags : the attach flags specified in lxc_attach_options_t
62 * @init_pid : the PID of the container's init process
63 * @dfd_init_pid : file descriptor to /proc/@init_pid
64 * __Must be closed in attach_context_security_barrier()__!
65 * @dfd_self_pid : file descriptor to /proc/self
66 * __Must be closed in attach_context_security_barrier()__!
67 * @setup_ns_uid : if CLONE_NEWUSER is specified will contain the uid used
68 * during attach setup.
69 * @setup_ns_gid : if CLONE_NEWUSER is specified will contain the gid used
70 * during attach setup.
71 * @target_ns_uid : if CLONE_NEWUSER is specified the uid that the final
72 * program will be run with.
73 * @target_ns_gid : if CLONE_NEWUSER is specified the gid that the final
74 * program will be run with.
75 * @target_host_uid : if CLONE_NEWUSER is specified the uid that the final
76 * program will be run with on the host.
77 * @target_host_gid : if CLONE_NEWUSER is specified the gid that the final
78 * program will be run with on the host.
79 * @lsm_label : LSM label to be used for the attaching process
80 * @container : the container we're attaching o
81 * @personality : the personality to use for the final program
82 * @capability : the capability mask of the @init_pid
83 * @ns_inherited : flags of namespaces that the final program will inherit
84 * from @init_pid
85 * @ns_fd : file descriptors to @init_pid's namespaces
20718e39 86 */
ab919e5f 87struct attach_context {
afc691a0 88 unsigned int attach_flags;
500ed813 89 int init_pid;
9b31ab58 90 int init_pidfd;
25c659d5
CB
91 int dfd_init_pid;
92 int dfd_self_pid;
3ac4480a
CB
93 uid_t setup_ns_uid;
94 gid_t setup_ns_gid;
95 uid_t target_ns_uid;
96 gid_t target_ns_gid;
97 uid_t target_host_uid;
98 uid_t target_host_gid;
0e304baa
CB
99 char *lsm_label;
100 struct lxc_container *container;
101 signed long personality;
102 unsigned long long capability_mask;
103 int ns_inherited;
104 int ns_fd[LXC_NS_MAX];
105 struct lsm_ops *lsm_ops;
106};
107
6f0c2cea 108static pid_t pidfd_get_pid(int dfd_init_pid, int pidfd)
d8764025
CB
109{
110 __do_free char *line = NULL;
111 __do_fclose FILE *f = NULL;
112 size_t len = 0;
6f0c2cea 113 char path[STRLITERALLEN("fdinfo/") + INTTYPE_TO_STRLEN(int) + 1 ] = "fdinfo/";
d8764025
CB
114 int ret;
115
6f0c2cea
CB
116 if (dfd_init_pid < 0 || pidfd < 0)
117 return ret_errno(EBADF);
d8764025 118
f51c7eb4
CB
119 ret = strnprintf(path + STRLITERALLEN("fdinfo/"), INTTYPE_TO_STRLEN(int), "%d", pidfd);
120 if (ret < 0)
d8764025
CB
121 return ret_errno(EIO);
122
6f0c2cea 123 f = fdopen_at(dfd_init_pid, path, "re", PROTECT_OPEN, PROTECT_LOOKUP_BENEATH);
d8764025
CB
124 if (!f)
125 return -errno;
126
127 while (getline(&line, &len, f) != -1) {
128 const char *prefix = "Pid:\t";
129 const size_t prefix_len = STRLITERALLEN("Pid:\t");
130 int pid = -ESRCH;
131 char *slider = line;
132
133 if (strncmp(slider, prefix, prefix_len))
134 continue;
135
136 slider += prefix_len;
137 slider = lxc_trim_whitespace_in_place(slider);
138
139 ret = lxc_safe_int(slider, &pid);
140 if (ret)
141 return -ret;
142
143 return pid;
144 }
145
146 return ret_errno(ENOENT);
147}
148
6e36c297
CB
149static inline bool sync_wake_pid(int fd, pid_t pid)
150{
151 return lxc_write_nointr(fd, &pid, sizeof(pid_t)) == sizeof(pid_t);
152}
153
154static inline bool sync_wait_pid(int fd, pid_t *pid)
155{
156 return lxc_read_nointr(fd, pid, sizeof(pid_t)) == sizeof(pid_t);
157}
158
159static inline bool sync_wake_fd(int fd, int fd_send)
160{
161 return lxc_abstract_unix_send_fds(fd, &fd_send, 1, NULL, 0) > 0;
162}
163
164static inline bool sync_wait_fd(int fd, int *fd_recv)
165{
166 return lxc_abstract_unix_recv_fds(fd, fd_recv, 1, NULL, 0) > 0;
167}
168
afc691a0
CB
169static bool attach_lsm(lxc_attach_options_t *options)
170{
171 return (options->namespaces & CLONE_NEWNS) &&
172 (options->attach_flags & (LXC_ATTACH_LSM | LXC_ATTACH_LSM_LABEL));
173}
174
9745eb8a
CB
175static struct attach_context *alloc_attach_context(void)
176{
581b849a
CB
177 struct attach_context *ctx;
178
179 ctx = zalloc(sizeof(struct attach_context));
180 if (!ctx)
181 return ret_set_errno(NULL, ENOMEM);
182
9b31ab58
CB
183 ctx->dfd_self_pid = -EBADF;
184 ctx->dfd_init_pid = -EBADF;
185 ctx->init_pidfd = -EBADF;
186 ctx->init_pid = -ESRCH;
187 ctx->setup_ns_uid = LXC_INVALID_UID;
188 ctx->setup_ns_gid = LXC_INVALID_GID;
189 ctx->target_ns_uid = LXC_INVALID_UID;
190 ctx->target_ns_gid = LXC_INVALID_GID;
191 ctx->target_host_uid = LXC_INVALID_UID;
192 ctx->target_host_gid = LXC_INVALID_GID;
581b849a
CB
193
194 for (int i = 0; i < LXC_NS_MAX; i++)
195 ctx->ns_fd[i] = -EBADF;
196
197 return ctx;
9745eb8a
CB
198}
199
ee142207
CB
200static int get_personality(const char *name, const char *lxcpath,
201 signed long *personality)
d92c8e40
CB
202{
203 __do_free char *p = NULL;
ee142207 204 signed long per;
d92c8e40
CB
205
206 p = lxc_cmd_get_config_item(name, "lxc.arch", lxcpath);
ee142207
CB
207 if (!p) {
208 *personality = LXC_ARCH_UNCHANGED;
209 return 0;
210 }
d92c8e40 211
ee142207
CB
212 per = lxc_config_parse_arch(p);
213 if (per == LXC_ARCH_UNCHANGED)
214 return ret_errno(EINVAL);
215
216 *personality = per;
217 return 0;
d92c8e40
CB
218}
219
4475fabb 220static int userns_setup_ids(struct attach_context *ctx,
3ac4480a 221 lxc_attach_options_t *options)
4475fabb
CB
222{
223 __do_free char *line = NULL;
224 __do_fclose FILE *f_gidmap = NULL, *f_uidmap = NULL;
225 size_t len = 0;
226 uid_t init_ns_uid = LXC_INVALID_UID;
227 gid_t init_ns_gid = LXC_INVALID_GID;
228 uid_t nsuid, hostuid, range_uid;
229 gid_t nsgid, hostgid, range_gid;
230
231 if (!(options->namespaces & CLONE_NEWUSER))
232 return 0;
233
72a19d2f 234 f_uidmap = fdopen_at(ctx->dfd_init_pid, "uid_map", "re", PROTECT_OPEN, PROTECT_LOOKUP_BENEATH);
4475fabb
CB
235 if (!f_uidmap)
236 return log_error_errno(-errno, errno, "Failed to open uid_map");
237
238 while (getline(&line, &len, f_uidmap) != -1) {
239 if (sscanf(line, "%u %u %u", &nsuid, &hostuid, &range_uid) != 3)
240 continue;
241
242 if (0 >= nsuid && 0 < nsuid + range_uid) {
3ac4480a 243 ctx->setup_ns_uid = 0;
4475fabb
CB
244 TRACE("Container has mapping for uid 0");
245 break;
246 }
247
3ac4480a
CB
248 if (ctx->target_host_uid >= hostuid && ctx->target_host_uid < hostuid + range_uid) {
249 init_ns_uid = (ctx->target_host_uid - hostuid) + nsuid;
4475fabb
CB
250 TRACE("Container runs with uid %d", init_ns_uid);
251 }
252 }
253
72a19d2f 254 f_gidmap = fdopen_at(ctx->dfd_init_pid, "gid_map", "re", PROTECT_OPEN, PROTECT_LOOKUP_BENEATH);
4475fabb
CB
255 if (!f_gidmap)
256 return log_error_errno(-errno, errno, "Failed to open gid_map");
257
258 while (getline(&line, &len, f_gidmap) != -1) {
259 if (sscanf(line, "%u %u %u", &nsgid, &hostgid, &range_gid) != 3)
260 continue;
261
262 if (0 >= nsgid && 0 < nsgid + range_gid) {
3ac4480a 263 ctx->setup_ns_gid = 0;
4475fabb
CB
264 TRACE("Container has mapping for gid 0");
265 break;
266 }
267
3ac4480a
CB
268 if (ctx->target_host_gid >= hostgid && ctx->target_host_gid < hostgid + range_gid) {
269 init_ns_gid = (ctx->target_host_gid - hostgid) + nsgid;
4475fabb
CB
270 TRACE("Container runs with gid %d", init_ns_gid);
271 }
272 }
273
3ac4480a
CB
274 if (ctx->setup_ns_uid == LXC_INVALID_UID)
275 ctx->setup_ns_uid = init_ns_uid;
4475fabb 276
3ac4480a
CB
277 if (ctx->setup_ns_gid == LXC_INVALID_UID)
278 ctx->setup_ns_gid = init_ns_gid;
4475fabb 279
4475fabb
CB
280 return 0;
281}
282
283static void userns_target_ids(struct attach_context *ctx, lxc_attach_options_t *options)
284{
285 if (options->uid != LXC_INVALID_UID)
3ac4480a 286 ctx->target_ns_uid = options->uid;
4475fabb 287 else if (options->namespaces & CLONE_NEWUSER)
3ac4480a 288 ctx->target_ns_uid = ctx->setup_ns_uid;
4475fabb 289 else
3ac4480a 290 ctx->target_ns_uid = 0;
4475fabb 291
3ac4480a 292 if (ctx->target_ns_uid == LXC_INVALID_UID)
4475fabb
CB
293 WARN("Invalid uid specified");
294
295 if (options->gid != LXC_INVALID_GID)
3ac4480a 296 ctx->target_ns_gid = options->gid;
4475fabb 297 else if (options->namespaces & CLONE_NEWUSER)
3ac4480a 298 ctx->target_ns_gid = ctx->setup_ns_gid;
4475fabb 299 else
3ac4480a 300 ctx->target_ns_gid = 0;
4475fabb 301
3ac4480a 302 if (ctx->target_ns_gid == LXC_INVALID_GID)
4475fabb
CB
303 WARN("Invalid gid specified");
304}
305
9680e7b0
CB
306static int parse_init_status(struct attach_context *ctx, lxc_attach_options_t *options)
307{
308 __do_free char *line = NULL;
309 __do_fclose FILE *f = NULL;
310 size_t len = 0;
311 bool caps_found = false;
4475fabb 312 int ret;
9680e7b0 313
72a19d2f 314 f = fdopen_at(ctx->dfd_init_pid, "status", "re", PROTECT_OPEN, PROTECT_LOOKUP_BENEATH);
9680e7b0 315 if (!f)
4475fabb 316 return log_error_errno(-errno, errno, "Failed to open status file");
9680e7b0
CB
317
318 while (getline(&line, &len, f) != -1) {
319 signed long value = -1;
9680e7b0 320
4475fabb
CB
321 /*
322 * Format is: real, effective, saved set user, fs we only care
323 * about real uid.
324 */
325 ret = sscanf(line, "Uid: %ld", &value);
326 if (ret != EOF && ret == 1) {
3ac4480a
CB
327 ctx->target_host_uid = (uid_t)value;
328 TRACE("Container's init process runs with hostuid %d", ctx->target_host_uid);
4475fabb
CB
329 goto next;
330 }
9680e7b0 331
4475fabb
CB
332 ret = sscanf(line, "Gid: %ld", &value);
333 if (ret != EOF && ret == 1) {
3ac4480a
CB
334 ctx->target_host_gid = (gid_t)value;
335 TRACE("Container's init process runs with hostgid %d", ctx->target_host_gid);
4475fabb 336 goto next;
9680e7b0
CB
337 }
338
339 ret = sscanf(line, "CapBnd: %llx", &ctx->capability_mask);
340 if (ret != EOF && ret == 1) {
341 caps_found = true;
342 goto next;
343 }
344
345 next:
3ac4480a
CB
346 if (ctx->target_host_uid != LXC_INVALID_UID &&
347 ctx->target_host_gid != LXC_INVALID_GID &&
4475fabb 348 caps_found)
9680e7b0
CB
349 break;
350
351 }
352
3ac4480a 353 ret = userns_setup_ids(ctx, options);
4475fabb
CB
354 if (ret)
355 return log_error_errno(ret, errno, "Failed to get setup ids");
356 userns_target_ids(ctx, options);
357
9680e7b0
CB
358 return 0;
359}
360
9b31ab58
CB
361static bool pidfd_setns_supported(struct attach_context *ctx)
362{
363 int ret;
364
365 /*
366 * The ability to attach to time namespaces came after the introduction
367 * of of using pidfds for attaching to namespaces. To avoid having to
368 * special-case both CLONE_NEWUSER and CLONE_NEWTIME handling, let's
369 * use CLONE_NEWTIME as gatekeeper.
370 */
371 if (ctx->init_pidfd >= 0)
372 ret = setns(ctx->init_pidfd, CLONE_NEWTIME);
373 else
374 ret = -EOPNOTSUPP;
375 TRACE("Attaching to namespaces via pidfds %s",
376 ret ? "unsupported" : "supported");
377 return ret == 0;
378}
379
500ed813 380static int get_attach_context(struct attach_context *ctx,
afc691a0
CB
381 struct lxc_container *container,
382 lxc_attach_options_t *options)
e0732705 383{
9680e7b0 384 __do_free char *lsm_label = NULL;
6f4f1937 385 int ret;
c538837d 386 char path[LXC_PROC_PID_LEN];
e0732705 387
500ed813 388 ctx->container = container;
afc691a0 389 ctx->attach_flags = options->attach_flags;
500ed813 390
6f0c2cea
CB
391 ctx->dfd_self_pid = open_at(-EBADF, "/proc/self",
392 PROTECT_OPATH_FILE & ~O_NOFOLLOW,
393 (PROTECT_LOOKUP_ABSOLUTE_WITH_SYMLINKS & ~RESOLVE_NO_XDEV), 0);
394 if (ctx->dfd_self_pid < 0)
395 return log_error_errno(-errno, errno, "Failed to open /proc/self");
396
9b31ab58
CB
397 ctx->init_pidfd = lxc_cmd_get_init_pidfd(container->name, container->config_path);
398 if (ctx->init_pidfd >= 0)
399 ctx->init_pid = pidfd_get_pid(ctx->dfd_self_pid, ctx->init_pidfd);
d8764025
CB
400 else
401 ctx->init_pid = lxc_cmd_get_init_pid(container->name, container->config_path);
402
500ed813
CB
403 if (ctx->init_pid < 0)
404 return log_error(-1, "Failed to get init pid");
405
f51c7eb4
CB
406 ret = strnprintf(path, sizeof(path), "/proc/%d", ctx->init_pid);
407 if (ret < 0)
c538837d 408 return ret_errno(EIO);
e0732705 409
5129b2d3
CB
410 ctx->dfd_init_pid = open_at(-EBADF, path,
411 PROTECT_OPATH_DIRECTORY,
412 (PROTECT_LOOKUP_ABSOLUTE & ~RESOLVE_NO_XDEV), 0);
9680e7b0 413 if (ctx->dfd_init_pid < 0)
4475fabb 414 return log_error_errno(-errno, errno, "Failed to open /proc/%d", ctx->init_pid);
c538837d 415
9b31ab58
CB
416 if (ctx->init_pidfd >= 0) {
417 ret = lxc_raw_pidfd_send_signal(ctx->init_pidfd, 0, NULL, 0);
d8764025
CB
418 if (ret)
419 return log_error_errno(-errno, errno, "Container process exited or PID has been recycled");
420 else
421 TRACE("Container process still running and PID was not recycled");
9b31ab58
CB
422
423 if (!pidfd_setns_supported(ctx)) {
424 /* We can't risk leaking file descriptors during attach. */
425 if (close(ctx->init_pidfd))
426 return log_error_errno(-errno, errno, "Failed to close pidfd");
427
428 ctx->init_pidfd = -EBADF;
429 TRACE("Attaching to namespaces via pidfds not supported");
430 }
d8764025
CB
431 }
432
4475fabb
CB
433 /* Determine which namespaces the container was created with. */
434 if (options->namespaces == -1) {
435 options->namespaces = lxc_cmd_get_clone_flags(container->name, container->config_path);
436 if (options->namespaces == -1)
437 return log_error_errno(-EINVAL, EINVAL, "Failed to automatically determine the namespaces which the container uses");
438
439 for (int i = 0; i < LXC_NS_MAX; i++) {
440 if (ns_info[i].clone_flag & CLONE_NEWCGROUP)
441 if (!(options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) ||
442 !cgns_supported())
443 continue;
444
445 if (ns_info[i].clone_flag & options->namespaces)
446 continue;
447
448 ctx->ns_inherited |= ns_info[i].clone_flag;
449 }
450 }
451
9680e7b0
CB
452 ret = parse_init_status(ctx, options);
453 if (ret)
4475fabb 454 return log_error_errno(-errno, errno, "Failed to open parse file");
e0732705 455
4eb19ac0 456 ctx->lsm_ops = lsm_init_static();
d701d729 457
afc691a0
CB
458 if (attach_lsm(options)) {
459 if (ctx->attach_flags & LXC_ATTACH_LSM_LABEL)
460 lsm_label = options->lsm_label;
461 else
9680e7b0 462 lsm_label = ctx->lsm_ops->process_label_get_at(ctx->lsm_ops, ctx->dfd_init_pid);
afc691a0
CB
463 if (!lsm_label)
464 WARN("No security context received");
465 else
466 INFO("Retrieved security context %s", lsm_label);
467 }
e0732705 468
ee142207
CB
469 ret = get_personality(container->name, container->config_path, &ctx->personality);
470 if (ret)
471 return log_error_errno(ret, errno, "Failed to get personality of the container");
d92c8e40 472
1874ef74
CB
473 if (!ctx->container->lxc_conf) {
474 ctx->container->lxc_conf = lxc_conf_init();
475 if (!ctx->container->lxc_conf)
476 return log_error_errno(-ENOMEM, ENOMEM, "Failed to allocate new lxc config");
477 }
478
afc691a0 479 ctx->lsm_label = move_ptr(lsm_label);
9745eb8a 480 return 0;
e0732705
CS
481}
482
9b31ab58 483static int same_nsfd(int dfd_pid1, int dfd_pid2, const char *ns_path)
299d1198 484{
9b31ab58 485 int ret;
299d1198
CB
486 struct stat ns_st1, ns_st2;
487
9b31ab58
CB
488 ret = fstatat(dfd_pid1, ns_path, &ns_st1, 0);
489 if (ret)
3cc629fe 490 return -1;
299d1198 491
9b31ab58
CB
492 ret = fstatat(dfd_pid2, ns_path, &ns_st2, 0);
493 if (ret)
3cc629fe 494 return -1;
299d1198
CB
495
496 /* processes are in the same namespace */
9b31ab58
CB
497 if ((ns_st1.st_dev == ns_st2.st_dev) &&
498 (ns_st1.st_ino == ns_st2.st_ino))
3cc629fe 499 return -EINVAL;
299d1198 500
9b31ab58
CB
501 return 0;
502}
503
504static int same_ns(int dfd_pid1, int dfd_pid2, const char *ns_path)
505{
506 __do_close int ns_fd2 = -EBADF;
507 int ret = -1;
508
509 ns_fd2 = open_at(dfd_pid2, ns_path, PROTECT_OPEN_WITH_TRAILING_SYMLINKS,
510 (PROTECT_LOOKUP_BENEATH_WITH_MAGICLINKS &
511 ~(RESOLVE_NO_XDEV | RESOLVE_BENEATH)), 0);
512 if (ns_fd2 < 0) {
513 /* The kernel does not support this namespace. This is not an error. */
514 if (errno == ENOENT)
515 return -EINVAL;
516 return log_error_errno(-errno, errno, "Failed to open %d(%s)",
517 dfd_pid2, ns_path);
518 }
519
520 ret = same_nsfd(dfd_pid1, dfd_pid2, ns_path);
521 if (ret < 0)
522 return ret;
523
299d1198 524 /* processes are in different namespaces */
3cc629fe 525 return move_fd(ns_fd2);
299d1198
CB
526}
527
9b31ab58
CB
528static int __prepare_namespaces_pidfd(struct attach_context *ctx)
529{
530 for (int i = 0; i < LXC_NS_MAX; i++) {
531 int ret;
532
533 if (!(ctx->ns_inherited & ns_info[i].clone_flag))
534 continue;
535
536 ret = same_nsfd(ctx->dfd_self_pid,
537 ctx->dfd_init_pid,
538 ns_info[i].proc_path);
539 if (ret == -EINVAL)
540 ctx->ns_inherited &= ~ns_info[i].clone_flag;
541 else if (ret < 0)
542 return log_error_errno(-1, errno,
543 "Failed to determine whether %s namespace is shared",
544 ns_info[i].proc_name);
545 else
546 TRACE("Shared %s namespace needs attach", ns_info[i].proc_name);
547 }
548
549 return 0;
550}
551
552static int __prepare_namespaces_nsfd(struct attach_context *ctx,
553 lxc_attach_options_t *options)
b7873c95 554{
b7873c95
CB
555 for (int i = 0; i < LXC_NS_MAX; i++) {
556 int j;
557
558 if (options->namespaces & ns_info[i].clone_flag)
5129b2d3
CB
559 ctx->ns_fd[i] = open_at(ctx->dfd_init_pid,
560 ns_info[i].proc_path,
561 PROTECT_OPEN_WITH_TRAILING_SYMLINKS,
9b31ab58
CB
562 (PROTECT_LOOKUP_BENEATH_WITH_MAGICLINKS &
563 ~(RESOLVE_NO_XDEV | RESOLVE_BENEATH)),
5129b2d3 564 0);
b7873c95 565 else if (ctx->ns_inherited & ns_info[i].clone_flag)
5129b2d3
CB
566 ctx->ns_fd[i] = same_ns(ctx->dfd_self_pid,
567 ctx->dfd_init_pid,
568 ns_info[i].proc_path);
b7873c95
CB
569 else
570 continue;
571
572 if (ctx->ns_fd[i] >= 0)
573 continue;
574
575 if (ctx->ns_fd[i] == -EINVAL) {
b7873c95
CB
576 ctx->ns_inherited &= ~ns_info[i].clone_flag;
577 continue;
578 }
579
580 /* We failed to preserve the namespace. */
9b31ab58
CB
581 SYSERROR("Failed to preserve %s namespace of %d",
582 ns_info[i].proc_name, ctx->init_pid);
b7873c95
CB
583
584 /* Close all already opened file descriptors before we return an
585 * error, so we don't leak them.
586 */
587 for (j = 0; j < i; j++)
588 close_prot_errno_disarm(ctx->ns_fd[j]);
589
590 return -1;
591 }
592
593 return 0;
594}
595
9b31ab58
CB
596static int prepare_namespaces(struct attach_context *ctx,
597 lxc_attach_options_t *options)
b7873c95 598{
9b31ab58
CB
599 if (ctx->init_pidfd < 0)
600 return __prepare_namespaces_nsfd(ctx, options);
601
602 return __prepare_namespaces_pidfd(ctx);
b7873c95
CB
603}
604
9b31ab58 605static inline void put_namespaces(struct attach_context *ctx)
b7873c95 606{
9b31ab58
CB
607 if (ctx->init_pidfd < 0) {
608 for (int i = 0; i < LXC_NS_MAX; i++)
609 close_prot_errno_disarm(ctx->ns_fd[i]);
610 }
611}
b7873c95 612
9b31ab58
CB
613static int __attach_namespaces_pidfd(struct attach_context *ctx,
614 lxc_attach_options_t *options)
615{
616 unsigned int ns_flags = options->namespaces | ctx->ns_inherited;
617 int ret;
b7873c95 618
9b31ab58
CB
619 /* The common case is to attach to all namespaces. */
620 ret = setns(ctx->init_pidfd, ns_flags);
621 if (ret)
622 return log_error_errno(-errno, errno,
623 "Failed to attach to namespaces via pidfd");
624
625 /* We can't risk leaking file descriptors into the container. */
626 if (close(ctx->init_pidfd))
627 return log_error_errno(-errno, errno, "Failed to close pidfd");
628 ctx->init_pidfd = -EBADF;
629
630 return log_trace(0, "Attached to container namespaces via pidfd");
b7873c95
CB
631}
632
9b31ab58
CB
633static int __attach_namespaces_nsfd(struct attach_context *ctx,
634 lxc_attach_options_t *options)
99d50954 635{
92466fe3
CB
636 int fret = 0;
637
ffeeed8b
CB
638 for (int i = 0; i < LXC_NS_MAX; i++) {
639 int ret;
99d50954 640
877f3a04 641 if (ctx->ns_fd[i] < 0)
26818618
CB
642 continue;
643
21d0acc2 644 ret = setns(ctx->ns_fd[i], ns_info[i].clone_flag);
92466fe3 645 if (ret)
9b31ab58
CB
646 return log_error_errno(-errno, errno,
647 "Failed to attach to %s namespace of %d",
648 ns_info[i].proc_name,
649 ctx->init_pid);
92466fe3
CB
650
651 if (close(ctx->ns_fd[i])) {
652 fret = -errno;
9b31ab58
CB
653 SYSERROR("Failed to close file descriptor for %s namespace",
654 ns_info[i].proc_name);
92466fe3
CB
655 }
656 ctx->ns_fd[i] = -EBADF;
99d50954
CS
657 }
658
92466fe3 659 return fret;
99d50954
CS
660}
661
9b31ab58
CB
662static int attach_namespaces(struct attach_context *ctx,
663 lxc_attach_options_t *options)
664{
665 if (lxc_log_trace()) {
666 for (int i = 0; i < LXC_NS_MAX; i++) {
667 if (ns_info[i].clone_flag & options->namespaces) {
668 TRACE("Attaching to %s namespace", ns_info[i].proc_name);
669 continue;
670 }
671 if (ns_info[i].clone_flag & ctx->ns_inherited) {
672 TRACE("Sharing %s namespace", ns_info[i].proc_name);
673 continue;
674 }
675 TRACE("Inheriting %s namespace", ns_info[i].proc_name);
676 }
677 }
678
679 if (ctx->init_pidfd < 0)
680 return __attach_namespaces_nsfd(ctx, options);
681
682 return __attach_namespaces_pidfd(ctx, options);
683}
684
685static void put_attach_context(struct attach_context *ctx)
686{
687 if (ctx) {
688 if (!(ctx->attach_flags & LXC_ATTACH_LSM_LABEL))
689 free_disarm(ctx->lsm_label);
690 close_prot_errno_disarm(ctx->dfd_init_pid);
691
692 if (ctx->container) {
693 lxc_container_put(ctx->container);
694 ctx->container = NULL;
695 }
696
697 put_namespaces(ctx);
698 free(ctx);
699 }
700}
701
c538837d
CB
702/*
703 * Place anything in here that needs to be get rid of before we move into the
704 * container's context and fail hard if we can't.
705 */
706static bool attach_context_security_barrier(struct attach_context *ctx)
707{
708 if (ctx) {
25c659d5
CB
709 if (close(ctx->dfd_self_pid))
710 return false;
711 ctx->dfd_self_pid = -EBADF;
712
713 if (close(ctx->dfd_init_pid))
c538837d 714 return false;
25c659d5 715 ctx->dfd_init_pid = -EBADF;
c538837d
CB
716 }
717
718 return true;
719}
720
e4103cf6 721int lxc_attach_remount_sys_proc(void)
7a0b0b56
CS
722{
723 int ret;
724
725 ret = unshare(CLONE_NEWNS);
ffeeed8b
CB
726 if (ret < 0)
727 return log_error_errno(-1, errno, "Failed to unshare mount namespace");
7a0b0b56 728
9e61fb1f
CB
729 if (detect_shared_rootfs() && mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL))
730 SYSERROR("Failed to recursively turn root mount tree into dependent mount. Continuing...");
2c6f3fc9 731
8ce83369 732 /* Assume /proc is always mounted, so remount it. */
7a0b0b56 733 ret = umount2("/proc", MNT_DETACH);
ffeeed8b
CB
734 if (ret < 0)
735 return log_error_errno(-1, errno, "Failed to unmount /proc");
7a0b0b56 736
0d50f288 737 ret = mount("none", "/proc", "proc", 0, NULL);
ffeeed8b
CB
738 if (ret < 0)
739 return log_error_errno(-1, errno, "Failed to remount /proc");
7a0b0b56 740
ffeeed8b
CB
741 /*
742 * Try to umount /sys. If it's not a mount point, we'll get EINVAL, then
8ce83369 743 * we ignore it because it may not have been mounted in the first place.
7a0b0b56
CS
744 */
745 ret = umount2("/sys", MNT_DETACH);
ffeeed8b
CB
746 if (ret < 0 && errno != EINVAL)
747 return log_error_errno(-1, errno, "Failed to unmount /sys");
748
749 /* Remount it. */
0d50f288 750 if (ret == 0 && mount("none", "/sys", "sysfs", 0, NULL))
ffeeed8b 751 return log_error_errno(-1, errno, "Failed to remount /sys");
7a0b0b56
CS
752
753 return 0;
754}
755
677e1d27 756static int drop_capabilities(struct attach_context *ctx)
e0732705 757{
ffeeed8b 758 int last_cap;
e0732705 759
6f4f1937 760 last_cap = lxc_caps_last_cap();
ffeeed8b 761 for (int cap = 0; cap <= last_cap; cap++) {
e0732705
CS
762 if (ctx->capability_mask & (1LL << cap))
763 continue;
764
b81689a1 765 if (prctl(PR_CAPBSET_DROP, prctl_arg(cap), prctl_arg(0),
ffeeed8b
CB
766 prctl_arg(0), prctl_arg(0)))
767 return log_error_errno(-1, errno, "Failed to drop capability %d", cap);
ea918412 768
94ac256f 769 TRACE("Dropped capability %d", cap);
e0732705
CS
770 }
771
772 return 0;
773}
905022f7 774
ab919e5f 775static int lxc_attach_set_environment(struct attach_context *ctx,
7385273f 776 enum lxc_attach_env_policy_t policy,
6f4f1937 777 char **extra_env, char **extra_keep)
b3a39ba6 778{
3d55242a 779 int ret;
7385273f 780 struct lxc_list *iterator;
781
799f96fd 782 if (policy == LXC_ATTACH_CLEAR_ENV) {
3d5e9f48 783 int path_kept = 0;
6f4f1937 784 char **extra_keep_store = NULL;
3d5e9f48
CS
785
786 if (extra_keep) {
787 size_t count, i;
788
3d55242a
CB
789 for (count = 0; extra_keep[count]; count++)
790 ;
3d5e9f48 791
89b7bfe3 792 extra_keep_store = zalloc(count * sizeof(char *));
3d55242a 793 if (!extra_keep_store)
3d5e9f48 794 return -1;
3d55242a 795
3d5e9f48
CS
796 for (i = 0; i < count; i++) {
797 char *v = getenv(extra_keep[i]);
798 if (v) {
799 extra_keep_store[i] = strdup(v);
800 if (!extra_keep_store[i]) {
3d5e9f48
CS
801 while (i > 0)
802 free(extra_keep_store[--i]);
ea918412 803
3d5e9f48
CS
804 free(extra_keep_store);
805 return -1;
806 }
3d55242a 807
3d5e9f48
CS
808 if (strcmp(extra_keep[i], "PATH") == 0)
809 path_kept = 1;
810 }
3d5e9f48
CS
811 }
812 }
813
799f96fd 814 if (clearenv()) {
a9cab7e3 815 if (extra_keep_store) {
3d55242a
CB
816 char **p;
817
a9cab7e3
CS
818 for (p = extra_keep_store; *p; p++)
819 free(*p);
3d55242a 820
a9cab7e3
CS
821 free(extra_keep_store);
822 }
3d55242a 823
ffeeed8b 824 return log_error(-1, "Failed to clear environment");
3d5e9f48
CS
825 }
826
827 if (extra_keep_store) {
828 size_t i;
6f4f1937 829
3d5e9f48 830 for (i = 0; extra_keep[i]; i++) {
acd4922e 831 if (extra_keep_store[i]) {
3d55242a
CB
832 ret = setenv(extra_keep[i], extra_keep_store[i], 1);
833 if (ret < 0)
a24c5678 834 SYSWARN("Failed to set environment variable");
acd4922e 835 }
ea918412 836
3d5e9f48
CS
837 free(extra_keep_store[i]);
838 }
ea918412 839
3d5e9f48
CS
840 free(extra_keep_store);
841 }
842
8ce83369
CB
843 /* Always set a default path; shells and execlp tend to be fine
844 * without it, but there is a disturbing number of C programs
845 * out there that just assume that getenv("PATH") is never NULL
846 * and then die a painful segfault death.
847 */
3d55242a
CB
848 if (!path_kept) {
849 ret = setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
850 if (ret < 0)
a24c5678 851 SYSWARN("Failed to set environment variable");
3d55242a 852 }
b3a39ba6
DW
853 }
854
3d55242a 855 ret = putenv("container=lxc");
ffeeed8b 856 if (ret < 0)
818a57fc 857 return log_warn(-1, "Failed to set environment variable");
b3a39ba6 858
7385273f 859 /* Set container environment variables.*/
640952e5 860 if (ctx->container->lxc_conf) {
ab919e5f 861 lxc_list_for_each(iterator, &ctx->container->lxc_conf->environment) {
3d55242a
CB
862 char *env_tmp;
863
864 env_tmp = strdup((char *)iterator->elem);
865 if (!env_tmp)
7385273f 866 return -1;
7385273f 867
3d55242a 868 ret = putenv(env_tmp);
ffeeed8b
CB
869 if (ret < 0)
870 return log_error_errno(-1, errno, "Failed to set environment variable: %s", (char *)iterator->elem);
7385273f 871 }
872 }
873
8ce83369 874 /* Set extra environment variables. */
3d5e9f48
CS
875 if (extra_env) {
876 for (; *extra_env; extra_env++) {
3d55242a 877 char *p;
ea918412 878
8ce83369
CB
879 /* We just assume the user knows what they are doing, so
880 * we don't do any checks.
881 */
3d55242a
CB
882 p = strdup(*extra_env);
883 if (!p)
3d5e9f48 884 return -1;
3d55242a
CB
885
886 ret = putenv(p);
887 if (ret < 0)
a24c5678 888 SYSWARN("Failed to set environment variable");
3d5e9f48
CS
889 }
890 }
891
b3a39ba6
DW
892 return 0;
893}
894
74a3920a 895static char *lxc_attach_getpwshell(uid_t uid)
905022f7 896{
1b9c9f5b 897 __do_free char *line = NULL, *result = NULL;
cd8f5663 898 __do_fclose FILE *pipe_f = NULL;
6f4f1937 899 int fd, ret;
905022f7
CS
900 pid_t pid;
901 int pipes[2];
3fa23ac3
CB
902 bool found = false;
903 size_t line_bufsz = 0;
905022f7 904
8ce83369
CB
905 /* We need to fork off a process that runs the getent program, and we
906 * need to capture its output, so we use a pipe for that purpose.
905022f7 907 */
3fa23ac3 908 ret = pipe2(pipes, O_CLOEXEC);
905022f7
CS
909 if (ret < 0)
910 return NULL;
911
912 pid = fork();
913 if (pid < 0) {
914 close(pipes[0]);
915 close(pipes[1]);
916 return NULL;
917 }
918
3fa23ac3 919 if (!pid) {
905022f7
CS
920 char uid_buf[32];
921 char *arguments[] = {
922 "getent",
923 "passwd",
924 uid_buf,
925 NULL
926 };
927
928 close(pipes[0]);
929
8ce83369 930 /* We want to capture stdout. */
3fa23ac3 931 ret = dup2(pipes[1], STDOUT_FILENO);
905022f7 932 close(pipes[1]);
3fa23ac3 933 if (ret < 0)
ea918412 934 _exit(EXIT_FAILURE);
905022f7 935
8ce83369
CB
936 /* Get rid of stdin/stderr, so we try to associate it with
937 * /dev/null.
905022f7 938 */
3fa23ac3 939 fd = open_devnull();
905022f7 940 if (fd < 0) {
3fa23ac3
CB
941 close(STDIN_FILENO);
942 close(STDERR_FILENO);
905022f7 943 } else {
3fa23ac3 944 (void)dup3(fd, STDIN_FILENO, O_CLOEXEC);
59f0e209 945 (void)dup3(fd, STDERR_FILENO, O_CLOEXEC);
905022f7
CS
946 close(fd);
947 }
948
8ce83369 949 /* Finish argument list. */
f51c7eb4
CB
950 ret = strnprintf(uid_buf, sizeof(uid_buf), "%ld", (long)uid);
951 if (ret <= 0)
ea918412 952 _exit(EXIT_FAILURE);
905022f7 953
8ce83369 954 /* Try to run getent program. */
3fa23ac3 955 (void)execvp("getent", arguments);
ea918412 956 _exit(EXIT_FAILURE);
905022f7 957 }
3fa23ac3
CB
958
959 close(pipes[1]);
960
4110345b 961 pipe_f = fdopen(pipes[0], "re");
cf4026f1
CB
962 if (!pipe_f) {
963 close(pipes[0]);
964 goto reap_child;
965 }
966 /* Transfer ownership of pipes[0] to pipe_f. */
967 move_fd(pipes[0]);
968
3fa23ac3
CB
969 while (getline(&line, &line_bufsz, pipe_f) != -1) {
970 int i;
971 long value;
972 char *token;
973 char *endptr = NULL, *saveptr = NULL;
974
975 /* If we already found something, just continue to read
976 * until the pipe doesn't deliver any more data, but
977 * don't modify the existing data structure.
978 */
979 if (found)
980 continue;
981
18d4ffde 982 if (!line)
983 continue;
984
3fa23ac3
CB
985 /* Trim line on the right hand side. */
986 for (i = strlen(line); i > 0 && (line[i - 1] == '\n' || line[i - 1] == '\r'); --i)
987 line[i - 1] = '\0';
988
989 /* Split into tokens: first: user name. */
990 token = strtok_r(line, ":", &saveptr);
991 if (!token)
992 continue;
993
994 /* next: dummy password field */
995 token = strtok_r(NULL, ":", &saveptr);
996 if (!token)
997 continue;
998
999 /* next: user id */
1000 token = strtok_r(NULL, ":", &saveptr);
1001 value = token ? strtol(token, &endptr, 10) : 0;
1002 if (!token || !endptr || *endptr || value == LONG_MIN ||
ea918412 1003 value == LONG_MAX)
3fa23ac3
CB
1004 continue;
1005
1006 /* dummy sanity check: user id matches */
1007 if ((uid_t)value != uid)
1008 continue;
1009
1010 /* skip fields: gid, gecos, dir, go to next field 'shell' */
1011 for (i = 0; i < 4; i++) {
1012 token = strtok_r(NULL, ":", &saveptr);
1013 if (!token)
1014 continue;
1015 }
ea918412 1016
3fa23ac3
CB
1017 if (!token)
1018 continue;
ea918412 1019
1b9c9f5b 1020 free_disarm(result);
3fa23ac3
CB
1021 result = strdup(token);
1022
1023 /* Sanity check that there are no fields after that. */
1024 token = strtok_r(NULL, ":", &saveptr);
1025 if (token)
1026 continue;
1027
1028 found = true;
1029 }
ea918412 1030
cf4026f1 1031reap_child:
3fa23ac3 1032 ret = wait_for_pid(pid);
1b9c9f5b 1033 if (ret < 0)
3fa23ac3 1034 return NULL;
3fa23ac3 1035
1b9c9f5b 1036 if (!found)
3fa23ac3 1037 return NULL;
3fa23ac3 1038
1b9c9f5b 1039 return move_ptr(result);
905022f7 1040}
cb3e61fa 1041
d4db3d14 1042static bool fetch_seccomp(struct lxc_container *c, lxc_attach_options_t *options)
2c4ea790 1043{
cd8f5663 1044 __do_free char *path = NULL;
d4db3d14
CB
1045 int ret;
1046 bool bret;
2eef2bda 1047
afc691a0 1048 if (!attach_lsm(options)) {
cca66e06 1049 free_disarm(c->lxc_conf->seccomp.seccomp);
2c4ea790 1050 return true;
bd4307f0 1051 }
bd7b4e28 1052
afc691a0 1053 /* Remove current setting. */
d4db3d14 1054 if (!c->set_config_item(c, "lxc.seccomp.profile", "") &&
ea918412 1055 !c->set_config_item(c, "lxc.seccomp", ""))
2c4ea790 1056 return false;
bd7b4e28 1057
8ce83369 1058 /* Fetch the current profile path over the cmd interface. */
0b427da0 1059 path = c->get_running_config_item(c, "lxc.seccomp.profile");
bd7b4e28 1060 if (!path) {
d4db3d14 1061 INFO("Failed to retrieve lxc.seccomp.profile");
ea918412 1062
0b427da0 1063 path = c->get_running_config_item(c, "lxc.seccomp");
cca66e06
CB
1064 if (!path)
1065 return log_info(true, "Failed to retrieve lxc.seccomp");
bd7b4e28
SG
1066 }
1067
8ce83369 1068 /* Copy the value into the new lxc_conf. */
d4db3d14 1069 bret = c->set_config_item(c, "lxc.seccomp.profile", path);
d4db3d14
CB
1070 if (!bret)
1071 return false;
bd7b4e28 1072
8ce83369 1073 /* Attempt to parse the resulting config. */
d4db3d14 1074 ret = lxc_read_seccomp_config(c->lxc_conf);
cca66e06
CB
1075 if (ret < 0)
1076 return log_error(false, "Failed to retrieve seccomp policy");
2c4ea790 1077
cca66e06 1078 return log_info(true, "Retrieved seccomp policy");
2e812c16
CB
1079}
1080
6f4f1937 1081static bool no_new_privs(struct lxc_container *c, lxc_attach_options_t *options)
2e812c16 1082{
cd8f5663 1083 __do_free char *val = NULL;
2e812c16 1084
2e812c16 1085 /* Remove current setting. */
02d3b72b
CB
1086 if (!c->set_config_item(c, "lxc.no_new_privs", ""))
1087 return log_info(false, "Failed to unset lxc.no_new_privs");
2e812c16
CB
1088
1089 /* Retrieve currently active setting. */
1090 val = c->get_running_config_item(c, "lxc.no_new_privs");
02d3b72b
CB
1091 if (!val)
1092 return log_info(false, "Failed to retrieve lxc.no_new_privs");
2e812c16
CB
1093
1094 /* Set currently active setting. */
cd8f5663 1095 return c->set_config_item(c, "lxc.no_new_privs", val);
2c4ea790
SH
1096}
1097
338b230f 1098struct attach_payload {
a998454a 1099 int ipc_socket;
cecf3e83 1100 int terminal_pts_fd;
a998454a 1101 lxc_attach_options_t *options;
ab919e5f 1102 struct attach_context *ctx;
a998454a
CB
1103 lxc_attach_exec_t exec_function;
1104 void *exec_payload;
1105};
1106
338b230f 1107static void put_attach_payload(struct attach_payload *p)
ba2be1a8 1108{
afc691a0
CB
1109 if (p) {
1110 close_prot_errno_disarm(p->ipc_socket);
1111 close_prot_errno_disarm(p->terminal_pts_fd);
dd53c8af 1112 put_attach_context(p->ctx);
ab919e5f 1113 p->ctx = NULL;
b21da190 1114 }
ba2be1a8
CB
1115}
1116
338b230f 1117__noreturn static void do_attach(struct attach_payload *ap)
a998454a 1118{
afc691a0
CB
1119 lxc_attach_exec_t attach_function = move_ptr(ap->exec_function);
1120 void *attach_function_args = move_ptr(ap->exec_payload);
427a8067 1121 int lsm_fd, ret;
338b230f
CB
1122 lxc_attach_options_t* options = ap->options;
1123 struct attach_context *ctx = ap->ctx;
ab919e5f 1124 struct lxc_conf *conf = ctx->container->lxc_conf;
a998454a
CB
1125
1126 /* A description of the purpose of this functionality is provided in the
1127 * lxc-attach(1) manual page. We have to remount here and not in the
1128 * parent process, otherwise /proc may not properly reflect the new pid
1129 * namespace.
1130 */
1131 if (!(options->namespaces & CLONE_NEWNS) &&
1132 (options->attach_flags & LXC_ATTACH_REMOUNT_PROC_SYS)) {
1133 ret = lxc_attach_remount_sys_proc();
b75c344c
CB
1134 if (ret < 0)
1135 goto on_error;
ea918412 1136
b75c344c 1137 TRACE("Remounted \"/proc\" and \"/sys\"");
a998454a
CB
1138 }
1139
5b514ce3 1140 /* Now perform additional attachments. */
a998454a 1141#if HAVE_SYS_PERSONALITY_H
a998454a 1142 if (options->attach_flags & LXC_ATTACH_SET_PERSONALITY) {
b75c344c
CB
1143 long new_personality;
1144
1145 if (options->personality < 0)
ab919e5f 1146 new_personality = ctx->personality;
b75c344c
CB
1147 else
1148 new_personality = options->personality;
ea918412 1149
ee142207
CB
1150 if (new_personality != LXC_ARCH_UNCHANGED) {
1151 ret = personality(new_personality);
1152 if (ret < 0)
1153 goto on_error;
ea918412 1154
ee142207
CB
1155 TRACE("Set new personality");
1156 }
a998454a
CB
1157 }
1158#endif
1159
1160 if (options->attach_flags & LXC_ATTACH_DROP_CAPABILITIES) {
677e1d27 1161 ret = drop_capabilities(ctx);
b75c344c
CB
1162 if (ret < 0)
1163 goto on_error;
ea918412 1164
b75c344c 1165 TRACE("Dropped capabilities");
a998454a
CB
1166 }
1167
1168 /* Always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL)
1169 * if you want this to be a no-op).
1170 */
ab919e5f 1171 ret = lxc_attach_set_environment(ctx,
7385273f 1172 options->env_policy,
a998454a
CB
1173 options->extra_env_vars,
1174 options->extra_keep_env);
b75c344c
CB
1175 if (ret < 0)
1176 goto on_error;
ea918412 1177
b75c344c 1178 TRACE("Set up environment");
a998454a 1179
afc691a0
CB
1180 /*
1181 * This remark only affects fully unprivileged containers:
57de839f
CB
1182 * Receive fd for LSM security module before we set{g,u}id(). The reason
1183 * is that on set{g,u}id() the kernel will a) make us undumpable and b)
1184 * we will change our effective uid. This means our effective uid will
1185 * be different from the effective uid of the process that created us
1186 * which means that this processs no longer has capabilities in our
1187 * namespace including CAP_SYS_PTRACE. This means we will not be able to
1188 * read and /proc/<pid> files for the process anymore when /proc is
1189 * mounted with hidepid={1,2}. So let's get the lsm label fd before the
1190 * set{g,u}id().
1191 */
afc691a0 1192 if (attach_lsm(options) && ctx->lsm_label) {
f8e88e94 1193 if (!sync_wait_fd(ap->ipc_socket, ATTACH_SYNC_LSM(&lsm_fd))) {
6e36c297 1194 SYSERROR("Failed to receive lsm label fd");
b75c344c 1195 goto on_error;
9044b79e 1196 }
1197
57de839f
CB
1198 TRACE("Received LSM label file descriptor %d from parent", lsm_fd);
1199 }
1200
08ea9270 1201 if (options->stdin_fd > 0 && isatty(options->stdin_fd)) {
cd0a2b2f 1202 ret = lxc_make_controlling_terminal(options->stdin_fd);
08ea9270
CB
1203 if (ret < 0)
1204 goto on_error;
1205 }
1206
9475d2b9
CB
1207 if ((options->attach_flags & LXC_ATTACH_SETGROUPS) &&
1208 options->groups.size > 0) {
8caac583
RJ
1209 if (!lxc_setgroups(options->groups.list, options->groups.size))
1210 goto on_error;
1211 } else {
1212 if (!lxc_drop_groups() && errno != EPERM)
1213 goto on_error;
1214 }
b58214ac 1215
4475fabb 1216 if (options->namespaces & CLONE_NEWUSER)
3ac4480a 1217 if (!lxc_switch_uid_gid(ctx->setup_ns_uid, ctx->setup_ns_gid))
b75c344c 1218 goto on_error;
936efc72 1219
afc691a0 1220 if (attach_lsm(options) && ctx->lsm_label) {
d3ba7c98 1221 bool on_exec;
a998454a
CB
1222
1223 /* Change into our new LSM profile. */
d3ba7c98 1224 on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? true : false;
afc691a0 1225 ret = ctx->lsm_ops->process_label_set_at(ctx->lsm_ops, lsm_fd, ctx->lsm_label, on_exec);
cb2420df 1226 close_prot_errno_disarm(lsm_fd);
b75c344c
CB
1227 if (ret < 0)
1228 goto on_error;
ea918412 1229
ab919e5f 1230 TRACE("Set %s LSM label to \"%s\"", ctx->lsm_ops->name, ctx->lsm_label);
a998454a
CB
1231 }
1232
640952e5 1233 if (conf->no_new_privs || (options->attach_flags & LXC_ATTACH_NO_NEW_PRIVS)) {
6ce8e678
AL
1234 ret = prctl(PR_SET_NO_NEW_PRIVS, prctl_arg(1), prctl_arg(0),
1235 prctl_arg(0), prctl_arg(0));
1236 if (ret < 0)
1237 goto on_error;
1238
1239 TRACE("Set PR_SET_NO_NEW_PRIVS");
1240 }
1241
a998454a
CB
1242 /* The following is done after the communication socket is shut down.
1243 * That way, all errors that might (though unlikely) occur up until this
1244 * point will have their messages printed to the original stderr (if
1245 * logging is so configured) and not the fd the user supplied, if any.
1246 */
1247
1248 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
1249 * may want to make sure the fds are closed, for example.
1250 */
08ea9270 1251 if (options->stdin_fd >= 0 && options->stdin_fd != STDIN_FILENO)
40301d48 1252 if (dup2(options->stdin_fd, STDIN_FILENO) < 0)
a7563434 1253 SYSDEBUG("Failed to replace stdin with %d", options->stdin_fd);
08ea9270
CB
1254
1255 if (options->stdout_fd >= 0 && options->stdout_fd != STDOUT_FILENO)
40301d48 1256 if (dup2(options->stdout_fd, STDOUT_FILENO) < 0)
93b9960a 1257 SYSDEBUG("Failed to replace stdout with %d", options->stdout_fd);
08ea9270
CB
1258
1259 if (options->stderr_fd >= 0 && options->stderr_fd != STDERR_FILENO)
40301d48 1260 if (dup2(options->stderr_fd, STDERR_FILENO) < 0)
93b9960a 1261 SYSDEBUG("Failed to replace stderr with %d", options->stderr_fd);
a998454a
CB
1262
1263 /* close the old fds */
08ea9270 1264 if (options->stdin_fd > STDERR_FILENO)
a998454a 1265 close(options->stdin_fd);
08ea9270
CB
1266
1267 if (options->stdout_fd > STDERR_FILENO)
a998454a 1268 close(options->stdout_fd);
08ea9270
CB
1269
1270 if (options->stderr_fd > STDERR_FILENO)
a998454a
CB
1271 close(options->stderr_fd);
1272
427a8067
CB
1273 /*
1274 * Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
a998454a
CB
1275 * here, ignore errors.
1276 */
427a8067 1277 for (int fd = STDIN_FILENO; fd <= STDERR_FILENO; fd++) {
3f62938a 1278 ret = fd_cloexec(fd, false);
b75c344c
CB
1279 if (ret < 0) {
1280 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd);
1281 goto on_error;
1282 }
a998454a
CB
1283 }
1284
9e84479f 1285 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
338b230f 1286 ret = lxc_terminal_prepare_login(ap->terminal_pts_fd);
ba2be1a8 1287 if (ret < 0) {
338b230f 1288 SYSERROR("Failed to prepare terminal file descriptor %d", ap->terminal_pts_fd);
ba2be1a8
CB
1289 goto on_error;
1290 }
ea918412 1291
338b230f 1292 TRACE("Prepared terminal file descriptor %d", ap->terminal_pts_fd);
ba2be1a8
CB
1293 }
1294
4475fabb 1295 /* Avoid unnecessary syscalls. */
3ac4480a
CB
1296 if (ctx->setup_ns_uid == ctx->target_ns_uid)
1297 ctx->target_ns_uid = LXC_INVALID_UID;
1298
1299 if (ctx->setup_ns_gid == ctx->target_ns_gid)
1300 ctx->target_ns_gid = LXC_INVALID_GID;
4475fabb 1301
3ac4480a
CB
1302 /*
1303 * Make sure that the processes STDIO is correctly owned by the user
1304 * that we are switching to.
1305 */
1306 ret = fix_stdio_permissions(ctx->target_ns_uid);
1307 if (ret)
1308 INFO("Failed to adjust stdio permissions");
4475fabb 1309
e18aba7d
CB
1310 if (conf->seccomp.seccomp) {
1311 ret = lxc_seccomp_load(conf);
1312 if (ret < 0)
1313 goto on_error;
1314
1315 TRACE("Loaded seccomp profile");
1316
1317 ret = lxc_seccomp_send_notifier_fd(&conf->seccomp, ap->ipc_socket);
1318 if (ret < 0)
1319 goto on_error;
c5bac506 1320 lxc_seccomp_close_notifier_fd(&conf->seccomp);
e18aba7d
CB
1321 }
1322
3ac4480a 1323 if (!lxc_switch_uid_gid(ctx->target_ns_uid, ctx->target_ns_gid))
936efc72
CB
1324 goto on_error;
1325
cd5f35ec
CB
1326 put_attach_payload(ap);
1327
a998454a 1328 /* We're done, so we can now do whatever the user intended us to do. */
afc691a0 1329 _exit(attach_function(attach_function_args));
b75c344c
CB
1330
1331on_error:
dab02267 1332 ERROR("Failed to attach to container");
cd5f35ec 1333 put_attach_payload(ap);
c7ac2e1c 1334 _exit(EXIT_FAILURE);
a998454a
CB
1335}
1336
f797f05e 1337static int lxc_attach_terminal(const char *name, const char *lxcpath, struct lxc_conf *conf,
9e84479f 1338 struct lxc_terminal *terminal)
ba2be1a8
CB
1339{
1340 int ret;
1341
9e84479f 1342 lxc_terminal_init(terminal);
ba2be1a8 1343
8ea93a0f 1344 ret = lxc_terminal_create(name, lxcpath, conf, terminal);
c2af3a15
CB
1345 if (ret < 0)
1346 return log_error(-1, "Failed to create terminal");
ba2be1a8 1347
ba2be1a8 1348 return 0;
ba2be1a8
CB
1349}
1350
9e84479f
CB
1351static int lxc_attach_terminal_mainloop_init(struct lxc_terminal *terminal,
1352 struct lxc_epoll_descr *descr)
ba2be1a8
CB
1353{
1354 int ret;
1355
1356 ret = lxc_mainloop_open(descr);
c2af3a15
CB
1357 if (ret < 0)
1358 return log_error(-1, "Failed to create mainloop");
ba2be1a8 1359
9e84479f 1360 ret = lxc_terminal_mainloop_add(descr, terminal);
ba2be1a8 1361 if (ret < 0) {
ba2be1a8 1362 lxc_mainloop_close(descr);
c2af3a15 1363 return log_error(-1, "Failed to add handlers to mainloop");
ba2be1a8
CB
1364 }
1365
1366 return 0;
1367}
1368
36a94ce8 1369static inline void lxc_attach_terminal_close_ptx(struct lxc_terminal *terminal)
ba2be1a8 1370{
36a94ce8 1371 close_prot_errno_disarm(terminal->ptx);
ba2be1a8
CB
1372}
1373
cecf3e83 1374static inline void lxc_attach_terminal_close_pts(struct lxc_terminal *terminal)
ba2be1a8 1375{
41808e20 1376 close_prot_errno_disarm(terminal->pty);
ba2be1a8
CB
1377}
1378
9e84479f 1379static inline void lxc_attach_terminal_close_peer(struct lxc_terminal *terminal)
ba2be1a8 1380{
19a3e906 1381 close_prot_errno_disarm(terminal->peer);
ba2be1a8
CB
1382}
1383
9e84479f 1384static inline void lxc_attach_terminal_close_log(struct lxc_terminal *terminal)
ba2be1a8 1385{
19a3e906 1386 close_prot_errno_disarm(terminal->log_fd);
ba2be1a8
CB
1387}
1388
908fbc1a
CB
1389int lxc_attach(struct lxc_container *container, lxc_attach_exec_t exec_function,
1390 void *exec_payload, lxc_attach_options_t *options,
1391 pid_t *attached_process)
9c4693b8 1392{
6f9fe5d0 1393 int ret_parent = -1;
6f9fe5d0 1394 struct lxc_epoll_descr descr = {};
a9f0cecf 1395 int ret;
26abd7ea 1396 char *name, *lxcpath;
9c4693b8 1397 int ipc_sockets[2];
500ed813 1398 pid_t attached_pid, pid, to_cleanup_pid;
ab919e5f 1399 struct attach_context *ctx;
9e84479f 1400 struct lxc_terminal terminal;
1cce35e6 1401 struct lxc_conf *conf;
9c4693b8 1402
908fbc1a 1403 if (!container)
540a2f70 1404 return ret_set_errno(-1, EINVAL);
908fbc1a
CB
1405
1406 if (!lxc_container_get(container))
540a2f70 1407 return ret_set_errno(-1, EINVAL);
908fbc1a
CB
1408
1409 name = container->name;
1410 lxcpath = container->config_path;
1411
afc691a0 1412 if (!options) {
9c4693b8 1413 options = &attach_static_default_options;
afc691a0
CB
1414 options->lsm_label = NULL;
1415 }
9c4693b8 1416
9745eb8a 1417 ctx = alloc_attach_context();
ab919e5f 1418 if (!ctx) {
9745eb8a
CB
1419 lxc_container_put(container);
1420 return log_error_errno(-ENOMEM, ENOMEM, "Failed to allocate attach context");
1421 }
1422
afc691a0 1423 ret = get_attach_context(ctx, container, options);
9745eb8a 1424 if (ret) {
7e995801 1425 put_attach_context(ctx);
74ce42b5 1426 return log_error(-1, "Failed to get attach context");
9c4693b8
CS
1427 }
1428
ab919e5f 1429 conf = ctx->container->lxc_conf;
ba773996 1430
ab919e5f 1431 if (!fetch_seccomp(ctx->container, options))
ae026f55 1432 WARN("Failed to get seccomp policy");
2c4ea790 1433
ab919e5f 1434 if (!no_new_privs(ctx->container, options))
ae026f55 1435 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set");
2e812c16 1436
9b31ab58 1437 ret = prepare_namespaces(ctx, options);
b7873c95 1438 if (ret) {
52ed870e 1439 put_attach_context(ctx);
74ce42b5 1440 return log_error(-1, "Failed to get namespace file descriptors");
9c4693b8
CS
1441 }
1442
9e84479f 1443 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
f797f05e 1444 ret = lxc_attach_terminal(name, lxcpath, conf, &terminal);
ba2be1a8 1445 if (ret < 0) {
dd53c8af 1446 put_attach_context(ctx);
74ce42b5 1447 return log_error(-1, "Failed to setup new terminal");
ba2be1a8
CB
1448 }
1449
9e84479f 1450 terminal.log_fd = options->log_fd;
c948657b 1451 } else {
9e84479f 1452 lxc_terminal_init(&terminal);
ba2be1a8
CB
1453 }
1454
8ce83369
CB
1455 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1456 * to make sure we don't irritate other threads that want to fork+exec
1457 * away
9c4693b8
CS
1458 *
1459 * IMPORTANT: if the initial process is multithreaded and another call
1460 * just fork()s away without exec'ing directly after, the socket fd will
1461 * exist in the forked process from the other thread and any close() in
8ce83369 1462 * our own child process will not really cause the socket to close
1d801260 1463 * properly, potentially causing the parent to hang.
9c4693b8
CS
1464 *
1465 * For this reason, while IPC is still active, we have to use shutdown()
8ce83369
CB
1466 * if the child exits prematurely in order to signal that the socket is
1467 * closed and cannot assume that the child exiting will automatically do
1468 * that.
9c4693b8
CS
1469 *
1470 * IPC mechanism: (X is receiver)
bd6a2355 1471 * initial process transient process attached process
9c4693b8
CS
1472 * X <--- send pid of
1473 * attached proc,
1474 * then exit
1475 * send 0 ------------------------------------> X
1476 * [do initialization]
1477 * X <------------------------------------ send 1
1478 * [add to cgroup, ...]
1479 * send 2 ------------------------------------> X
81f466d0
CB
1480 * [set LXC_ATTACH_NO_NEW_PRIVS]
1481 * X <------------------------------------ send 3
1482 * [open LSM label fd]
1483 * send 4 ------------------------------------> X
1484 * [set LSM label]
9c4693b8
CS
1485 * close socket close socket
1486 * run program
1487 */
1488 ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, ipc_sockets);
1489 if (ret < 0) {
dd53c8af 1490 put_attach_context(ctx);
74ce42b5 1491 return log_error_errno(-1, errno, "Could not set up required IPC mechanism for attaching");
9c4693b8
CS
1492 }
1493
bd6a2355 1494 /* Create transient process, two reasons:
e3f0e436 1495 * 1. We can't setns() in the child itself, since we want to make
8ce83369 1496 * sure we are properly attached to the pidns.
e3f0e436 1497 * 2. Also, the initial thread has to put the attached process
8ce83369
CB
1498 * into the cgroup, which we can only do if we didn't already
1499 * setns() (otherwise, user namespaces will hate us).
9c4693b8
CS
1500 */
1501 pid = fork();
9c4693b8 1502 if (pid < 0) {
dd53c8af 1503 put_attach_context(ctx);
74ce42b5 1504 return log_error_errno(-1, errno, "Failed to create first subprocess");
9c4693b8
CS
1505 }
1506
4f25e72f 1507 if (pid == 0) {
26abd7ea 1508 char *cwd, *new_cwd;
a588a482 1509
ba2be1a8 1510 /* close unneeded file descriptors */
4f25e72f 1511 close_prot_errno_disarm(ipc_sockets[0]);
2202afc9 1512
4f25e72f
CB
1513 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1514 lxc_attach_terminal_close_ptx(&terminal);
1515 lxc_attach_terminal_close_peer(&terminal);
1516 lxc_attach_terminal_close_log(&terminal);
f4364484
SG
1517 }
1518
4f25e72f 1519 /* Wait for the parent to have setup cgroups. */
6e48e7c5 1520 if (!sync_wait(ipc_sockets[1], ATTACH_SYNC_CGROUP)) {
4f25e72f 1521 shutdown(ipc_sockets[1], SHUT_RDWR);
dd53c8af 1522 put_attach_context(ctx);
4f25e72f 1523 _exit(EXIT_FAILURE);
bb2ada6f
CB
1524 }
1525
c538837d
CB
1526 if (!attach_context_security_barrier(ctx)) {
1527 shutdown(ipc_sockets[1], SHUT_RDWR);
1528 put_attach_context(ctx);
1529 _exit(EXIT_FAILURE);
1530 }
1531
a588a482
CB
1532 cwd = getcwd(NULL, 0);
1533
c538837d
CB
1534 /*
1535 * Attach now, create another subprocess later, since pid
1536 * namespaces only really affect the children of the current
1537 * process.
1538 *
1539 * Note that this is a crucial barrier. We're no moving into
1540 * the container's context so we need to make sure to not leak
1541 * anything sensitive. That especially means things such as
1542 * open file descriptors!
4f25e72f 1543 */
9b31ab58 1544 ret = attach_namespaces(ctx, options);
4f25e72f
CB
1545 if (ret < 0) {
1546 ERROR("Failed to enter namespaces");
1547 shutdown(ipc_sockets[1], SHUT_RDWR);
dd53c8af 1548 put_attach_context(ctx);
4f25e72f 1549 _exit(EXIT_FAILURE);
ba2be1a8
CB
1550 }
1551
4f25e72f
CB
1552 /* Attach succeeded, try to cwd. */
1553 if (options->initial_cwd)
1554 new_cwd = options->initial_cwd;
1555 else
1556 new_cwd = cwd;
1557 if (new_cwd) {
1558 ret = chdir(new_cwd);
1559 if (ret < 0)
1560 WARN("Could not change directory to \"%s\"", new_cwd);
ba2be1a8 1561 }
a588a482 1562 free_disarm(cwd);
c6d09e15 1563
4f25e72f 1564 /* Create attached process. */
4f25e72f
CB
1565 pid = lxc_raw_clone(CLONE_PARENT, NULL);
1566 if (pid < 0) {
1567 SYSERROR("Failed to clone attached process");
1568 shutdown(ipc_sockets[1], SHUT_RDWR);
dd53c8af 1569 put_attach_context(ctx);
4f25e72f
CB
1570 _exit(EXIT_FAILURE);
1571 }
f4364484 1572
4f25e72f 1573 if (pid == 0) {
338b230f 1574 struct attach_payload ap = {
a64902ab
CB
1575 .ipc_socket = ipc_sockets[1],
1576 .options = options,
1577 .ctx = ctx,
1578 .terminal_pts_fd = terminal.pty,
1579 .exec_function = exec_function,
1580 .exec_payload = exec_payload,
1581 };
1582
4f25e72f
CB
1583 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1584 ret = lxc_terminal_signal_sigmask_safe_blocked(&terminal);
1585 if (ret < 0) {
1586 SYSERROR("Failed to reset signal mask");
1587 _exit(EXIT_FAILURE);
1588 }
1589 }
ea918412 1590
a64902ab 1591 /* Does not return. */
338b230f 1592 do_attach(&ap);
62183f1a 1593 }
bd6a2355 1594 TRACE("Attached process %d started initializing", pid);
2eef2bda 1595
4f25e72f
CB
1596 if (options->attach_flags & LXC_ATTACH_TERMINAL)
1597 lxc_attach_terminal_close_pts(&terminal);
ea918412 1598
4f25e72f 1599 /* Tell grandparent the pid of the pid of the newly created child. */
f8e88e94 1600 if (!sync_wake_pid(ipc_sockets[1], ATTACH_SYNC_PID(pid))) {
4f25e72f
CB
1601 /* If this really happens here, this is very unfortunate, since
1602 * the parent will not know the pid of the attached process and
1603 * will not be able to wait for it (and we won't either due to
1604 * CLONE_PARENT) so the parent won't be able to reap it and the
1605 * attached process will remain a zombie.
1606 */
1607 shutdown(ipc_sockets[1], SHUT_RDWR);
dd53c8af 1608 put_attach_context(ctx);
4f25e72f
CB
1609 _exit(EXIT_FAILURE);
1610 }
9c4693b8 1611
4f25e72f 1612 /* The rest is in the hands of the initial and the attached process. */
dd53c8af 1613 put_attach_context(ctx);
4f25e72f
CB
1614 _exit(EXIT_SUCCESS);
1615 }
bd6a2355 1616 TRACE("Transient process %d started initializing", pid);
6f4f1937 1617
4f25e72f 1618 to_cleanup_pid = pid;
ea918412 1619
4f25e72f 1620 /* close unneeded file descriptors */
cb2420df 1621 close_prot_errno_disarm(ipc_sockets[1]);
9b31ab58 1622 put_namespaces(ctx);
4f25e72f
CB
1623 if (options->attach_flags & LXC_ATTACH_TERMINAL)
1624 lxc_attach_terminal_close_pts(&terminal);
81f466d0 1625
4f25e72f
CB
1626 /* Attach to cgroup, if requested. */
1627 if (options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) {
1628 /*
1629 * If this is the unified hierarchy cgroup_attach() is
1630 * enough.
1631 */
1632 ret = cgroup_attach(conf, name, lxcpath, pid);
9a57778b 1633 if (ret) {
4f25e72f 1634 call_cleaner(cgroup_exit) struct cgroup_ops *cgroup_ops = NULL;
9044b79e 1635
9a57778b
CB
1636 if (ret != -ENOCGROUP2) {
1637 SYSERROR("Failed to attach cgroup");
1638 goto on_error;
1639 }
1640
4f25e72f
CB
1641 cgroup_ops = cgroup_init(conf);
1642 if (!cgroup_ops)
1643 goto on_error;
9044b79e 1644
4f25e72f
CB
1645 if (!cgroup_ops->attach(cgroup_ops, conf, name, lxcpath, pid))
1646 goto on_error;
81f466d0 1647 }
9a57778b 1648
bd6a2355 1649 TRACE("Moved transient process %d into container cgroup", pid);
4f25e72f 1650 }
81f466d0 1651
4f25e72f
CB
1652 /* Setup /proc limits */
1653 if (!lxc_list_empty(&conf->procs)) {
1654 ret = setup_proc_filesystem(&conf->procs, pid);
1655 if (ret < 0)
1656 goto on_error;
4f3b6a85
CB
1657
1658 TRACE("Setup /proc/%d settings", pid);
4f25e72f 1659 }
cdb2a47f 1660
4f25e72f
CB
1661 /* Setup resource limits */
1662 if (!lxc_list_empty(&conf->limits)) {
1663 ret = setup_resource_limits(&conf->limits, pid);
1664 if (ret < 0)
1665 goto on_error;
4f3b6a85
CB
1666
1667 TRACE("Setup resource limits");
4f25e72f 1668 }
cdb2a47f 1669
4f25e72f
CB
1670 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1671 ret = lxc_attach_terminal_mainloop_init(&terminal, &descr);
1672 if (ret < 0)
1673 goto on_error;
9c4693b8 1674
4f25e72f
CB
1675 TRACE("Initialized terminal mainloop");
1676 }
9c4693b8 1677
4f25e72f 1678 /* Let the child process know to go ahead. */
6e48e7c5 1679 if (!sync_wake(ipc_sockets[0], ATTACH_SYNC_CGROUP))
4f25e72f 1680 goto close_mainloop;
ba2be1a8 1681
bd6a2355 1682 TRACE("Told transient process to start initializing");
ea918412 1683
bd6a2355 1684 /* Get pid of attached process from transient process. */
f8e88e94 1685 if (!sync_wait_pid(ipc_sockets[0], ATTACH_SYNC_PID(&attached_pid)))
4f25e72f 1686 goto close_mainloop;
ba2be1a8 1687
4f25e72f 1688 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid);
ba2be1a8 1689
4f25e72f 1690 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
5d2b46fb 1691 if (options->stdin_fd == STDIN_FILENO) {
4f25e72f
CB
1692 signal(SIGINT, SIG_IGN);
1693 signal(SIGQUIT, SIG_IGN);
1694 }
ba2be1a8 1695
bd6a2355 1696 /* Reap transient process. */
4f25e72f
CB
1697 ret = wait_for_pid(pid);
1698 if (ret < 0)
1699 goto close_mainloop;
ba2be1a8 1700
bd6a2355 1701 TRACE("Transient process %d exited", pid);
ea918412 1702
4f25e72f
CB
1703 /* We will always have to reap the attached process now. */
1704 to_cleanup_pid = attached_pid;
9c4693b8 1705
4f25e72f 1706 /* Open LSM fd and send it to child. */
afc691a0 1707 if (attach_lsm(options) && ctx->lsm_label) {
ad001fb6 1708 __do_close int labelfd = -EBADF;
4f25e72f 1709 bool on_exec;
ea918412 1710
4f25e72f 1711 on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? true : false;
afc691a0 1712 labelfd = ctx->lsm_ops->process_label_fd_get(ctx->lsm_ops, attached_pid, on_exec);
4f25e72f
CB
1713 if (labelfd < 0)
1714 goto close_mainloop;
9c4693b8 1715
4f25e72f 1716 TRACE("Opened LSM label file descriptor %d", labelfd);
ea918412 1717
4f25e72f 1718 /* Send child fd of the LSM security module to write to. */
f8e88e94 1719 if (!sync_wake_fd(ipc_sockets[0], ATTACH_SYNC_LSM(labelfd))) {
6e36c297 1720 SYSERROR("Failed to send lsm label fd");
4f25e72f
CB
1721 goto close_mainloop;
1722 }
1723
4f25e72f 1724 TRACE("Sent LSM label file descriptor %d to child", labelfd);
9c4693b8 1725 }
ea918412 1726
4f25e72f
CB
1727 if (conf->seccomp.seccomp) {
1728 ret = lxc_seccomp_recv_notifier_fd(&conf->seccomp, ipc_sockets[0]);
1729 if (ret < 0)
1730 goto close_mainloop;
9c4693b8 1731
4f25e72f 1732 ret = lxc_seccomp_add_notifier(name, lxcpath, &conf->seccomp);
d6d979bc 1733 if (ret < 0)
4f25e72f 1734 goto close_mainloop;
d6d979bc 1735 }
9c4693b8 1736
4f25e72f
CB
1737 /* We're done, the child process should now execute whatever it
1738 * is that the user requested. The parent can now track it with
1739 * waitpid() or similar.
1740 */
9c4693b8 1741
4f25e72f 1742 *attached_process = attached_pid;
a998454a 1743
4f25e72f
CB
1744 /* Now shut down communication with child, we're done. */
1745 shutdown(ipc_sockets[0], SHUT_RDWR);
cb2420df 1746 close_prot_errno_disarm(ipc_sockets[0]);
f157b056 1747
4f25e72f
CB
1748 ret_parent = 0;
1749 to_cleanup_pid = -1;
ea918412 1750
4f25e72f
CB
1751 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1752 ret = lxc_mainloop(&descr, -1);
1753 if (ret < 0) {
1754 ret_parent = -1;
1755 to_cleanup_pid = attached_pid;
1756 }
a998454a 1757 }
ea918412 1758
4f25e72f 1759close_mainloop:
9e84479f 1760 if (options->attach_flags & LXC_ATTACH_TERMINAL)
4f25e72f 1761 lxc_mainloop_close(&descr);
9c4693b8 1762
4f25e72f
CB
1763on_error:
1764 if (ipc_sockets[0] >= 0) {
1765 shutdown(ipc_sockets[0], SHUT_RDWR);
cb2420df 1766 close_prot_errno_disarm(ipc_sockets[0]);
9c4693b8 1767 }
ea918412 1768
4f25e72f
CB
1769 if (to_cleanup_pid > 0)
1770 (void)wait_for_pid(to_cleanup_pid);
1771
1772 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1773 lxc_terminal_delete(&terminal);
1774 lxc_terminal_conf_free(&terminal);
1775 }
9c4693b8 1776
dd53c8af 1777 put_attach_context(ctx);
4f25e72f 1778 return ret_parent;
9c4693b8
CS
1779}
1780
06346bb0 1781int lxc_attach_run_command(void *payload)
9c4693b8 1782{
06346bb0
CB
1783 int ret = -1;
1784 lxc_attach_command_t *cmd = payload;
9c4693b8 1785
06346bb0
CB
1786 ret = execvp(cmd->program, cmd->argv);
1787 if (ret < 0) {
1788 switch (errno) {
1789 case ENOEXEC:
1790 ret = 126;
cf0fd972 1791 break;
06346bb0
CB
1792 case ENOENT:
1793 ret = 127;
cf0fd972 1794 break;
06346bb0
CB
1795 }
1796 }
ea918412 1797
c2af3a15 1798 return log_error_errno(ret, errno, "Failed to exec \"%s\"", cmd->program);
9c4693b8
CS
1799}
1800
1801int lxc_attach_run_shell(void* payload)
1802{
cd8f5663 1803 __do_free char *buf = NULL;
9c4693b8 1804 uid_t uid;
cb7aa5e8
DJ
1805 struct passwd pwent;
1806 struct passwd *pwentp = NULL;
9c4693b8 1807 char *user_shell;
cb7aa5e8
DJ
1808 size_t bufsize;
1809 int ret;
9c4693b8 1810
8ce83369 1811 /* Ignore payload parameter. */
9c4693b8
CS
1812 (void)payload;
1813
1814 uid = getuid();
cb7aa5e8
DJ
1815
1816 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1817 if (bufsize == -1)
1818 bufsize = 1024;
1819
1820 buf = malloc(bufsize);
1821 if (buf) {
1822 ret = getpwuid_r(uid, &pwent, buf, bufsize, &pwentp);
1823 if (!pwentp) {
1824 if (ret == 0)
ea918412 1825 WARN("Could not find matched password record");
cb7aa5e8
DJ
1826
1827 WARN("Failed to get password record - %u", uid);
1828 }
1829 }
9c4693b8 1830
8ce83369
CB
1831 /* This probably happens because of incompatible nss implementations in
1832 * host and container (remember, this code is still using the host's
1833 * glibc but our mount namespace is in the container) we may try to get
1834 * the information by spawning a [getent passwd uid] process and parsing
1835 * the result.
9c4693b8 1836 */
cb7aa5e8 1837 if (!pwentp)
9c4693b8
CS
1838 user_shell = lxc_attach_getpwshell(uid);
1839 else
cb7aa5e8 1840 user_shell = pwent.pw_shell;
ea918412 1841
9c4693b8 1842 if (user_shell)
acf47e1b 1843 execlp(user_shell, user_shell, (char *)NULL);
9c4693b8 1844
8ce83369
CB
1845 /* Executed if either no passwd entry or execvp fails, we will fall back
1846 * on /bin/sh as a default shell.
9c4693b8 1847 */
acf47e1b 1848 execlp("/bin/sh", "/bin/sh", (char *)NULL);
ea918412 1849
edeb1836 1850 SYSERROR("Failed to execute shell");
cb7aa5e8 1851 if (!pwentp)
edeb1836 1852 free(user_shell);
ea918412 1853
9c4693b8
CS
1854 return -1;
1855}