]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/attach.c
attach_options: use standard C pointer syntax
[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
6f0c2cea 119 ret = snprintf(path + STRLITERALLEN("fdinfo/"), INTTYPE_TO_STRLEN(int), "%d", pidfd);
d8764025
CB
120 if (ret < 0 || ret > (size_t)INTTYPE_TO_STRLEN(int))
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
c538837d
CB
406 ret = snprintf(path, sizeof(path), "/proc/%d", ctx->init_pid);
407 if (ret < 0 || ret >= sizeof(path))
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
657256e0 737 ret = mount_filesystem("proc", "/proc", 0);
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. */
657256e0 750 if (ret == 0 && mount_filesystem("sysfs", "/sys", 0))
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. */
3fa23ac3
CB
950 ret = snprintf(uid_buf, sizeof(uid_buf), "%ld", (long)uid);
951 if (ret <= 0 || ret >= sizeof(uid_buf))
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
8caac583
RJ
1207 if (options->attach_flags & LXC_ATTACH_SETGROUPS && options->groups.size > 0) {
1208 if (!lxc_setgroups(options->groups.list, options->groups.size))
1209 goto on_error;
1210 } else {
1211 if (!lxc_drop_groups() && errno != EPERM)
1212 goto on_error;
1213 }
b58214ac 1214
4475fabb 1215 if (options->namespaces & CLONE_NEWUSER)
3ac4480a 1216 if (!lxc_switch_uid_gid(ctx->setup_ns_uid, ctx->setup_ns_gid))
b75c344c 1217 goto on_error;
936efc72 1218
afc691a0 1219 if (attach_lsm(options) && ctx->lsm_label) {
d3ba7c98 1220 bool on_exec;
a998454a
CB
1221
1222 /* Change into our new LSM profile. */
d3ba7c98 1223 on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? true : false;
afc691a0 1224 ret = ctx->lsm_ops->process_label_set_at(ctx->lsm_ops, lsm_fd, ctx->lsm_label, on_exec);
cb2420df 1225 close_prot_errno_disarm(lsm_fd);
b75c344c
CB
1226 if (ret < 0)
1227 goto on_error;
ea918412 1228
ab919e5f 1229 TRACE("Set %s LSM label to \"%s\"", ctx->lsm_ops->name, ctx->lsm_label);
a998454a
CB
1230 }
1231
640952e5 1232 if (conf->no_new_privs || (options->attach_flags & LXC_ATTACH_NO_NEW_PRIVS)) {
6ce8e678
AL
1233 ret = prctl(PR_SET_NO_NEW_PRIVS, prctl_arg(1), prctl_arg(0),
1234 prctl_arg(0), prctl_arg(0));
1235 if (ret < 0)
1236 goto on_error;
1237
1238 TRACE("Set PR_SET_NO_NEW_PRIVS");
1239 }
1240
a998454a
CB
1241 /* The following is done after the communication socket is shut down.
1242 * That way, all errors that might (though unlikely) occur up until this
1243 * point will have their messages printed to the original stderr (if
1244 * logging is so configured) and not the fd the user supplied, if any.
1245 */
1246
1247 /* Fd handling for stdin, stdout and stderr; ignore errors here, user
1248 * may want to make sure the fds are closed, for example.
1249 */
08ea9270 1250 if (options->stdin_fd >= 0 && options->stdin_fd != STDIN_FILENO)
40301d48 1251 if (dup2(options->stdin_fd, STDIN_FILENO) < 0)
a7563434 1252 SYSDEBUG("Failed to replace stdin with %d", options->stdin_fd);
08ea9270
CB
1253
1254 if (options->stdout_fd >= 0 && options->stdout_fd != STDOUT_FILENO)
40301d48 1255 if (dup2(options->stdout_fd, STDOUT_FILENO) < 0)
93b9960a 1256 SYSDEBUG("Failed to replace stdout with %d", options->stdout_fd);
08ea9270
CB
1257
1258 if (options->stderr_fd >= 0 && options->stderr_fd != STDERR_FILENO)
40301d48 1259 if (dup2(options->stderr_fd, STDERR_FILENO) < 0)
93b9960a 1260 SYSDEBUG("Failed to replace stderr with %d", options->stderr_fd);
a998454a
CB
1261
1262 /* close the old fds */
08ea9270 1263 if (options->stdin_fd > STDERR_FILENO)
a998454a 1264 close(options->stdin_fd);
08ea9270
CB
1265
1266 if (options->stdout_fd > STDERR_FILENO)
a998454a 1267 close(options->stdout_fd);
08ea9270
CB
1268
1269 if (options->stderr_fd > STDERR_FILENO)
a998454a
CB
1270 close(options->stderr_fd);
1271
427a8067
CB
1272 /*
1273 * Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
a998454a
CB
1274 * here, ignore errors.
1275 */
427a8067 1276 for (int fd = STDIN_FILENO; fd <= STDERR_FILENO; fd++) {
3f62938a 1277 ret = fd_cloexec(fd, false);
b75c344c
CB
1278 if (ret < 0) {
1279 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd);
1280 goto on_error;
1281 }
a998454a
CB
1282 }
1283
9e84479f 1284 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
338b230f 1285 ret = lxc_terminal_prepare_login(ap->terminal_pts_fd);
ba2be1a8 1286 if (ret < 0) {
338b230f 1287 SYSERROR("Failed to prepare terminal file descriptor %d", ap->terminal_pts_fd);
ba2be1a8
CB
1288 goto on_error;
1289 }
ea918412 1290
338b230f 1291 TRACE("Prepared terminal file descriptor %d", ap->terminal_pts_fd);
ba2be1a8
CB
1292 }
1293
4475fabb 1294 /* Avoid unnecessary syscalls. */
3ac4480a
CB
1295 if (ctx->setup_ns_uid == ctx->target_ns_uid)
1296 ctx->target_ns_uid = LXC_INVALID_UID;
1297
1298 if (ctx->setup_ns_gid == ctx->target_ns_gid)
1299 ctx->target_ns_gid = LXC_INVALID_GID;
4475fabb 1300
3ac4480a
CB
1301 /*
1302 * Make sure that the processes STDIO is correctly owned by the user
1303 * that we are switching to.
1304 */
1305 ret = fix_stdio_permissions(ctx->target_ns_uid);
1306 if (ret)
1307 INFO("Failed to adjust stdio permissions");
4475fabb 1308
e18aba7d
CB
1309 if (conf->seccomp.seccomp) {
1310 ret = lxc_seccomp_load(conf);
1311 if (ret < 0)
1312 goto on_error;
1313
1314 TRACE("Loaded seccomp profile");
1315
1316 ret = lxc_seccomp_send_notifier_fd(&conf->seccomp, ap->ipc_socket);
1317 if (ret < 0)
1318 goto on_error;
c5bac506 1319 lxc_seccomp_close_notifier_fd(&conf->seccomp);
e18aba7d
CB
1320 }
1321
3ac4480a 1322 if (!lxc_switch_uid_gid(ctx->target_ns_uid, ctx->target_ns_gid))
936efc72
CB
1323 goto on_error;
1324
cd5f35ec
CB
1325 put_attach_payload(ap);
1326
a998454a 1327 /* We're done, so we can now do whatever the user intended us to do. */
afc691a0 1328 _exit(attach_function(attach_function_args));
b75c344c
CB
1329
1330on_error:
dab02267 1331 ERROR("Failed to attach to container");
cd5f35ec 1332 put_attach_payload(ap);
c7ac2e1c 1333 _exit(EXIT_FAILURE);
a998454a
CB
1334}
1335
f797f05e 1336static int lxc_attach_terminal(const char *name, const char *lxcpath, struct lxc_conf *conf,
9e84479f 1337 struct lxc_terminal *terminal)
ba2be1a8
CB
1338{
1339 int ret;
1340
9e84479f 1341 lxc_terminal_init(terminal);
ba2be1a8 1342
8ea93a0f 1343 ret = lxc_terminal_create(name, lxcpath, conf, terminal);
c2af3a15
CB
1344 if (ret < 0)
1345 return log_error(-1, "Failed to create terminal");
ba2be1a8 1346
ba2be1a8 1347 return 0;
ba2be1a8
CB
1348}
1349
9e84479f
CB
1350static int lxc_attach_terminal_mainloop_init(struct lxc_terminal *terminal,
1351 struct lxc_epoll_descr *descr)
ba2be1a8
CB
1352{
1353 int ret;
1354
1355 ret = lxc_mainloop_open(descr);
c2af3a15
CB
1356 if (ret < 0)
1357 return log_error(-1, "Failed to create mainloop");
ba2be1a8 1358
9e84479f 1359 ret = lxc_terminal_mainloop_add(descr, terminal);
ba2be1a8 1360 if (ret < 0) {
ba2be1a8 1361 lxc_mainloop_close(descr);
c2af3a15 1362 return log_error(-1, "Failed to add handlers to mainloop");
ba2be1a8
CB
1363 }
1364
1365 return 0;
1366}
1367
36a94ce8 1368static inline void lxc_attach_terminal_close_ptx(struct lxc_terminal *terminal)
ba2be1a8 1369{
36a94ce8 1370 close_prot_errno_disarm(terminal->ptx);
ba2be1a8
CB
1371}
1372
cecf3e83 1373static inline void lxc_attach_terminal_close_pts(struct lxc_terminal *terminal)
ba2be1a8 1374{
41808e20 1375 close_prot_errno_disarm(terminal->pty);
ba2be1a8
CB
1376}
1377
9e84479f 1378static inline void lxc_attach_terminal_close_peer(struct lxc_terminal *terminal)
ba2be1a8 1379{
19a3e906 1380 close_prot_errno_disarm(terminal->peer);
ba2be1a8
CB
1381}
1382
9e84479f 1383static inline void lxc_attach_terminal_close_log(struct lxc_terminal *terminal)
ba2be1a8 1384{
19a3e906 1385 close_prot_errno_disarm(terminal->log_fd);
ba2be1a8
CB
1386}
1387
908fbc1a
CB
1388int lxc_attach(struct lxc_container *container, lxc_attach_exec_t exec_function,
1389 void *exec_payload, lxc_attach_options_t *options,
1390 pid_t *attached_process)
9c4693b8 1391{
6f9fe5d0 1392 int ret_parent = -1;
6f9fe5d0 1393 struct lxc_epoll_descr descr = {};
a9f0cecf 1394 int ret;
26abd7ea 1395 char *name, *lxcpath;
9c4693b8 1396 int ipc_sockets[2];
500ed813 1397 pid_t attached_pid, pid, to_cleanup_pid;
ab919e5f 1398 struct attach_context *ctx;
9e84479f 1399 struct lxc_terminal terminal;
1cce35e6 1400 struct lxc_conf *conf;
9c4693b8 1401
908fbc1a 1402 if (!container)
540a2f70 1403 return ret_set_errno(-1, EINVAL);
908fbc1a
CB
1404
1405 if (!lxc_container_get(container))
540a2f70 1406 return ret_set_errno(-1, EINVAL);
908fbc1a
CB
1407
1408 name = container->name;
1409 lxcpath = container->config_path;
1410
afc691a0 1411 if (!options) {
9c4693b8 1412 options = &attach_static_default_options;
afc691a0
CB
1413 options->lsm_label = NULL;
1414 }
9c4693b8 1415
9745eb8a 1416 ctx = alloc_attach_context();
ab919e5f 1417 if (!ctx) {
9745eb8a
CB
1418 lxc_container_put(container);
1419 return log_error_errno(-ENOMEM, ENOMEM, "Failed to allocate attach context");
1420 }
1421
afc691a0 1422 ret = get_attach_context(ctx, container, options);
9745eb8a 1423 if (ret) {
7e995801 1424 put_attach_context(ctx);
74ce42b5 1425 return log_error(-1, "Failed to get attach context");
9c4693b8
CS
1426 }
1427
ab919e5f 1428 conf = ctx->container->lxc_conf;
ba773996 1429
ab919e5f 1430 if (!fetch_seccomp(ctx->container, options))
ae026f55 1431 WARN("Failed to get seccomp policy");
2c4ea790 1432
ab919e5f 1433 if (!no_new_privs(ctx->container, options))
ae026f55 1434 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set");
2e812c16 1435
9b31ab58 1436 ret = prepare_namespaces(ctx, options);
b7873c95 1437 if (ret) {
52ed870e 1438 put_attach_context(ctx);
74ce42b5 1439 return log_error(-1, "Failed to get namespace file descriptors");
9c4693b8
CS
1440 }
1441
9e84479f 1442 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
f797f05e 1443 ret = lxc_attach_terminal(name, lxcpath, conf, &terminal);
ba2be1a8 1444 if (ret < 0) {
dd53c8af 1445 put_attach_context(ctx);
74ce42b5 1446 return log_error(-1, "Failed to setup new terminal");
ba2be1a8
CB
1447 }
1448
9e84479f 1449 terminal.log_fd = options->log_fd;
c948657b 1450 } else {
9e84479f 1451 lxc_terminal_init(&terminal);
ba2be1a8
CB
1452 }
1453
8ce83369
CB
1454 /* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
1455 * to make sure we don't irritate other threads that want to fork+exec
1456 * away
9c4693b8
CS
1457 *
1458 * IMPORTANT: if the initial process is multithreaded and another call
1459 * just fork()s away without exec'ing directly after, the socket fd will
1460 * exist in the forked process from the other thread and any close() in
8ce83369 1461 * our own child process will not really cause the socket to close
1d801260 1462 * properly, potentially causing the parent to hang.
9c4693b8
CS
1463 *
1464 * For this reason, while IPC is still active, we have to use shutdown()
8ce83369
CB
1465 * if the child exits prematurely in order to signal that the socket is
1466 * closed and cannot assume that the child exiting will automatically do
1467 * that.
9c4693b8
CS
1468 *
1469 * IPC mechanism: (X is receiver)
1470 * initial process intermediate attached
1471 * X <--- send pid of
1472 * attached proc,
1473 * then exit
1474 * send 0 ------------------------------------> X
1475 * [do initialization]
1476 * X <------------------------------------ send 1
1477 * [add to cgroup, ...]
1478 * send 2 ------------------------------------> X
81f466d0
CB
1479 * [set LXC_ATTACH_NO_NEW_PRIVS]
1480 * X <------------------------------------ send 3
1481 * [open LSM label fd]
1482 * send 4 ------------------------------------> X
1483 * [set LSM label]
9c4693b8
CS
1484 * close socket close socket
1485 * run program
1486 */
1487 ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, ipc_sockets);
1488 if (ret < 0) {
dd53c8af 1489 put_attach_context(ctx);
74ce42b5 1490 return log_error_errno(-1, errno, "Could not set up required IPC mechanism for attaching");
9c4693b8
CS
1491 }
1492
e3f0e436
CB
1493 /* Create intermediate subprocess, two reasons:
1494 * 1. We can't setns() in the child itself, since we want to make
8ce83369 1495 * sure we are properly attached to the pidns.
e3f0e436 1496 * 2. Also, the initial thread has to put the attached process
8ce83369
CB
1497 * into the cgroup, which we can only do if we didn't already
1498 * setns() (otherwise, user namespaces will hate us).
9c4693b8
CS
1499 */
1500 pid = fork();
9c4693b8 1501 if (pid < 0) {
dd53c8af 1502 put_attach_context(ctx);
74ce42b5 1503 return log_error_errno(-1, errno, "Failed to create first subprocess");
9c4693b8
CS
1504 }
1505
4f25e72f 1506 if (pid == 0) {
26abd7ea 1507 char *cwd, *new_cwd;
a588a482 1508
ba2be1a8 1509 /* close unneeded file descriptors */
4f25e72f 1510 close_prot_errno_disarm(ipc_sockets[0]);
2202afc9 1511
4f25e72f
CB
1512 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1513 lxc_attach_terminal_close_ptx(&terminal);
1514 lxc_attach_terminal_close_peer(&terminal);
1515 lxc_attach_terminal_close_log(&terminal);
f4364484
SG
1516 }
1517
4f25e72f 1518 /* Wait for the parent to have setup cgroups. */
6e48e7c5 1519 if (!sync_wait(ipc_sockets[1], ATTACH_SYNC_CGROUP)) {
4f25e72f 1520 shutdown(ipc_sockets[1], SHUT_RDWR);
dd53c8af 1521 put_attach_context(ctx);
4f25e72f 1522 _exit(EXIT_FAILURE);
bb2ada6f
CB
1523 }
1524
c538837d
CB
1525 if (!attach_context_security_barrier(ctx)) {
1526 shutdown(ipc_sockets[1], SHUT_RDWR);
1527 put_attach_context(ctx);
1528 _exit(EXIT_FAILURE);
1529 }
1530
4f25e72f
CB
1531 TRACE("Intermediate process starting to initialize");
1532
a588a482
CB
1533 cwd = getcwd(NULL, 0);
1534
c538837d
CB
1535 /*
1536 * Attach now, create another subprocess later, since pid
1537 * namespaces only really affect the children of the current
1538 * process.
1539 *
1540 * Note that this is a crucial barrier. We're no moving into
1541 * the container's context so we need to make sure to not leak
1542 * anything sensitive. That especially means things such as
1543 * open file descriptors!
4f25e72f 1544 */
9b31ab58 1545 ret = attach_namespaces(ctx, options);
4f25e72f
CB
1546 if (ret < 0) {
1547 ERROR("Failed to enter namespaces");
1548 shutdown(ipc_sockets[1], SHUT_RDWR);
dd53c8af 1549 put_attach_context(ctx);
4f25e72f 1550 _exit(EXIT_FAILURE);
ba2be1a8
CB
1551 }
1552
4f25e72f
CB
1553 /* Attach succeeded, try to cwd. */
1554 if (options->initial_cwd)
1555 new_cwd = options->initial_cwd;
1556 else
1557 new_cwd = cwd;
1558 if (new_cwd) {
1559 ret = chdir(new_cwd);
1560 if (ret < 0)
1561 WARN("Could not change directory to \"%s\"", new_cwd);
ba2be1a8 1562 }
a588a482 1563 free_disarm(cwd);
c6d09e15 1564
4f25e72f 1565 /* Create attached process. */
4f25e72f
CB
1566 pid = lxc_raw_clone(CLONE_PARENT, NULL);
1567 if (pid < 0) {
1568 SYSERROR("Failed to clone attached process");
1569 shutdown(ipc_sockets[1], SHUT_RDWR);
dd53c8af 1570 put_attach_context(ctx);
4f25e72f
CB
1571 _exit(EXIT_FAILURE);
1572 }
f4364484 1573
4f25e72f 1574 if (pid == 0) {
338b230f 1575 struct attach_payload ap = {
a64902ab
CB
1576 .ipc_socket = ipc_sockets[1],
1577 .options = options,
1578 .ctx = ctx,
1579 .terminal_pts_fd = terminal.pty,
1580 .exec_function = exec_function,
1581 .exec_payload = exec_payload,
1582 };
1583
4f25e72f
CB
1584 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1585 ret = lxc_terminal_signal_sigmask_safe_blocked(&terminal);
1586 if (ret < 0) {
1587 SYSERROR("Failed to reset signal mask");
1588 _exit(EXIT_FAILURE);
1589 }
1590 }
ea918412 1591
a64902ab 1592 /* Does not return. */
338b230f 1593 do_attach(&ap);
62183f1a 1594 }
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 TRACE("Sending pid %d of attached process", pid);
9c4693b8 1613
4f25e72f 1614 /* The rest is in the hands of the initial and the attached process. */
dd53c8af 1615 put_attach_context(ctx);
4f25e72f
CB
1616 _exit(EXIT_SUCCESS);
1617 }
6f4f1937 1618
4f25e72f 1619 to_cleanup_pid = pid;
ea918412 1620
4f25e72f 1621 /* close unneeded file descriptors */
cb2420df 1622 close_prot_errno_disarm(ipc_sockets[1]);
9b31ab58 1623 put_namespaces(ctx);
4f25e72f
CB
1624 if (options->attach_flags & LXC_ATTACH_TERMINAL)
1625 lxc_attach_terminal_close_pts(&terminal);
81f466d0 1626
4f25e72f
CB
1627 /* Attach to cgroup, if requested. */
1628 if (options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) {
1629 /*
1630 * If this is the unified hierarchy cgroup_attach() is
1631 * enough.
1632 */
1633 ret = cgroup_attach(conf, name, lxcpath, pid);
9a57778b 1634 if (ret) {
4f25e72f 1635 call_cleaner(cgroup_exit) struct cgroup_ops *cgroup_ops = NULL;
9044b79e 1636
9a57778b
CB
1637 if (ret != -ENOCGROUP2) {
1638 SYSERROR("Failed to attach cgroup");
1639 goto on_error;
1640 }
1641
4f25e72f
CB
1642 cgroup_ops = cgroup_init(conf);
1643 if (!cgroup_ops)
1644 goto on_error;
9044b79e 1645
4f25e72f
CB
1646 if (!cgroup_ops->attach(cgroup_ops, conf, name, lxcpath, pid))
1647 goto on_error;
81f466d0 1648 }
9a57778b 1649
4f25e72f
CB
1650 TRACE("Moved intermediate process %d into container's cgroups", pid);
1651 }
81f466d0 1652
4f25e72f
CB
1653 /* Setup /proc limits */
1654 if (!lxc_list_empty(&conf->procs)) {
1655 ret = setup_proc_filesystem(&conf->procs, pid);
1656 if (ret < 0)
1657 goto on_error;
4f3b6a85
CB
1658
1659 TRACE("Setup /proc/%d settings", pid);
4f25e72f 1660 }
cdb2a47f 1661
4f25e72f
CB
1662 /* Setup resource limits */
1663 if (!lxc_list_empty(&conf->limits)) {
1664 ret = setup_resource_limits(&conf->limits, pid);
1665 if (ret < 0)
1666 goto on_error;
4f3b6a85
CB
1667
1668 TRACE("Setup resource limits");
4f25e72f 1669 }
cdb2a47f 1670
4f25e72f
CB
1671 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1672 ret = lxc_attach_terminal_mainloop_init(&terminal, &descr);
1673 if (ret < 0)
1674 goto on_error;
9c4693b8 1675
4f25e72f
CB
1676 TRACE("Initialized terminal mainloop");
1677 }
9c4693b8 1678
4f25e72f 1679 /* Let the child process know to go ahead. */
6e48e7c5 1680 if (!sync_wake(ipc_sockets[0], ATTACH_SYNC_CGROUP))
4f25e72f 1681 goto close_mainloop;
ba2be1a8 1682
4f25e72f 1683 TRACE("Told intermediate process to start initializing");
ea918412 1684
4f25e72f 1685 /* Get pid of attached process from intermediate process. */
f8e88e94 1686 if (!sync_wait_pid(ipc_sockets[0], ATTACH_SYNC_PID(&attached_pid)))
4f25e72f 1687 goto close_mainloop;
ba2be1a8 1688
4f25e72f 1689 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid);
ba2be1a8 1690
4f25e72f 1691 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
5d2b46fb 1692 if (options->stdin_fd == STDIN_FILENO) {
4f25e72f
CB
1693 signal(SIGINT, SIG_IGN);
1694 signal(SIGQUIT, SIG_IGN);
1695 }
ba2be1a8 1696
4f25e72f
CB
1697 /* Reap intermediate process. */
1698 ret = wait_for_pid(pid);
1699 if (ret < 0)
1700 goto close_mainloop;
ba2be1a8 1701
4f25e72f 1702 TRACE("Intermediate process %d exited", pid);
ea918412 1703
4f25e72f
CB
1704 /* We will always have to reap the attached process now. */
1705 to_cleanup_pid = attached_pid;
9c4693b8 1706
4f25e72f 1707 /* Open LSM fd and send it to child. */
afc691a0 1708 if (attach_lsm(options) && ctx->lsm_label) {
ad001fb6 1709 __do_close int labelfd = -EBADF;
4f25e72f 1710 bool on_exec;
ea918412 1711
4f25e72f 1712 on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? true : false;
afc691a0 1713 labelfd = ctx->lsm_ops->process_label_fd_get(ctx->lsm_ops, attached_pid, on_exec);
4f25e72f
CB
1714 if (labelfd < 0)
1715 goto close_mainloop;
9c4693b8 1716
4f25e72f 1717 TRACE("Opened LSM label file descriptor %d", labelfd);
ea918412 1718
4f25e72f 1719 /* Send child fd of the LSM security module to write to. */
f8e88e94 1720 if (!sync_wake_fd(ipc_sockets[0], ATTACH_SYNC_LSM(labelfd))) {
6e36c297 1721 SYSERROR("Failed to send lsm label fd");
4f25e72f
CB
1722 goto close_mainloop;
1723 }
1724
4f25e72f 1725 TRACE("Sent LSM label file descriptor %d to child", labelfd);
9c4693b8 1726 }
ea918412 1727
4f25e72f
CB
1728 if (conf->seccomp.seccomp) {
1729 ret = lxc_seccomp_recv_notifier_fd(&conf->seccomp, ipc_sockets[0]);
1730 if (ret < 0)
1731 goto close_mainloop;
9c4693b8 1732
4f25e72f 1733 ret = lxc_seccomp_add_notifier(name, lxcpath, &conf->seccomp);
d6d979bc 1734 if (ret < 0)
4f25e72f 1735 goto close_mainloop;
d6d979bc 1736 }
9c4693b8 1737
4f25e72f
CB
1738 /* We're done, the child process should now execute whatever it
1739 * is that the user requested. The parent can now track it with
1740 * waitpid() or similar.
1741 */
9c4693b8 1742
4f25e72f 1743 *attached_process = attached_pid;
a998454a 1744
4f25e72f
CB
1745 /* Now shut down communication with child, we're done. */
1746 shutdown(ipc_sockets[0], SHUT_RDWR);
cb2420df 1747 close_prot_errno_disarm(ipc_sockets[0]);
f157b056 1748
4f25e72f
CB
1749 ret_parent = 0;
1750 to_cleanup_pid = -1;
ea918412 1751
4f25e72f
CB
1752 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1753 ret = lxc_mainloop(&descr, -1);
1754 if (ret < 0) {
1755 ret_parent = -1;
1756 to_cleanup_pid = attached_pid;
1757 }
a998454a 1758 }
ea918412 1759
4f25e72f 1760close_mainloop:
9e84479f 1761 if (options->attach_flags & LXC_ATTACH_TERMINAL)
4f25e72f 1762 lxc_mainloop_close(&descr);
9c4693b8 1763
4f25e72f
CB
1764on_error:
1765 if (ipc_sockets[0] >= 0) {
1766 shutdown(ipc_sockets[0], SHUT_RDWR);
cb2420df 1767 close_prot_errno_disarm(ipc_sockets[0]);
9c4693b8 1768 }
ea918412 1769
4f25e72f
CB
1770 if (to_cleanup_pid > 0)
1771 (void)wait_for_pid(to_cleanup_pid);
1772
1773 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1774 lxc_terminal_delete(&terminal);
1775 lxc_terminal_conf_free(&terminal);
1776 }
9c4693b8 1777
dd53c8af 1778 put_attach_context(ctx);
4f25e72f 1779 return ret_parent;
9c4693b8
CS
1780}
1781
06346bb0 1782int lxc_attach_run_command(void *payload)
9c4693b8 1783{
06346bb0
CB
1784 int ret = -1;
1785 lxc_attach_command_t *cmd = payload;
9c4693b8 1786
06346bb0
CB
1787 ret = execvp(cmd->program, cmd->argv);
1788 if (ret < 0) {
1789 switch (errno) {
1790 case ENOEXEC:
1791 ret = 126;
cf0fd972 1792 break;
06346bb0
CB
1793 case ENOENT:
1794 ret = 127;
cf0fd972 1795 break;
06346bb0
CB
1796 }
1797 }
ea918412 1798
c2af3a15 1799 return log_error_errno(ret, errno, "Failed to exec \"%s\"", cmd->program);
9c4693b8
CS
1800}
1801
1802int lxc_attach_run_shell(void* payload)
1803{
cd8f5663 1804 __do_free char *buf = NULL;
9c4693b8 1805 uid_t uid;
cb7aa5e8
DJ
1806 struct passwd pwent;
1807 struct passwd *pwentp = NULL;
9c4693b8 1808 char *user_shell;
cb7aa5e8
DJ
1809 size_t bufsize;
1810 int ret;
9c4693b8 1811
8ce83369 1812 /* Ignore payload parameter. */
9c4693b8
CS
1813 (void)payload;
1814
1815 uid = getuid();
cb7aa5e8
DJ
1816
1817 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1818 if (bufsize == -1)
1819 bufsize = 1024;
1820
1821 buf = malloc(bufsize);
1822 if (buf) {
1823 ret = getpwuid_r(uid, &pwent, buf, bufsize, &pwentp);
1824 if (!pwentp) {
1825 if (ret == 0)
ea918412 1826 WARN("Could not find matched password record");
cb7aa5e8
DJ
1827
1828 WARN("Failed to get password record - %u", uid);
1829 }
1830 }
9c4693b8 1831
8ce83369
CB
1832 /* This probably happens because of incompatible nss implementations in
1833 * host and container (remember, this code is still using the host's
1834 * glibc but our mount namespace is in the container) we may try to get
1835 * the information by spawning a [getent passwd uid] process and parsing
1836 * the result.
9c4693b8 1837 */
cb7aa5e8 1838 if (!pwentp)
9c4693b8
CS
1839 user_shell = lxc_attach_getpwshell(uid);
1840 else
cb7aa5e8 1841 user_shell = pwent.pw_shell;
ea918412 1842
9c4693b8 1843 if (user_shell)
acf47e1b 1844 execlp(user_shell, user_shell, (char *)NULL);
9c4693b8 1845
8ce83369
CB
1846 /* Executed if either no passwd entry or execvp fails, we will fall back
1847 * on /bin/sh as a default shell.
9c4693b8 1848 */
acf47e1b 1849 execlp("/bin/sh", "/bin/sh", (char *)NULL);
ea918412 1850
edeb1836 1851 SYSERROR("Failed to execute shell");
cb7aa5e8 1852 if (!pwentp)
edeb1836 1853 free(user_shell);
ea918412 1854
9c4693b8
CS
1855 return -1;
1856}