/
attach.c
1387 lines (1189 loc) · 35.4 KB
/
attach.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* lxc: linux Container library
*
* (C) Copyright IBM Corp. 2007, 2008
*
* Authors:
* Daniel Lezcano <daniel.lezcano at free.fr>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <sys/param.h>
#include <sys/prctl.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <linux/unistd.h>
#include <pwd.h>
#ifndef HAVE_DECL_PR_CAPBSET_DROP
#define PR_CAPBSET_DROP 24
#endif
#ifndef HAVE_DECL_PR_SET_NO_NEW_PRIVS
#define PR_SET_NO_NEW_PRIVS 38
#endif
#ifndef HAVE_DECL_PR_GET_NO_NEW_PRIVS
#define PR_GET_NO_NEW_PRIVS 39
#endif
#include "namespace.h"
#include "log.h"
#include "af_unix.h"
#include "attach.h"
#include "caps.h"
#include "config.h"
#include "utils.h"
#include "commands.h"
#include "cgroup.h"
#include "lxclock.h"
#include "conf.h"
#include "lxcseccomp.h"
#include <lxc/lxccontainer.h>
#include "lsm/lsm.h"
#include "confile.h"
#if HAVE_SYS_PERSONALITY_H
#include <sys/personality.h>
#endif
#ifndef SOCK_CLOEXEC
# define SOCK_CLOEXEC 02000000
#endif
#ifndef MS_REC
#define MS_REC 16384
#endif
#ifndef MS_SLAVE
#define MS_SLAVE (1<<19)
#endif
lxc_log_define(lxc_attach, lxc);
/* /proc/pid-to-str/current\0 = (5 + 21 + 7 + 1) */
#define __LSMATTRLEN (5 + (LXC_NUMSTRLEN64) + 7 + 1)
static int lsm_openat(int procfd, pid_t pid, int on_exec)
{
int ret = -1;
int labelfd = -1;
const char *name;
char path[__LSMATTRLEN];
name = lsm_name();
if (strcmp(name, "nop") == 0)
return 0;
if (strcmp(name, "none") == 0)
return 0;
/* We don't support on-exec with AppArmor */
if (strcmp(name, "AppArmor") == 0)
on_exec = 0;
if (on_exec)
ret = snprintf(path, __LSMATTRLEN, "%d/attr/exec", pid);
else
ret = snprintf(path, __LSMATTRLEN, "%d/attr/current", pid);
if (ret < 0 || ret >= __LSMATTRLEN)
return -1;
labelfd = openat(procfd, path, O_RDWR);
if (labelfd < 0) {
SYSERROR("Unable to open file descriptor to set LSM label.");
return -1;
}
return labelfd;
}
static int lsm_set_label_at(int lsm_labelfd, int on_exec, char *lsm_label)
{
int fret = -1;
const char* name;
char *command = NULL;
name = lsm_name();
if (strcmp(name, "nop") == 0)
return 0;
if (strcmp(name, "none") == 0)
return 0;
/* We don't support on-exec with AppArmor */
if (strcmp(name, "AppArmor") == 0)
on_exec = 0;
if (strcmp(name, "AppArmor") == 0) {
int size;
command = malloc(strlen(lsm_label) + strlen("changeprofile ") + 1);
if (!command) {
SYSERROR("Failed to write apparmor profile.");
goto out;
}
size = sprintf(command, "changeprofile %s", lsm_label);
if (size < 0) {
SYSERROR("Failed to write apparmor profile.");
goto out;
}
if (write(lsm_labelfd, command, size + 1) < 0) {
SYSERROR("Unable to set LSM label: %s.", command);
goto out;
}
INFO("Set LSM label to: %s.", command);
} else if (strcmp(name, "SELinux") == 0) {
if (write(lsm_labelfd, lsm_label, strlen(lsm_label) + 1) < 0) {
SYSERROR("Unable to set LSM label: %s.", lsm_label);
goto out;
}
INFO("Set LSM label to: %s.", lsm_label);
} else {
ERROR("Unable to restore label for unknown LSM: %s.", name);
goto out;
}
fret = 0;
out:
free(command);
if (lsm_labelfd != -1)
close(lsm_labelfd);
return fret;
}
/* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
#define __PROC_STATUS_LEN (5 + (LXC_NUMSTRLEN64) + 7 + 1)
static struct lxc_proc_context_info *lxc_proc_get_context_info(pid_t pid)
{
FILE *proc_file;
char proc_fn[__PROC_STATUS_LEN];
bool found;
int ret;
char *line = NULL;
size_t line_bufsz = 0;
struct lxc_proc_context_info *info = NULL;
/* Read capabilities. */
ret = snprintf(proc_fn, __PROC_STATUS_LEN, "/proc/%d/status", pid);
if (ret < 0 || ret >= __PROC_STATUS_LEN)
goto on_error;
proc_file = fopen(proc_fn, "r");
if (!proc_file) {
SYSERROR("Could not open %s.", proc_fn);
goto on_error;
}
info = calloc(1, sizeof(*info));
if (!info) {
SYSERROR("Could not allocate memory.");
return NULL;
}
found = false;
while (getline(&line, &line_bufsz, proc_file) != -1) {
ret = sscanf(line, "CapBnd: %llx", &info->capability_mask);
if (ret != EOF && ret == 1) {
found = true;
break;
}
}
free(line);
fclose(proc_file);
if (!found) {
SYSERROR("Could not read capability bounding set from %s.", proc_fn);
errno = ENOENT;
goto on_error;
}
info->lsm_label = lsm_process_label_get(pid);
return info;
on_error:
free(info);
return NULL;
}
static void lxc_proc_put_context_info(struct lxc_proc_context_info *ctx)
{
free(ctx->lsm_label);
if (ctx->container)
lxc_container_put(ctx->container);
free(ctx);
}
static int lxc_attach_to_ns(pid_t pid, int which)
{
int fd[LXC_NS_MAX];
int i, j, saved_errno;
if (access("/proc/self/ns", X_OK)) {
ERROR("Does this kernel version support namespaces?");
return -1;
}
for (i = 0; i < LXC_NS_MAX; i++) {
/* Ignore if we are not supposed to attach to that namespace. */
if (which != -1 && !(which & ns_info[i].clone_flag)) {
fd[i] = -1;
continue;
}
fd[i] = lxc_preserve_ns(pid, ns_info[i].proc_name);
if (fd[i] < 0) {
saved_errno = errno;
/* Close all already opened file descriptors before we
* return an error, so we don't leak them.
*/
for (j = 0; j < i; j++)
close(fd[j]);
errno = saved_errno;
SYSERROR("Failed to open namespace: \"%s\".", ns_info[i].proc_name);
return -1;
}
}
for (i = 0; i < LXC_NS_MAX; i++) {
if (fd[i] < 0)
continue;
if (setns(fd[i], 0) < 0) {
saved_errno = errno;
for (j = i; j < LXC_NS_MAX; j++)
close(fd[j]);
errno = saved_errno;
SYSERROR("Failed to attach to namespace \"%s\".", ns_info[i].proc_name);
return -1;
}
DEBUG("Attached to namespace \"%s\".", ns_info[i].proc_name);
close(fd[i]);
}
return 0;
}
static int lxc_attach_remount_sys_proc(void)
{
int ret;
ret = unshare(CLONE_NEWNS);
if (ret < 0) {
SYSERROR("Failed to unshare mount namespace.");
return -1;
}
if (detect_shared_rootfs()) {
if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL)) {
SYSERROR("Failed to make / rslave.");
ERROR("Continuing...");
}
}
/* Assume /proc is always mounted, so remount it. */
ret = umount2("/proc", MNT_DETACH);
if (ret < 0) {
SYSERROR("Failed to unmount /proc.");
return -1;
}
ret = mount("none", "/proc", "proc", 0, NULL);
if (ret < 0) {
SYSERROR("Failed to remount /proc.");
return -1;
}
/* Try to umount /sys. If it's not a mount point, we'll get EINVAL, then
* we ignore it because it may not have been mounted in the first place.
*/
ret = umount2("/sys", MNT_DETACH);
if (ret < 0 && errno != EINVAL) {
SYSERROR("Failed to unmount /sys.");
return -1;
} else if (ret == 0) {
/* Remount it. */
ret = mount("none", "/sys", "sysfs", 0, NULL);
if (ret < 0) {
SYSERROR("Failed to remount /sys.");
return -1;
}
}
return 0;
}
static int lxc_attach_drop_privs(struct lxc_proc_context_info *ctx)
{
int last_cap = lxc_caps_last_cap();
int cap;
for (cap = 0; cap <= last_cap; cap++) {
if (ctx->capability_mask & (1LL << cap))
continue;
if (prctl(PR_CAPBSET_DROP, cap, 0, 0, 0)) {
SYSERROR("Failed to remove capability id %d.", cap);
return -1;
}
}
return 0;
}
static int lxc_attach_set_environment(enum lxc_attach_env_policy_t policy, char** extra_env, char** extra_keep)
{
if (policy == LXC_ATTACH_CLEAR_ENV) {
char **extra_keep_store = NULL;
int path_kept = 0;
if (extra_keep) {
size_t count, i;
for (count = 0; extra_keep[count]; count++);
extra_keep_store = calloc(count, sizeof(char *));
if (!extra_keep_store) {
SYSERROR("Failed to allocate memory for storing current "
"environment variable values that will be kept.");
return -1;
}
for (i = 0; i < count; i++) {
char *v = getenv(extra_keep[i]);
if (v) {
extra_keep_store[i] = strdup(v);
if (!extra_keep_store[i]) {
SYSERROR("Failed to allocate memory for storing current "
"environment variable values that will be kept.");
while (i > 0)
free(extra_keep_store[--i]);
free(extra_keep_store);
return -1;
}
if (strcmp(extra_keep[i], "PATH") == 0)
path_kept = 1;
}
/* Calloc sets entire array to zero, so we don't
* need an else.
*/
}
}
if (clearenv()) {
char **p;
SYSERROR("Failed to clear environment.");
if (extra_keep_store) {
for (p = extra_keep_store; *p; p++)
free(*p);
free(extra_keep_store);
}
return -1;
}
if (extra_keep_store) {
size_t i;
for (i = 0; extra_keep[i]; i++) {
if (extra_keep_store[i]) {
if (setenv(extra_keep[i], extra_keep_store[i], 1) < 0)
SYSERROR("Unable to set environment variable.");
}
free(extra_keep_store[i]);
}
free(extra_keep_store);
}
/* Always set a default path; shells and execlp tend to be fine
* without it, but there is a disturbing number of C programs
* out there that just assume that getenv("PATH") is never NULL
* and then die a painful segfault death.
*/
if (!path_kept)
setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
}
if (putenv("container=lxc")) {
SYSERROR("Failed to set environment variable.");
return -1;
}
/* Set extra environment variables. */
if (extra_env) {
for (; *extra_env; extra_env++) {
/* Duplicate the string, just to be on the safe side,
* because putenv does not do it for us.
*/
char *p = strdup(*extra_env);
/* We just assume the user knows what they are doing, so
* we don't do any checks.
*/
if (!p) {
SYSERROR("Failed to allocate memory for additional environment "
"variables.");
return -1;
}
putenv(p);
}
}
return 0;
}
static char *lxc_attach_getpwshell(uid_t uid)
{
pid_t pid;
int pipes[2];
int ret;
int fd;
char *result = NULL;
/* We need to fork off a process that runs the getent program, and we
* need to capture its output, so we use a pipe for that purpose.
*/
ret = pipe(pipes);
if (ret < 0)
return NULL;
pid = fork();
if (pid < 0) {
close(pipes[0]);
close(pipes[1]);
return NULL;
}
if (pid) {
FILE *pipe_f;
char *line = NULL;
size_t line_bufsz = 0;
int found = 0;
int status;
close(pipes[1]);
pipe_f = fdopen(pipes[0], "r");
while (getline(&line, &line_bufsz, pipe_f) != -1) {
char *token;
char *saveptr = NULL;
long value;
char *endptr = NULL;
int i;
/* If we already found something, just continue to read
* until the pipe doesn't deliver any more data, but
* don't modify the existing data structure.
*/
if (found)
continue;
/* Trim line on the right hand side. */
for (i = strlen(line); i > 0 && (line[i - 1] == '\n' || line[i - 1] == '\r'); --i)
line[i - 1] = '\0';
/* Split into tokens: first: user name. */
token = strtok_r(line, ":", &saveptr);
if (!token)
continue;
/* next: dummy password field */
token = strtok_r(NULL, ":", &saveptr);
if (!token)
continue;
/* next: user id */
token = strtok_r(NULL, ":", &saveptr);
value = token ? strtol(token, &endptr, 10) : 0;
if (!token || !endptr || *endptr || value == LONG_MIN || value == LONG_MAX)
continue;
/* dummy sanity check: user id matches */
if ((uid_t) value != uid)
continue;
/* skip fields: gid, gecos, dir, go to next field 'shell' */
for (i = 0; i < 4; i++) {
token = strtok_r(NULL, ":", &saveptr);
if (!token)
break;
}
if (!token)
continue;
free(result);
result = strdup(token);
/* Sanity check that there are no fields after that. */
token = strtok_r(NULL, ":", &saveptr);
if (token)
continue;
found = 1;
}
free(line);
fclose(pipe_f);
again:
if (waitpid(pid, &status, 0) < 0) {
if (errno == EINTR)
goto again;
return NULL;
}
/* Some sanity checks. If anything even hinted at going wrong,
* we can't be sure we have a valid result, so we assume we
* don't.
*/
if (!WIFEXITED(status))
return NULL;
if (WEXITSTATUS(status) != 0)
return NULL;
if (!found)
return NULL;
return result;
} else {
char uid_buf[32];
char *arguments[] = {
"getent",
"passwd",
uid_buf,
NULL
};
close(pipes[0]);
/* We want to capture stdout. */
dup2(pipes[1], 1);
close(pipes[1]);
/* Get rid of stdin/stderr, so we try to associate it with
* /dev/null.
*/
fd = open("/dev/null", O_RDWR);
if (fd < 0) {
close(0);
close(2);
} else {
dup2(fd, 0);
dup2(fd, 2);
close(fd);
}
/* Finish argument list. */
ret = snprintf(uid_buf, sizeof(uid_buf), "%ld", (long) uid);
if (ret <= 0)
exit(-1);
/* Try to run getent program. */
(void) execvp("getent", arguments);
exit(-1);
}
}
static void lxc_attach_get_init_uidgid(uid_t* init_uid, gid_t* init_gid)
{
FILE *proc_file;
char proc_fn[__PROC_STATUS_LEN];
int ret;
char *line = NULL;
size_t line_bufsz = 0;
long value = -1;
uid_t uid = (uid_t)-1;
gid_t gid = (gid_t)-1;
/* Read capabilities. */
snprintf(proc_fn, __PROC_STATUS_LEN, "/proc/%d/status", 1);
proc_file = fopen(proc_fn, "r");
if (!proc_file)
return;
while (getline(&line, &line_bufsz, proc_file) != -1) {
/* Format is: real, effective, saved set user, fs we only care
* about real uid.
*/
ret = sscanf(line, "Uid: %ld", &value);
if (ret != EOF && ret == 1) {
uid = (uid_t) value;
} else {
ret = sscanf(line, "Gid: %ld", &value);
if (ret != EOF && ret == 1)
gid = (gid_t) value;
}
if (uid != (uid_t)-1 && gid != (gid_t)-1)
break;
}
fclose(proc_file);
free(line);
/* Only override arguments if we found something. */
if (uid != (uid_t)-1)
*init_uid = uid;
if (gid != (gid_t)-1)
*init_gid = gid;
/* TODO: we should also parse supplementary groups and use
* setgroups() to set them.
*/
}
struct attach_clone_payload {
int ipc_socket;
lxc_attach_options_t* options;
struct lxc_proc_context_info* init_ctx;
lxc_attach_exec_t exec_function;
void* exec_payload;
};
static int attach_child_main(void* data);
/* Help the optimizer along if it doesn't know that exit always exits. */
#define rexit(c) do { int __c = (c); _exit(__c); return __c; } while(0)
/* Define default options if no options are supplied by the user. */
static lxc_attach_options_t attach_static_default_options = LXC_ATTACH_OPTIONS_DEFAULT;
static bool fetch_seccomp(struct lxc_container *c,
lxc_attach_options_t *options)
{
char *path;
if (!(options->namespaces & CLONE_NEWNS) || !(options->attach_flags & LXC_ATTACH_LSM)) {
free(c->lxc_conf->seccomp);
c->lxc_conf->seccomp = NULL;
return true;
}
/* Remove current setting. */
if (!c->set_config_item(c, "lxc.seccomp", "")) {
return false;
}
/* Fetch the current profile path over the cmd interface. */
path = c->get_running_config_item(c, "lxc.seccomp");
if (!path) {
INFO("Failed to get running config item for lxc.seccomp.");
return true;
}
/* Copy the value into the new lxc_conf. */
if (!c->set_config_item(c, "lxc.seccomp", path)) {
free(path);
return false;
}
free(path);
/* Attempt to parse the resulting config. */
if (lxc_read_seccomp_config(c->lxc_conf) < 0) {
ERROR("Error reading seccomp policy.");
return false;
}
INFO("Retrieved seccomp policy.");
return true;
}
static bool no_new_privs(struct lxc_container *c,
lxc_attach_options_t *options)
{
char *val;
/* Remove current setting. */
if (!c->set_config_item(c, "lxc.no_new_privs", "")) {
return false;
}
/* Retrieve currently active setting. */
val = c->get_running_config_item(c, "lxc.no_new_privs");
if (!val) {
INFO("Failed to get running config item for lxc.no_new_privs.");
return false;
}
/* Set currently active setting. */
if (!c->set_config_item(c, "lxc.no_new_privs", val)) {
free(val);
return false;
}
free(val);
return true;
}
static signed long get_personality(const char *name, const char *lxcpath)
{
char *p = lxc_cmd_get_config_item(name, "lxc.arch", lxcpath);
signed long ret;
if (!p)
return -1;
ret = lxc_config_parse_arch(p);
free(p);
return ret;
}
int lxc_attach(const char* name, const char* lxcpath, lxc_attach_exec_t exec_function, void* exec_payload, lxc_attach_options_t* options, pid_t* attached_process)
{
int ret, status;
pid_t init_pid, pid, attached_pid, expected;
struct lxc_proc_context_info *init_ctx;
char* cwd;
char* new_cwd;
int ipc_sockets[2];
signed long personality;
if (!options)
options = &attach_static_default_options;
init_pid = lxc_cmd_get_init_pid(name, lxcpath);
if (init_pid < 0) {
ERROR("Failed to get init pid.");
return -1;
}
init_ctx = lxc_proc_get_context_info(init_pid);
if (!init_ctx) {
ERROR("Failed to get context of init process: %ld.",
(long)init_pid);
return -1;
}
personality = get_personality(name, lxcpath);
if (init_ctx->personality < 0) {
ERROR("Failed to get personality of the container.");
lxc_proc_put_context_info(init_ctx);
return -1;
}
init_ctx->personality = personality;
init_ctx->container = lxc_container_new(name, lxcpath);
if (!init_ctx->container)
return -1;
if (!fetch_seccomp(init_ctx->container, options))
WARN("Failed to get seccomp policy.");
if (!no_new_privs(init_ctx->container, options))
WARN("Could not determine whether PR_SET_NO_NEW_PRIVS is set.");
cwd = getcwd(NULL, 0);
/* Determine which namespaces the container was created with
* by asking lxc-start, if necessary.
*/
if (options->namespaces == -1) {
options->namespaces = lxc_cmd_get_clone_flags(name, lxcpath);
/* call failed */
if (options->namespaces == -1) {
ERROR("Failed to automatically determine the "
"namespaces which the container uses.");
free(cwd);
lxc_proc_put_context_info(init_ctx);
return -1;
}
}
/* Create a socket pair for IPC communication; set SOCK_CLOEXEC in order
* to make sure we don't irritate other threads that want to fork+exec
* away
*
* IMPORTANT: if the initial process is multithreaded and another call
* just fork()s away without exec'ing directly after, the socket fd will
* exist in the forked process from the other thread and any close() in
* our own child process will not really cause the socket to close
* properly, potentiall causing the parent to hang.
*
* For this reason, while IPC is still active, we have to use shutdown()
* if the child exits prematurely in order to signal that the socket is
* closed and cannot assume that the child exiting will automatically do
* that.
*
* IPC mechanism: (X is receiver)
* initial process intermediate attached
* X <--- send pid of
* attached proc,
* then exit
* send 0 ------------------------------------> X
* [do initialization]
* X <------------------------------------ send 1
* [add to cgroup, ...]
* send 2 ------------------------------------> X
* [set LXC_ATTACH_NO_NEW_PRIVS]
* X <------------------------------------ send 3
* [open LSM label fd]
* send 4 ------------------------------------> X
* [set LSM label]
* close socket close socket
* run program
*/
ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, ipc_sockets);
if (ret < 0) {
SYSERROR("Could not set up required IPC mechanism for attaching.");
free(cwd);
lxc_proc_put_context_info(init_ctx);
return -1;
}
/* Create intermediate subprocess, three reasons:
* 1. Runs all pthread_atfork handlers and the child will no
* longer be threaded (we can't properly setns() in a threaded
* process).
* 2. We can't setns() in the child itself, since we want to make
* sure we are properly attached to the pidns.
* 3. Also, the initial thread has to put the attached process
* into the cgroup, which we can only do if we didn't already
* setns() (otherwise, user namespaces will hate us).
*/
pid = fork();
if (pid < 0) {
SYSERROR("Failed to create first subprocess.");
free(cwd);
lxc_proc_put_context_info(init_ctx);
return -1;
}
if (pid) {
int procfd = -1;
pid_t to_cleanup_pid = pid;
/* Initial thread, we close the socket that is for the
* subprocesses.
*/
close(ipc_sockets[1]);
free(cwd);
/* Attach to cgroup, if requested. */
if (options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) {
if (!cgroup_attach(name, lxcpath, pid))
goto on_error;
}
/* Setup resource limits */
if (!lxc_list_empty(&init_ctx->container->lxc_conf->limits) && setup_resource_limits(&init_ctx->container->lxc_conf->limits, pid)) {
goto on_error;
}
/* Open /proc before setns() to the containers namespace so we
* don't rely on any information from inside the container.
*/
procfd = open("/proc", O_DIRECTORY | O_RDONLY | O_CLOEXEC);
if (procfd < 0) {
SYSERROR("Unable to open /proc.");
goto on_error;
}
/* Let the child process know to go ahead. */
status = 0;
ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status));
if (ret <= 0) {
ERROR("Intended to send sequence number 0: %s.",
strerror(errno));
goto on_error;
}
/* Get pid of attached process from intermediate process. */
ret = lxc_read_nointr_expect(ipc_sockets[0], &attached_pid, sizeof(attached_pid), NULL);
if (ret <= 0) {
if (ret != 0)
ERROR("Expected to receive pid: %s.", strerror(errno));
goto on_error;
}
/* Ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313. */
if (options->stdin_fd == 0) {
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
}
/* Reap intermediate process. */
ret = wait_for_pid(pid);
if (ret < 0)
goto on_error;
/* We will always have to reap the attached process now. */
to_cleanup_pid = attached_pid;
/* Tell attached process it may start initializing. */
status = 0;
ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status));
if (ret <= 0) {
ERROR("Intended to send sequence number 0: %s.", strerror(errno));
goto on_error;
}
/* Wait for the attached process to finish initializing. */
expected = 1;
ret = lxc_read_nointr_expect(ipc_sockets[0], &status, sizeof(status), &expected);
if (ret <= 0) {
if (ret != 0)
ERROR("Expected to receive sequence number 1: %s.", strerror(errno));
goto on_error;
}
/* Tell attached process we're done. */
status = 2;
ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status));
if (ret <= 0) {
ERROR("Intended to send sequence number 2: %s.", strerror(errno));
goto on_error;
}
/* Wait for the (grand)child to tell us that it's ready to set
* up its LSM labels.
*/
expected = 3;
ret = lxc_read_nointr_expect(ipc_sockets[0], &status, sizeof(status), &expected);
if (ret <= 0) {
ERROR("Expected to receive sequence number 3: %s.",
strerror(errno));
goto on_error;
}
/* Open LSM fd and send it to child. */
if ((options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_LSM) && init_ctx->lsm_label) {
int on_exec, saved_errno;
int labelfd = -1;
on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? 1 : 0;
/* Open fd for the LSM security module. */
labelfd = lsm_openat(procfd, attached_pid, on_exec);
if (labelfd < 0)
goto on_error;
/* Send child fd of the LSM security module to write to. */
ret = lxc_abstract_unix_send_fd(ipc_sockets[0], labelfd, NULL, 0);
saved_errno = errno;
close(labelfd);
if (ret <= 0) {
ERROR("Intended to send file descriptor %d: %s.", labelfd, strerror(saved_errno));
goto on_error;
}
}
if (procfd >= 0)
close(procfd);
/* Now shut down communication with child, we're done. */