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