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