forked from aws/aws-nitro-enclaves-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.c
435 lines (376 loc) · 11.9 KB
/
init.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
/*
* MIT License
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE
*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <signal.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/reboot.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <linux/vm_sockets.h>
#include <poll.h>
_Noreturn void die(const char *msg);
#define die_on(CONDITION, ...) \
do { \
if (CONDITION) { \
die(__VA_ARGS__); \
} \
} while (0)
#define finit_module(fd, param_values, flags) (int)syscall(__NR_finit_module, fd, param_values, flags)
#define DEFAULT_PATH_ENV "PATH=/sbin:/usr/sbin:/bin:/usr/bin"
#define NSM_PATH "nsm.ko"
#define TIMEOUT 20000 // millis
#define VSOCK_PORT 9000
#define VSOCK_CID 3
#define HEART_BEAT 0xB7
const char *const default_envp[] = {
DEFAULT_PATH_ENV,
NULL,
};
const char *const default_argv[] = { "sh", NULL };
struct Mount {
const char *source, *target, *type;
unsigned long flags;
const void *data;
};
struct Mkdir {
const char *path;
mode_t mode;
};
struct Mknod {
const char *path;
mode_t mode;
int major, minor;
};
struct Symlink {
const char *linkpath, *target;
};
enum OpType {
OpMount,
OpMkdir,
OpMknod,
OpSymlink,
};
struct InitOp {
enum OpType op;
union {
struct Mount mount;
struct Mkdir mkdir;
struct Mknod mknod;
struct Symlink symlink;
};
};
const struct InitOp ops[] = {
// mount /proc (which should already exist)
{ OpMount, .mount = { "proc", "/proc", "proc", MS_NODEV | MS_NOSUID | MS_NOEXEC } },
// add symlinks in /dev (which is already mounted)
{ OpSymlink, .symlink = { "/dev/fd", "/proc/self/fd" } },
{ OpSymlink, .symlink = { "/dev/stdin", "/proc/self/fd/0" } },
{ OpSymlink, .symlink = { "/dev/stdout", "/proc/self/fd/1" } },
{ OpSymlink, .symlink = { "/dev/stderr", "/proc/self/fd/2" } },
// mount tmpfs on /run and /tmp (which should already exist)
{ OpMount, .mount = { "tmpfs", "/run", "tmpfs", MS_NODEV | MS_NOSUID | MS_NOEXEC, "mode=0755" } },
{ OpMount, .mount = { "tmpfs", "/tmp", "tmpfs", MS_NODEV | MS_NOSUID | MS_NOEXEC } },
// mount shm and devpts
{ OpMkdir, .mkdir = { "/dev/shm", 0755 } },
{ OpMount, .mount = { "shm", "/dev/shm", "tmpfs", MS_NODEV | MS_NOSUID | MS_NOEXEC } },
{ OpMkdir, .mkdir = { "/dev/pts", 0755 } },
{ OpMount, .mount = { "devpts", "/dev/pts", "devpts", MS_NOSUID | MS_NOEXEC } },
// mount /sys (which should already exist)
{ OpMount, .mount = { "sysfs", "/sys", "sysfs", MS_NODEV | MS_NOSUID | MS_NOEXEC } },
{ OpMount, .mount = { "cgroup_root", "/sys/fs/cgroup", "tmpfs", MS_NODEV | MS_NOSUID | MS_NOEXEC, "mode=0755" } },
};
void warn(const char *msg) {
int error = errno;
perror(msg);
errno = error;
}
void warn2(const char *msg1, const char *msg2) {
int error = errno;
fputs(msg1, stderr);
fputs(": ", stderr);
errno = error;
warn(msg2);
}
_Noreturn void dien() {
exit(errno);
}
_Noreturn void die(const char *msg) {
warn(msg);
dien();
}
_Noreturn void die2(const char *msg1, const char *msg2) {
warn2(msg1, msg2);
dien();
}
void init_dev() {
if (mount("dev", "/dev", "devtmpfs", MS_NOSUID | MS_NOEXEC, NULL) < 0) {
warn2("mount", "/dev");
// /dev will be already mounted if devtmpfs.mount = 1 on the kernel
// command line or CONFIG_DEVTMPFS_MOUNT is set. Do not consider this
// an error.
if (errno != EBUSY) {
dien();
}
}
}
void init_fs(const struct InitOp *ops, size_t count) {
for (size_t i = 0; i < count; i++) {
switch (ops[i].op) {
case OpMount: {
const struct Mount *m = &ops[i].mount;
if (mount(m->source, m->target, m->type, m->flags, m->data) < 0) {
die2("mount", m->target);
}
break;
}
case OpMkdir: {
const struct Mkdir *m = &ops[i].mkdir;
if (mkdir(m->path, m->mode) < 0) {
warn2("mkdir", m->path);
if (errno != EEXIST) {
dien();
}
}
break;
}
case OpMknod: {
const struct Mknod *n = &ops[i].mknod;
if (mknod(n->path, n->mode, makedev(n->major, n->minor)) < 0) {
warn2("mknod", n->path);
if (errno != EEXIST) {
dien();
}
}
break;
}
case OpSymlink: {
const struct Symlink *sl = &ops[i].symlink;
if (symlink(sl->target, sl->linkpath) < 0) {
warn2("symlink", sl->linkpath);
if (errno != EEXIST) {
dien();
}
}
break;
}
}
}
}
void init_cgroups() {
const char *fpath = "/proc/cgroups";
FILE *f = fopen(fpath, "r");
if (f == NULL) {
die2("fopen", fpath);
}
// Skip the first line.
for (;;) {
int c = fgetc(f);
if (c == EOF || c == '\n') {
break;
}
}
for (;;) {
static const char base_path[] = "/sys/fs/cgroup/";
char path[sizeof(base_path) - 1 + 64];
char* name = path + sizeof(base_path) - 1;
int hier, groups, enabled;
int r = fscanf(f, "%64s %d %d %d\n", name, &hier, &groups, &enabled);
if (r == EOF) {
break;
}
if (r != 4) {
errno = errno ? : EINVAL;
die2("fscanf", fpath);
}
if (enabled) {
memcpy(path, base_path, sizeof(base_path) - 1);
if (mkdir(path, 0755) < 0) {
die2("mkdir", path);
}
if (mount(name, path, "cgroup", MS_NODEV | MS_NOSUID | MS_NOEXEC, name) < 0) {
die2("mount", path);
}
}
}
fclose(f);
}
void init_console() {
// init process needs to set up a tty for the container and this is likely
// not the correct way to do this, although it works when compiling with
// musl-gcc.
const char *console_path = "/dev/console";
die_on(freopen(console_path, "r", stdin) == NULL,
"freopen failed for stdin");
die_on(freopen(console_path, "w", stdout) == NULL,
"freopen failed for stdout");
die_on(freopen(console_path, "w", stderr) == NULL,
"freopen failed for stderr");
}
pid_t launch(char **argv, char **envp) {
int pid = fork();
if (pid != 0) {
die_on(pid < 0, "fork");
return pid;
}
if (argv == NULL)
argv = (char **) default_argv;
if (envp == NULL)
envp = (char **) default_envp;
// Unblock signals before execing.
sigset_t set;
sigfillset(&set);
sigprocmask(SIG_UNBLOCK, &set, 0);
// Create a session and process group.
setsid();
setpgid(0, 0);
// Terminate the arguments and exec.
die_on(putenv(DEFAULT_PATH_ENV), "putenv"); // Specify the PATH used for execvpe
execvpe(argv[0], argv, envp);
die2("execvpe", argv[0]);
}
int reap_until(pid_t until_pid) {
for (;;) {
int status;
pid_t pid = wait(&status);
die_on(pid < 0, "wait");
if (pid == until_pid) {
// The initial child process died. Pass through the exit status.
if (WIFEXITED(status)) {
if (WEXITSTATUS(status) != 0) {
fputs("child exited with error\n", stderr);
}
return WEXITSTATUS(status);
}
fputs("child exited by signal\n", stderr);
return 128 + WTERMSIG(status);
}
}
}
char **read_config(FILE *env_file) {
if (env_file == NULL) {
warn("Could not open /env file");
return NULL;
}
char **env = NULL;
const size_t env_increment = 10;
size_t env_size = 0;
for (size_t i = 0; !feof(env_file); i++) {
char *line = NULL;
size_t len = 0;
ssize_t read = getline(&line, &len, env_file);
if (read == -1)
break;
if (line[read - 1] == '\n')
line[read - 1] = 0;
if (i + 1 >= env_size) {
env_size += env_increment;
env = realloc(env, env_size * sizeof(char *));
die_on(env == NULL, "not enough mem for env variables");
}
env[i] = line;
env[i + 1] = NULL;
}
return env;
}
void enclave_ready() {
int socket_fd;
struct sockaddr_vm sa = {
.svm_family = AF_VSOCK,
.svm_cid = VSOCK_CID,
.svm_port = VSOCK_PORT,
.svm_reserved1 = 0,
};
uint8_t buf[1];
buf[0] = HEART_BEAT;
errno = -EINVAL;
socket_fd = socket(AF_VSOCK, SOCK_STREAM, 0);
die_on(socket_fd < 0, "socket");
die_on(connect(socket_fd, (struct sockaddr*) &sa, sizeof(sa)), "connect");
die_on(write(socket_fd, buf, 1) != 1, "write heartbeat");
die_on(read(socket_fd, buf, 1) != 1, "read heartbeat");
die_on(buf[0] != HEART_BEAT, "received wrong heartbeat");
die_on(close(socket_fd), "close");
}
void init_nsm_driver() {
int fd;
int rc;
fd = open(NSM_PATH, O_RDONLY | O_CLOEXEC);
if (fd < 0 && errno == ENOENT) {
return;
}
die_on(fd < 0, "failed to open nsm fd");
rc = finit_module(fd, "", 0);
die_on(rc < 0, "failed to insert nsm driver");
die_on(close(fd), "close nsm fd");
}
int main() {
// Block all signals in init. SIGCHLD will still cause wait() to return.
sigset_t set;
sigfillset(&set);
sigprocmask(SIG_BLOCK, &set, 0);
// Set up the minimal dependencies to start a container
// Init /dev and start /dev/console for early debugging
init_dev();
init_console();
// Insert the Nitro Secure Module driver
init_nsm_driver();
// Signal nitro-cli that the enclave has started
enclave_ready();
FILE *env_file = fopen("/env", "r");
FILE *cmd_file = fopen("/cmd", "r");
// env should be an array of "VAR1=string1", "VAR2=string2", ...
// The array should end with NULL
char **env = read_config(env_file);
// cmd should be an array of "command", "param1", "param2", ...
// The array should end with NULL
char **cmd = read_config(cmd_file);
fclose(env_file);
fclose(cmd_file);
die_on(chdir("/rootfs") != 0, "chdir /rootfs");
die_on(chroot("/rootfs") != 0, "chroot /rootfs");
// At this point, we need to make sure the container /dev is initialized
// as well.
init_dev();
init_fs(ops, sizeof(ops) / sizeof(ops[0]));
init_cgroups();
pid_t pid = launch(cmd, env);
//// Reap until the initial child process dies.
reap_until(pid);
reboot(RB_AUTOBOOT);
}