]> git.proxmox.com Git - mirror_lxc.git/blame_incremental - src/lxc/attach.c
Merge pull request #3666 from brauner/2021-02-11/fixes
[mirror_lxc.git] / src / lxc / attach.c
... / ...
CommitLineData
1/* SPDX-License-Identifier: LGPL-2.1+ */
2
3#ifndef _GNU_SOURCE
4#define _GNU_SOURCE 1
5#endif
6#include <errno.h>
7#include <fcntl.h>
8#include <grp.h>
9#include <linux/unistd.h>
10#include <pwd.h>
11#include <pthread.h>
12#include <signal.h>
13#include <stdio.h>
14#include <stdlib.h>
15#include <string.h>
16#include <sys/mount.h>
17#include <sys/param.h>
18#include <sys/prctl.h>
19#include <sys/socket.h>
20#include <sys/syscall.h>
21#include <sys/wait.h>
22#include <termios.h>
23#include <unistd.h>
24
25#include <lxc/lxccontainer.h>
26
27#include "af_unix.h"
28#include "attach.h"
29#include "caps.h"
30#include "cgroup.h"
31#include "commands.h"
32#include "conf.h"
33#include "config.h"
34#include "confile.h"
35#include "log.h"
36#include "lsm/lsm.h"
37#include "lxclock.h"
38#include "lxcseccomp.h"
39#include "macro.h"
40#include "mainloop.h"
41#include "memory_utils.h"
42#include "mount_utils.h"
43#include "namespace.h"
44#include "process_utils.h"
45#include "sync.h"
46#include "syscall_wrappers.h"
47#include "terminal.h"
48#include "utils.h"
49
50#if HAVE_SYS_PERSONALITY_H
51#include <sys/personality.h>
52#endif
53
54lxc_log_define(attach, lxc);
55
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
59/*
60 * The context used to attach to the container.
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
86 */
87struct attach_context {
88 unsigned int attach_flags;
89 int init_pid;
90 int init_pidfd;
91 int dfd_init_pid;
92 int dfd_self_pid;
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;
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
108static pid_t pidfd_get_pid(int dfd_init_pid, int pidfd)
109{
110 __do_free char *line = NULL;
111 __do_fclose FILE *f = NULL;
112 size_t len = 0;
113 char path[STRLITERALLEN("fdinfo/") + INTTYPE_TO_STRLEN(int) + 1 ] = "fdinfo/";
114 int ret;
115
116 if (dfd_init_pid < 0 || pidfd < 0)
117 return ret_errno(EBADF);
118
119 ret = strnprintf(path + STRLITERALLEN("fdinfo/"), INTTYPE_TO_STRLEN(int), "%d", pidfd);
120 if (ret < 0)
121 return ret_errno(EIO);
122
123 f = fdopen_at(dfd_init_pid, path, "re", PROTECT_OPEN, PROTECT_LOOKUP_BENEATH);
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
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
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
175static struct attach_context *alloc_attach_context(void)
176{
177 struct attach_context *ctx;
178
179 ctx = zalloc(sizeof(struct attach_context));
180 if (!ctx)
181 return ret_set_errno(NULL, ENOMEM);
182
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;
193
194 for (int i = 0; i < LXC_NS_MAX; i++)
195 ctx->ns_fd[i] = -EBADF;
196
197 return ctx;
198}
199
200static int get_personality(const char *name, const char *lxcpath,
201 signed long *personality)
202{
203 __do_free char *p = NULL;
204 signed long per;
205
206 p = lxc_cmd_get_config_item(name, "lxc.arch", lxcpath);
207 if (!p) {
208 *personality = LXC_ARCH_UNCHANGED;
209 return 0;
210 }
211
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;
218}
219
220static int userns_setup_ids(struct attach_context *ctx,
221 lxc_attach_options_t *options)
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
234 f_uidmap = fdopen_at(ctx->dfd_init_pid, "uid_map", "re", PROTECT_OPEN, PROTECT_LOOKUP_BENEATH);
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) {
243 ctx->setup_ns_uid = 0;
244 TRACE("Container has mapping for uid 0");
245 break;
246 }
247
248 if (ctx->target_host_uid >= hostuid && ctx->target_host_uid < hostuid + range_uid) {
249 init_ns_uid = (ctx->target_host_uid - hostuid) + nsuid;
250 TRACE("Container runs with uid %d", init_ns_uid);
251 }
252 }
253
254 f_gidmap = fdopen_at(ctx->dfd_init_pid, "gid_map", "re", PROTECT_OPEN, PROTECT_LOOKUP_BENEATH);
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) {
263 ctx->setup_ns_gid = 0;
264 TRACE("Container has mapping for gid 0");
265 break;
266 }
267
268 if (ctx->target_host_gid >= hostgid && ctx->target_host_gid < hostgid + range_gid) {
269 init_ns_gid = (ctx->target_host_gid - hostgid) + nsgid;
270 TRACE("Container runs with gid %d", init_ns_gid);
271 }
272 }
273
274 if (ctx->setup_ns_uid == LXC_INVALID_UID)
275 ctx->setup_ns_uid = init_ns_uid;
276
277 if (ctx->setup_ns_gid == LXC_INVALID_UID)
278 ctx->setup_ns_gid = init_ns_gid;
279
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)
286 ctx->target_ns_uid = options->uid;
287 else if (options->namespaces & CLONE_NEWUSER)
288 ctx->target_ns_uid = ctx->setup_ns_uid;
289 else
290 ctx->target_ns_uid = 0;
291
292 if (ctx->target_ns_uid == LXC_INVALID_UID)
293 WARN("Invalid uid specified");
294
295 if (options->gid != LXC_INVALID_GID)
296 ctx->target_ns_gid = options->gid;
297 else if (options->namespaces & CLONE_NEWUSER)
298 ctx->target_ns_gid = ctx->setup_ns_gid;
299 else
300 ctx->target_ns_gid = 0;
301
302 if (ctx->target_ns_gid == LXC_INVALID_GID)
303 WARN("Invalid gid specified");
304}
305
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;
312 int ret;
313
314 f = fdopen_at(ctx->dfd_init_pid, "status", "re", PROTECT_OPEN, PROTECT_LOOKUP_BENEATH);
315 if (!f)
316 return log_error_errno(-errno, errno, "Failed to open status file");
317
318 while (getline(&line, &len, f) != -1) {
319 signed long value = -1;
320
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) {
327 ctx->target_host_uid = (uid_t)value;
328 TRACE("Container's init process runs with hostuid %d", ctx->target_host_uid);
329 goto next;
330 }
331
332 ret = sscanf(line, "Gid: %ld", &value);
333 if (ret != EOF && ret == 1) {
334 ctx->target_host_gid = (gid_t)value;
335 TRACE("Container's init process runs with hostgid %d", ctx->target_host_gid);
336 goto next;
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:
346 if (ctx->target_host_uid != LXC_INVALID_UID &&
347 ctx->target_host_gid != LXC_INVALID_GID &&
348 caps_found)
349 break;
350
351 }
352
353 ret = userns_setup_ids(ctx, options);
354 if (ret)
355 return log_error_errno(ret, errno, "Failed to get setup ids");
356 userns_target_ids(ctx, options);
357
358 return 0;
359}
360
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
380static int get_attach_context(struct attach_context *ctx,
381 struct lxc_container *container,
382 lxc_attach_options_t *options)
383{
384 __do_free char *lsm_label = NULL;
385 int ret;
386 char path[LXC_PROC_PID_LEN];
387
388 ctx->container = container;
389 ctx->attach_flags = options->attach_flags;
390
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
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);
400 else
401 ctx->init_pid = lxc_cmd_get_init_pid(container->name, container->config_path);
402
403 if (ctx->init_pid < 0)
404 return log_error(-1, "Failed to get init pid");
405
406 ret = strnprintf(path, sizeof(path), "/proc/%d", ctx->init_pid);
407 if (ret < 0)
408 return ret_errno(EIO);
409
410 ctx->dfd_init_pid = open_at(-EBADF, path,
411 PROTECT_OPATH_DIRECTORY,
412 (PROTECT_LOOKUP_ABSOLUTE & ~RESOLVE_NO_XDEV), 0);
413 if (ctx->dfd_init_pid < 0)
414 return log_error_errno(-errno, errno, "Failed to open /proc/%d", ctx->init_pid);
415
416 if (ctx->init_pidfd >= 0) {
417 ret = lxc_raw_pidfd_send_signal(ctx->init_pidfd, 0, NULL, 0);
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");
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 }
431 }
432
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
452 ret = parse_init_status(ctx, options);
453 if (ret)
454 return log_error_errno(-errno, errno, "Failed to open parse file");
455
456 ctx->lsm_ops = lsm_init_static();
457
458 if (attach_lsm(options)) {
459 if (ctx->attach_flags & LXC_ATTACH_LSM_LABEL)
460 lsm_label = options->lsm_label;
461 else
462 lsm_label = ctx->lsm_ops->process_label_get_at(ctx->lsm_ops, ctx->dfd_init_pid);
463 if (!lsm_label)
464 WARN("No security context received");
465 else
466 INFO("Retrieved security context %s", lsm_label);
467 }
468
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");
472
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
479 ctx->lsm_label = move_ptr(lsm_label);
480 return 0;
481}
482
483static int same_nsfd(int dfd_pid1, int dfd_pid2, const char *ns_path)
484{
485 int ret;
486 struct stat ns_st1, ns_st2;
487
488 ret = fstatat(dfd_pid1, ns_path, &ns_st1, 0);
489 if (ret)
490 return -1;
491
492 ret = fstatat(dfd_pid2, ns_path, &ns_st2, 0);
493 if (ret)
494 return -1;
495
496 /* processes are in the same namespace */
497 if ((ns_st1.st_dev == ns_st2.st_dev) &&
498 (ns_st1.st_ino == ns_st2.st_ino))
499 return -EINVAL;
500
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
524 /* processes are in different namespaces */
525 return move_fd(ns_fd2);
526}
527
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)
554{
555 for (int i = 0; i < LXC_NS_MAX; i++) {
556 int j;
557
558 if (options->namespaces & ns_info[i].clone_flag)
559 ctx->ns_fd[i] = open_at(ctx->dfd_init_pid,
560 ns_info[i].proc_path,
561 PROTECT_OPEN_WITH_TRAILING_SYMLINKS,
562 (PROTECT_LOOKUP_BENEATH_WITH_MAGICLINKS &
563 ~(RESOLVE_NO_XDEV | RESOLVE_BENEATH)),
564 0);
565 else if (ctx->ns_inherited & ns_info[i].clone_flag)
566 ctx->ns_fd[i] = same_ns(ctx->dfd_self_pid,
567 ctx->dfd_init_pid,
568 ns_info[i].proc_path);
569 else
570 continue;
571
572 if (ctx->ns_fd[i] >= 0)
573 continue;
574
575 if (ctx->ns_fd[i] == -EINVAL) {
576 ctx->ns_inherited &= ~ns_info[i].clone_flag;
577 continue;
578 }
579
580 /* We failed to preserve the namespace. */
581 SYSERROR("Failed to preserve %s namespace of %d",
582 ns_info[i].proc_name, ctx->init_pid);
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
596static int prepare_namespaces(struct attach_context *ctx,
597 lxc_attach_options_t *options)
598{
599 if (ctx->init_pidfd < 0)
600 return __prepare_namespaces_nsfd(ctx, options);
601
602 return __prepare_namespaces_pidfd(ctx);
603}
604
605static inline void put_namespaces(struct attach_context *ctx)
606{
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}
612
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;
618
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");
631}
632
633static int __attach_namespaces_nsfd(struct attach_context *ctx,
634 lxc_attach_options_t *options)
635{
636 int fret = 0;
637
638 for (int i = 0; i < LXC_NS_MAX; i++) {
639 int ret;
640
641 if (ctx->ns_fd[i] < 0)
642 continue;
643
644 ret = setns(ctx->ns_fd[i], ns_info[i].clone_flag);
645 if (ret)
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);
650
651 if (close(ctx->ns_fd[i])) {
652 fret = -errno;
653 SYSERROR("Failed to close file descriptor for %s namespace",
654 ns_info[i].proc_name);
655 }
656 ctx->ns_fd[i] = -EBADF;
657 }
658
659 return fret;
660}
661
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
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) {
709 if (close(ctx->dfd_self_pid))
710 return false;
711 ctx->dfd_self_pid = -EBADF;
712
713 if (close(ctx->dfd_init_pid))
714 return false;
715 ctx->dfd_init_pid = -EBADF;
716 }
717
718 return true;
719}
720
721int lxc_attach_remount_sys_proc(void)
722{
723 int ret;
724
725 ret = unshare(CLONE_NEWNS);
726 if (ret < 0)
727 return log_error_errno(-1, errno, "Failed to unshare mount namespace");
728
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...");
731
732 /* Assume /proc is always mounted, so remount it. */
733 ret = umount2("/proc", MNT_DETACH);
734 if (ret < 0)
735 return log_error_errno(-1, errno, "Failed to unmount /proc");
736
737 ret = mount("none", "/proc", "proc", 0, NULL);
738 if (ret < 0)
739 return log_error_errno(-1, errno, "Failed to remount /proc");
740
741 /*
742 * Try to umount /sys. If it's not a mount point, we'll get EINVAL, then
743 * we ignore it because it may not have been mounted in the first place.
744 */
745 ret = umount2("/sys", MNT_DETACH);
746 if (ret < 0 && errno != EINVAL)
747 return log_error_errno(-1, errno, "Failed to unmount /sys");
748
749 /* Remount it. */
750 if (ret == 0 && mount("none", "/sys", "sysfs", 0, NULL))
751 return log_error_errno(-1, errno, "Failed to remount /sys");
752
753 return 0;
754}
755
756static int drop_capabilities(struct attach_context *ctx)
757{
758 int last_cap;
759
760 last_cap = lxc_caps_last_cap();
761 for (int cap = 0; cap <= last_cap; cap++) {
762 if (ctx->capability_mask & (1LL << cap))
763 continue;
764
765 if (prctl(PR_CAPBSET_DROP, prctl_arg(cap), prctl_arg(0),
766 prctl_arg(0), prctl_arg(0)))
767 return log_error_errno(-1, errno, "Failed to drop capability %d", cap);
768
769 TRACE("Dropped capability %d", cap);
770 }
771
772 return 0;
773}
774
775static int lxc_attach_set_environment(struct attach_context *ctx,
776 enum lxc_attach_env_policy_t policy,
777 char **extra_env, char **extra_keep)
778{
779 int ret;
780 struct lxc_list *iterator;
781
782 if (policy == LXC_ATTACH_CLEAR_ENV) {
783 int path_kept = 0;
784 char **extra_keep_store = NULL;
785
786 if (extra_keep) {
787 size_t count, i;
788
789 for (count = 0; extra_keep[count]; count++)
790 ;
791
792 extra_keep_store = zalloc(count * sizeof(char *));
793 if (!extra_keep_store)
794 return -1;
795
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]) {
801 while (i > 0)
802 free(extra_keep_store[--i]);
803
804 free(extra_keep_store);
805 return -1;
806 }
807
808 if (strcmp(extra_keep[i], "PATH") == 0)
809 path_kept = 1;
810 }
811 }
812 }
813
814 if (clearenv()) {
815 if (extra_keep_store) {
816 char **p;
817
818 for (p = extra_keep_store; *p; p++)
819 free(*p);
820
821 free(extra_keep_store);
822 }
823
824 return log_error(-1, "Failed to clear environment");
825 }
826
827 if (extra_keep_store) {
828 size_t i;
829
830 for (i = 0; extra_keep[i]; i++) {
831 if (extra_keep_store[i]) {
832 ret = setenv(extra_keep[i], extra_keep_store[i], 1);
833 if (ret < 0)
834 SYSWARN("Failed to set environment variable");
835 }
836
837 free(extra_keep_store[i]);
838 }
839
840 free(extra_keep_store);
841 }
842
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 */
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)
851 SYSWARN("Failed to set environment variable");
852 }
853 }
854
855 ret = putenv("container=lxc");
856 if (ret < 0)
857 return log_warn(-1, "Failed to set environment variable");
858
859 /* Set container environment variables.*/
860 if (ctx->container->lxc_conf) {
861 lxc_list_for_each(iterator, &ctx->container->lxc_conf->environment) {
862 char *env_tmp;
863
864 env_tmp = strdup((char *)iterator->elem);
865 if (!env_tmp)
866 return -1;
867
868 ret = putenv(env_tmp);
869 if (ret < 0)
870 return log_error_errno(-1, errno, "Failed to set environment variable: %s", (char *)iterator->elem);
871 }
872 }
873
874 /* Set extra environment variables. */
875 if (extra_env) {
876 for (; *extra_env; extra_env++) {
877 char *p;
878
879 /* We just assume the user knows what they are doing, so
880 * we don't do any checks.
881 */
882 p = strdup(*extra_env);
883 if (!p)
884 return -1;
885
886 ret = putenv(p);
887 if (ret < 0)
888 SYSWARN("Failed to set environment variable");
889 }
890 }
891
892 return 0;
893}
894
895static char *lxc_attach_getpwshell(uid_t uid)
896{
897 __do_free char *line = NULL, *result = NULL;
898 __do_fclose FILE *pipe_f = NULL;
899 int fd, ret;
900 pid_t pid;
901 int pipes[2];
902 bool found = false;
903 size_t line_bufsz = 0;
904
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.
907 */
908 ret = pipe2(pipes, O_CLOEXEC);
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
919 if (!pid) {
920 char uid_buf[32];
921 char *arguments[] = {
922 "getent",
923 "passwd",
924 uid_buf,
925 NULL
926 };
927
928 close(pipes[0]);
929
930 /* We want to capture stdout. */
931 ret = dup2(pipes[1], STDOUT_FILENO);
932 close(pipes[1]);
933 if (ret < 0)
934 _exit(EXIT_FAILURE);
935
936 /* Get rid of stdin/stderr, so we try to associate it with
937 * /dev/null.
938 */
939 fd = open_devnull();
940 if (fd < 0) {
941 close(STDIN_FILENO);
942 close(STDERR_FILENO);
943 } else {
944 (void)dup3(fd, STDIN_FILENO, O_CLOEXEC);
945 (void)dup3(fd, STDERR_FILENO, O_CLOEXEC);
946 close(fd);
947 }
948
949 /* Finish argument list. */
950 ret = strnprintf(uid_buf, sizeof(uid_buf), "%ld", (long)uid);
951 if (ret <= 0)
952 _exit(EXIT_FAILURE);
953
954 /* Try to run getent program. */
955 (void)execvp("getent", arguments);
956 _exit(EXIT_FAILURE);
957 }
958
959 close(pipes[1]);
960
961 pipe_f = fdopen(pipes[0], "re");
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
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
982 if (!line)
983 continue;
984
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 ||
1003 value == LONG_MAX)
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 }
1016
1017 if (!token)
1018 continue;
1019
1020 free_disarm(result);
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 }
1030
1031reap_child:
1032 ret = wait_for_pid(pid);
1033 if (ret < 0)
1034 return NULL;
1035
1036 if (!found)
1037 return NULL;
1038
1039 return move_ptr(result);
1040}
1041
1042static bool fetch_seccomp(struct lxc_container *c, lxc_attach_options_t *options)
1043{
1044 __do_free char *path = NULL;
1045 int ret;
1046 bool bret;
1047
1048 if (!attach_lsm(options)) {
1049 free_disarm(c->lxc_conf->seccomp.seccomp);
1050 return true;
1051 }
1052
1053 /* Remove current setting. */
1054 if (!c->set_config_item(c, "lxc.seccomp.profile", "") &&
1055 !c->set_config_item(c, "lxc.seccomp", ""))
1056 return false;
1057
1058 /* Fetch the current profile path over the cmd interface. */
1059 path = c->get_running_config_item(c, "lxc.seccomp.profile");
1060 if (!path) {
1061 INFO("Failed to retrieve lxc.seccomp.profile");
1062
1063 path = c->get_running_config_item(c, "lxc.seccomp");
1064 if (!path)
1065 return log_info(true, "Failed to retrieve lxc.seccomp");
1066 }
1067
1068 /* Copy the value into the new lxc_conf. */
1069 bret = c->set_config_item(c, "lxc.seccomp.profile", path);
1070 if (!bret)
1071 return false;
1072
1073 /* Attempt to parse the resulting config. */
1074 ret = lxc_read_seccomp_config(c->lxc_conf);
1075 if (ret < 0)
1076 return log_error(false, "Failed to retrieve seccomp policy");
1077
1078 return log_info(true, "Retrieved seccomp policy");
1079}
1080
1081static bool no_new_privs(struct lxc_container *c, lxc_attach_options_t *options)
1082{
1083 __do_free char *val = NULL;
1084
1085 /* Remove current setting. */
1086 if (!c->set_config_item(c, "lxc.no_new_privs", ""))
1087 return log_info(false, "Failed to unset lxc.no_new_privs");
1088
1089 /* Retrieve currently active setting. */
1090 val = c->get_running_config_item(c, "lxc.no_new_privs");
1091 if (!val)
1092 return log_info(false, "Failed to retrieve lxc.no_new_privs");
1093
1094 /* Set currently active setting. */
1095 return c->set_config_item(c, "lxc.no_new_privs", val);
1096}
1097
1098struct attach_payload {
1099 int ipc_socket;
1100 int terminal_pts_fd;
1101 lxc_attach_options_t *options;
1102 struct attach_context *ctx;
1103 lxc_attach_exec_t exec_function;
1104 void *exec_payload;
1105};
1106
1107static void put_attach_payload(struct attach_payload *p)
1108{
1109 if (p) {
1110 close_prot_errno_disarm(p->ipc_socket);
1111 close_prot_errno_disarm(p->terminal_pts_fd);
1112 put_attach_context(p->ctx);
1113 p->ctx = NULL;
1114 }
1115}
1116
1117__noreturn static void do_attach(struct attach_payload *ap)
1118{
1119 lxc_attach_exec_t attach_function = move_ptr(ap->exec_function);
1120 void *attach_function_args = move_ptr(ap->exec_payload);
1121 int lsm_fd, ret;
1122 lxc_attach_options_t* options = ap->options;
1123 struct attach_context *ctx = ap->ctx;
1124 struct lxc_conf *conf = ctx->container->lxc_conf;
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();
1134 if (ret < 0)
1135 goto on_error;
1136
1137 TRACE("Remounted \"/proc\" and \"/sys\"");
1138 }
1139
1140 /* Now perform additional attachments. */
1141#if HAVE_SYS_PERSONALITY_H
1142 if (options->attach_flags & LXC_ATTACH_SET_PERSONALITY) {
1143 long new_personality;
1144
1145 if (options->personality < 0)
1146 new_personality = ctx->personality;
1147 else
1148 new_personality = options->personality;
1149
1150 if (new_personality != LXC_ARCH_UNCHANGED) {
1151 ret = personality(new_personality);
1152 if (ret < 0)
1153 goto on_error;
1154
1155 TRACE("Set new personality");
1156 }
1157 }
1158#endif
1159
1160 if (options->attach_flags & LXC_ATTACH_DROP_CAPABILITIES) {
1161 ret = drop_capabilities(ctx);
1162 if (ret < 0)
1163 goto on_error;
1164
1165 TRACE("Dropped capabilities");
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 */
1171 ret = lxc_attach_set_environment(ctx,
1172 options->env_policy,
1173 options->extra_env_vars,
1174 options->extra_keep_env);
1175 if (ret < 0)
1176 goto on_error;
1177
1178 TRACE("Set up environment");
1179
1180 /*
1181 * This remark only affects fully unprivileged containers:
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 */
1192 if (attach_lsm(options) && ctx->lsm_label) {
1193 if (!sync_wait_fd(ap->ipc_socket, ATTACH_SYNC_LSM(&lsm_fd))) {
1194 SYSERROR("Failed to receive lsm label fd");
1195 goto on_error;
1196 }
1197
1198 TRACE("Received LSM label file descriptor %d from parent", lsm_fd);
1199 }
1200
1201 if (options->stdin_fd > 0 && isatty(options->stdin_fd)) {
1202 ret = lxc_make_controlling_terminal(options->stdin_fd);
1203 if (ret < 0)
1204 goto on_error;
1205 }
1206
1207 if ((options->attach_flags & LXC_ATTACH_SETGROUPS) &&
1208 options->groups.size > 0) {
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 }
1215
1216 if (options->namespaces & CLONE_NEWUSER)
1217 if (!lxc_switch_uid_gid(ctx->setup_ns_uid, ctx->setup_ns_gid))
1218 goto on_error;
1219
1220 if (attach_lsm(options) && ctx->lsm_label) {
1221 bool on_exec;
1222
1223 /* Change into our new LSM profile. */
1224 on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? true : false;
1225 ret = ctx->lsm_ops->process_label_set_at(ctx->lsm_ops, lsm_fd, ctx->lsm_label, on_exec);
1226 close_prot_errno_disarm(lsm_fd);
1227 if (ret < 0)
1228 goto on_error;
1229
1230 TRACE("Set %s LSM label to \"%s\"", ctx->lsm_ops->name, ctx->lsm_label);
1231 }
1232
1233 if (conf->no_new_privs || (options->attach_flags & LXC_ATTACH_NO_NEW_PRIVS)) {
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
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 */
1251 if (options->stdin_fd >= 0 && options->stdin_fd != STDIN_FILENO)
1252 if (dup2(options->stdin_fd, STDIN_FILENO) < 0)
1253 SYSDEBUG("Failed to replace stdin with %d", options->stdin_fd);
1254
1255 if (options->stdout_fd >= 0 && options->stdout_fd != STDOUT_FILENO)
1256 if (dup2(options->stdout_fd, STDOUT_FILENO) < 0)
1257 SYSDEBUG("Failed to replace stdout with %d", options->stdout_fd);
1258
1259 if (options->stderr_fd >= 0 && options->stderr_fd != STDERR_FILENO)
1260 if (dup2(options->stderr_fd, STDERR_FILENO) < 0)
1261 SYSDEBUG("Failed to replace stderr with %d", options->stderr_fd);
1262
1263 /* close the old fds */
1264 if (options->stdin_fd > STDERR_FILENO)
1265 close(options->stdin_fd);
1266
1267 if (options->stdout_fd > STDERR_FILENO)
1268 close(options->stdout_fd);
1269
1270 if (options->stderr_fd > STDERR_FILENO)
1271 close(options->stderr_fd);
1272
1273 /*
1274 * Try to remove FD_CLOEXEC flag from stdin/stdout/stderr, but also
1275 * here, ignore errors.
1276 */
1277 for (int fd = STDIN_FILENO; fd <= STDERR_FILENO; fd++) {
1278 ret = fd_cloexec(fd, false);
1279 if (ret < 0) {
1280 SYSERROR("Failed to clear FD_CLOEXEC from file descriptor %d", fd);
1281 goto on_error;
1282 }
1283 }
1284
1285 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1286 ret = lxc_terminal_prepare_login(ap->terminal_pts_fd);
1287 if (ret < 0) {
1288 SYSERROR("Failed to prepare terminal file descriptor %d", ap->terminal_pts_fd);
1289 goto on_error;
1290 }
1291
1292 TRACE("Prepared terminal file descriptor %d", ap->terminal_pts_fd);
1293 }
1294
1295 /* Avoid unnecessary syscalls. */
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;
1301
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");
1309
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;
1320 lxc_seccomp_close_notifier_fd(&conf->seccomp);
1321 }
1322
1323 if (!lxc_switch_uid_gid(ctx->target_ns_uid, ctx->target_ns_gid))
1324 goto on_error;
1325
1326 put_attach_payload(ap);
1327
1328 /* We're done, so we can now do whatever the user intended us to do. */
1329 _exit(attach_function(attach_function_args));
1330
1331on_error:
1332 ERROR("Failed to attach to container");
1333 put_attach_payload(ap);
1334 _exit(EXIT_FAILURE);
1335}
1336
1337static int lxc_attach_terminal(const char *name, const char *lxcpath, struct lxc_conf *conf,
1338 struct lxc_terminal *terminal)
1339{
1340 int ret;
1341
1342 lxc_terminal_init(terminal);
1343
1344 ret = lxc_terminal_create(name, lxcpath, conf, terminal);
1345 if (ret < 0)
1346 return log_error(-1, "Failed to create terminal");
1347
1348 return 0;
1349}
1350
1351static int lxc_attach_terminal_mainloop_init(struct lxc_terminal *terminal,
1352 struct lxc_epoll_descr *descr)
1353{
1354 int ret;
1355
1356 ret = lxc_mainloop_open(descr);
1357 if (ret < 0)
1358 return log_error(-1, "Failed to create mainloop");
1359
1360 ret = lxc_terminal_mainloop_add(descr, terminal);
1361 if (ret < 0) {
1362 lxc_mainloop_close(descr);
1363 return log_error(-1, "Failed to add handlers to mainloop");
1364 }
1365
1366 return 0;
1367}
1368
1369static inline void lxc_attach_terminal_close_ptx(struct lxc_terminal *terminal)
1370{
1371 close_prot_errno_disarm(terminal->ptx);
1372}
1373
1374static inline void lxc_attach_terminal_close_pts(struct lxc_terminal *terminal)
1375{
1376 close_prot_errno_disarm(terminal->pty);
1377}
1378
1379static inline void lxc_attach_terminal_close_peer(struct lxc_terminal *terminal)
1380{
1381 close_prot_errno_disarm(terminal->peer);
1382}
1383
1384static inline void lxc_attach_terminal_close_log(struct lxc_terminal *terminal)
1385{
1386 close_prot_errno_disarm(terminal->log_fd);
1387}
1388
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)
1392{
1393 int ret_parent = -1;
1394 struct lxc_epoll_descr descr = {};
1395 int ret;
1396 char *name, *lxcpath;
1397 int ipc_sockets[2];
1398 pid_t attached_pid, pid, to_cleanup_pid;
1399 struct attach_context *ctx;
1400 struct lxc_terminal terminal;
1401 struct lxc_conf *conf;
1402
1403 if (!container)
1404 return ret_set_errno(-1, EINVAL);
1405
1406 if (!lxc_container_get(container))
1407 return ret_set_errno(-1, EINVAL);
1408
1409 name = container->name;
1410 lxcpath = container->config_path;
1411
1412 if (!options) {
1413 options = &attach_static_default_options;
1414 options->lsm_label = NULL;
1415 }
1416
1417 ctx = alloc_attach_context();
1418 if (!ctx) {
1419 lxc_container_put(container);
1420 return log_error_errno(-ENOMEM, ENOMEM, "Failed to allocate attach context");
1421 }
1422
1423 ret = get_attach_context(ctx, container, options);
1424 if (ret) {
1425 put_attach_context(ctx);
1426 return log_error(-1, "Failed to get attach context");
1427 }
1428
1429 conf = ctx->container->lxc_conf;
1430
1431 if (!fetch_seccomp(ctx->container, options))
1432 WARN("Failed to get seccomp policy");
1433
1434 if (!no_new_privs(ctx->container, options))
1435 WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set");
1436
1437 ret = prepare_namespaces(ctx, options);
1438 if (ret) {
1439 put_attach_context(ctx);
1440 return log_error(-1, "Failed to get namespace file descriptors");
1441 }
1442
1443 if (options->attach_flags & LXC_ATTACH_TERMINAL) {
1444 ret = lxc_attach_terminal(name, lxcpath, conf, &terminal);
1445 if (ret < 0) {
1446 put_attach_context(ctx);
1447 return log_error(-1, "Failed to setup new terminal");
1448 }
1449
1450 terminal.log_fd = options->log_fd;
1451 } else {
1452 lxc_terminal_init(&terminal);
1453 }
1454
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
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
1462 * our own child process will not really cause the socket to close
1463 * properly, potentially causing the parent to hang.
1464 *
1465 * For this reason, while IPC is still active, we have to use shutdown()
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.
1469 *
1470 * IPC mechanism: (X is receiver)
1471 * initial process transient process attached process
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
1480 * [set LXC_ATTACH_NO_NEW_PRIVS]
1481 * X <------------------------------------ send 3
1482 * [open LSM label fd]
1483 * send 4 ------------------------------------> X
1484 * [set LSM label]
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) {
1490 put_attach_context(ctx);
1491 return log_error_errno(-1, errno, "Could not set up required IPC mechanism for attaching");
1492 }
1493
1494 /* Create transient process, two reasons:
1495 * 1. We can't setns() in the child itself, since we want to make
1496 * sure we are properly attached to the pidns.
1497 * 2. Also, the initial thread has to put the attached process
1498 * into the cgroup, which we can only do if we didn't already
1499 * setns() (otherwise, user namespaces will hate us).
1500 */
1501 pid = fork();
1502 if (pid < 0) {
1503 put_attach_context(ctx);
1504 return log_error_errno(-1, errno, "Failed to create first subprocess");
1505 }
1506
1507 if (pid == 0) {
1508 char *cwd, *new_cwd;
1509
1510 /* close unneeded file descriptors */
1511 close_prot_errno_disarm(ipc_sockets[0]);
1512
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);
1517 }
1518
1519 /* Wait for the parent to have setup cgroups. */
1520 if (!sync_wait(ipc_sockets[1], ATTACH_SYNC_CGROUP)) {
1521 shutdown(ipc_sockets[1], SHUT_RDWR);
1522 put_attach_context(ctx);
1523 _exit(EXIT_FAILURE);
1524 }
1525
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
1532 cwd = getcwd(NULL, 0);
1533
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!
1543 */
1544 ret = attach_namespaces(ctx, options);
1545 if (ret < 0) {
1546 ERROR("Failed to enter namespaces");
1547 shutdown(ipc_sockets[1], SHUT_RDWR);
1548 put_attach_context(ctx);
1549 _exit(EXIT_FAILURE);
1550 }
1551
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);
1561 }
1562 free_disarm(cwd);
1563
1564 /* Create attached process. */
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);
1569 put_attach_context(ctx);
1570 _exit(EXIT_FAILURE);
1571 }
1572
1573 if (pid == 0) {
1574 struct attach_payload ap = {
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
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 }
1590
1591 /* Does not return. */
1592 do_attach(&ap);
1593 }
1594 TRACE("Attached process %d started initializing", pid);
1595
1596 if (options->attach_flags & LXC_ATTACH_TERMINAL)
1597 lxc_attach_terminal_close_pts(&terminal);
1598
1599 /* Tell grandparent the pid of the pid of the newly created child. */
1600 if (!sync_wake_pid(ipc_sockets[1], ATTACH_SYNC_PID(pid))) {
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);
1608 put_attach_context(ctx);
1609 _exit(EXIT_FAILURE);
1610 }
1611
1612 /* The rest is in the hands of the initial and the attached process. */
1613 put_attach_context(ctx);
1614 _exit(EXIT_SUCCESS);
1615 }
1616 TRACE("Transient process %d started initializing", pid);
1617
1618 to_cleanup_pid = pid;
1619
1620 /* close unneeded file descriptors */
1621 close_prot_errno_disarm(ipc_sockets[1]);
1622 put_namespaces(ctx);
1623 if (options->attach_flags & LXC_ATTACH_TERMINAL)
1624 lxc_attach_terminal_close_pts(&terminal);
1625
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);
1633 if (ret) {
1634 call_cleaner(cgroup_exit) struct cgroup_ops *cgroup_ops = NULL;
1635
1636 if (ret != -ENOCGROUP2) {
1637 SYSERROR("Failed to attach cgroup");
1638 goto on_error;
1639 }
1640
1641 cgroup_ops = cgroup_init(conf);
1642 if (!cgroup_ops)
1643 goto on_error;
1644
1645 if (!cgroup_ops->attach(cgroup_ops, conf, name, lxcpath, pid))
1646 goto on_error;
1647 }
1648
1649 TRACE("Moved transient process %d into container cgroup", pid);
1650 }
1651
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;
1657
1658 TRACE("Setup /proc/%d settings", pid);
1659 }
1660
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;
1666
1667 TRACE("Setup resource limits");
1668 }
1669
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;
1674
1675 TRACE("Initialized terminal mainloop");
1676 }
1677
1678 /* Let the child process know to go ahead. */
1679 if (!sync_wake(ipc_sockets[0], ATTACH_SYNC_CGROUP))
1680 goto close_mainloop;
1681
1682 TRACE("Told transient process to start initializing");
1683
1684 /* Get pid of attached process from transient process. */
1685 if (!sync_wait_pid(ipc_sockets[0], ATTACH_SYNC_PID(&attached_pid)))
1686 goto close_mainloop;
1687
1688 TRACE("Received pid %d of attached process in parent pid namespace", attached_pid);
1689
1690 /* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
1691 if (options->stdin_fd == STDIN_FILENO) {
1692 signal(SIGINT, SIG_IGN);
1693 signal(SIGQUIT, SIG_IGN);
1694 }
1695
1696 /* Reap transient process. */
1697 ret = wait_for_pid(pid);
1698 if (ret < 0)
1699 goto close_mainloop;
1700
1701 TRACE("Transient process %d exited", pid);
1702
1703 /* We will always have to reap the attached process now. */
1704 to_cleanup_pid = attached_pid;
1705
1706 /* Open LSM fd and send it to child. */
1707 if (attach_lsm(options) && ctx->lsm_label) {
1708 __do_close int labelfd = -EBADF;
1709 bool on_exec;
1710
1711 on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? true : false;
1712 labelfd = ctx->lsm_ops->process_label_fd_get(ctx->lsm_ops, attached_pid, on_exec);
1713 if (labelfd < 0)
1714 goto close_mainloop;
1715
1716 TRACE("Opened LSM label file descriptor %d", labelfd);
1717
1718 /* Send child fd of the LSM security module to write to. */
1719 if (!sync_wake_fd(ipc_sockets[0], ATTACH_SYNC_LSM(labelfd))) {
1720 SYSERROR("Failed to send lsm label fd");
1721 goto close_mainloop;
1722 }
1723
1724 TRACE("Sent LSM label file descriptor %d to child", labelfd);
1725 }
1726
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;
1731
1732 ret = lxc_seccomp_add_notifier(name, lxcpath, &conf->seccomp);
1733 if (ret < 0)
1734 goto close_mainloop;
1735 }
1736
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 */
1741
1742 *attached_process = attached_pid;
1743
1744 /* Now shut down communication with child, we're done. */
1745 shutdown(ipc_sockets[0], SHUT_RDWR);
1746 close_prot_errno_disarm(ipc_sockets[0]);
1747
1748 ret_parent = 0;
1749 to_cleanup_pid = -1;
1750
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 }
1757 }
1758
1759close_mainloop:
1760 if (options->attach_flags & LXC_ATTACH_TERMINAL)
1761 lxc_mainloop_close(&descr);
1762
1763on_error:
1764 if (ipc_sockets[0] >= 0) {
1765 shutdown(ipc_sockets[0], SHUT_RDWR);
1766 close_prot_errno_disarm(ipc_sockets[0]);
1767 }
1768
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 }
1776
1777 put_attach_context(ctx);
1778 return ret_parent;
1779}
1780
1781int lxc_attach_run_command(void *payload)
1782{
1783 int ret = -1;
1784 lxc_attach_command_t *cmd = payload;
1785
1786 ret = execvp(cmd->program, cmd->argv);
1787 if (ret < 0) {
1788 switch (errno) {
1789 case ENOEXEC:
1790 ret = 126;
1791 break;
1792 case ENOENT:
1793 ret = 127;
1794 break;
1795 }
1796 }
1797
1798 return log_error_errno(ret, errno, "Failed to exec \"%s\"", cmd->program);
1799}
1800
1801int lxc_attach_run_shell(void* payload)
1802{
1803 __do_free char *buf = NULL;
1804 uid_t uid;
1805 struct passwd pwent;
1806 struct passwd *pwentp = NULL;
1807 char *user_shell;
1808 size_t bufsize;
1809 int ret;
1810
1811 /* Ignore payload parameter. */
1812 (void)payload;
1813
1814 uid = getuid();
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)
1825 WARN("Could not find matched password record");
1826
1827 WARN("Failed to get password record - %u", uid);
1828 }
1829 }
1830
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.
1836 */
1837 if (!pwentp)
1838 user_shell = lxc_attach_getpwshell(uid);
1839 else
1840 user_shell = pwent.pw_shell;
1841
1842 if (user_shell)
1843 execlp(user_shell, user_shell, (char *)NULL);
1844
1845 /* Executed if either no passwd entry or execvp fails, we will fall back
1846 * on /bin/sh as a default shell.
1847 */
1848 execlp("/bin/sh", "/bin/sh", (char *)NULL);
1849
1850 SYSERROR("Failed to execute shell");
1851 if (!pwentp)
1852 free(user_shell);
1853
1854 return -1;
1855}