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