interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / native / kernel / tools / ck_imac_netboot.c

439 lines · 16035 bytes Raw Blame History
1/* ck_imac_netboot.c -- host side of the AIENOS lab netboot (NETLDR.EFI on the
2 * iMac; wire format native/boot/netboot_proto.h). Hosted C (POSIX sockets),
3 * tooling only, never in an image. No Python, no outside libraries: Ed25519
4 * and SHA-512 are native/sig.
5 *
6 * ck_imac_netboot keygen KEY PUB new lab signing key: KEY = 32-byte seed
7 * (created 0600, never overwritten), PUB =
8 * "owner_root_ed25519 <hex>" for
9 * make imac-netldr CK_NETLDR_KEYS=PUB
10 * ck_imac_netboot pubkey KEY print the public key (64 hex)
11 * ck_imac_netboot sign KEY TBS SIG Ed25519 over the to-be-signed bytes
12 * (ck_slot_tool tbs) -> 64-byte SIG
13 * ck_imac_netboot serve SPOOL [--bcast A.B.C.D] [--mac M] [--seconds N]
14 * [--qemu-dgram LOCALPORT:REMOTEPORT]
15 *
16 * serve answers NETLDR. A job is SPOOL/next.job: a signed slot manifest
17 * (CK_SLOT_UNIT bytes) followed by the image; write it elsewhere and rename()
18 * it in. On a HELLO the job moves to SPOOL/serving.job and is offered; the
19 * loader's DONE moves it to SPOOL/booted-<time>.job (status 0, verified) or
20 * SPOOL/refused-<time>.job (status 1). With no job every HELLO gets WAIT, so
21 * the iMac sits in its loader until the next job arrives. One line per event
22 * goes to stdout. This tool never signs or checks what it serves: the loader
23 * verifies every byte against its built-in key, so a bad job is refused there.
24 *
25 * Transports: UDP (default) binds 0.0.0.0:NB_PORT_SERVER and answers to the
26 * broadcast address --bcast (default 255.255.255.255) port NB_PORT_LOADER.
27 * --qemu-dgram speaks raw Ethernet frames over a UDP pair on 127.0.0.1, the
28 * QEMU "-netdev dgram" backend, so the QEMU test runs the real loader without
29 * root or a tap device. --mac answers only HELLOs from that address.
30 * Exit 0 at --seconds, 2 usage, 3 socket or file error. */
31#define _GNU_SOURCE
32#include <arpa/inet.h>
33#include <errno.h>
34#include <fcntl.h>
35#include <netinet/in.h>
36#include <poll.h>
37#include <stdarg.h>
38#include <stdint.h>
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42#include <sys/random.h>
43#include <sys/socket.h>
44#include <sys/stat.h>
45#include <time.h>
46#include <unistd.h>
47
48#include "aienos_net.h"
49#include "aienos_sig.h"
50#include "netboot_proto.h"
51
52#define MANIFEST_BYTES 4096u /* CK_SLOT_UNIT (slot_format.h) */
53#define TBS_BYTES 448u /* CK_SLOT_TBS_BYTES */
54#define WAIT_S 5u
55
56static int usage(void)
57{
58 fprintf(stderr, "usage: ck_imac_netboot keygen KEY PUB | pubkey KEY | sign KEY TBS SIG |\n"
59 " serve SPOOL [--bcast A.B.C.D] [--mac xx:xx:xx:xx:xx:xx] [--seconds N]\n"
60 " [--qemu-dgram LOCALPORT:REMOTEPORT]\n");
61 return 2;
62}
63
64static void hex(const uint8_t *b, size_t n, char *out)
65{
66 static const char d[] = "0123456789abcdef";
67 for (size_t i = 0; i < n; i++) {
68 out[2 * i] = d[b[i] >> 4];
69 out[2 * i + 1] = d[b[i] & 15];
70 }
71 out[2 * n] = 0;
72}
73
74static int read_exact(const char *path, uint8_t *b, size_t n)
75{
76 int fd = open(path, O_RDONLY | O_CLOEXEC);
77 if (fd < 0)
78 return -1;
79 size_t got = 0;
80 while (got < n) {
81 ssize_t r = read(fd, b + got, n - got);
82 if (r <= 0)
83 break;
84 got += (size_t)r;
85 }
86 uint8_t extra;
87 int more = read(fd, &extra, 1) > 0;
88 close(fd);
89 return got == n && !more ? 0 : -1;
90}
91
92static int write_new(const char *path, const void *b, size_t n, mode_t mode, int excl)
93{
94 int fd = open(path, O_WRONLY | O_CREAT | O_CLOEXEC | (excl ? O_EXCL : O_TRUNC), mode);
95 if (fd < 0)
96 return -1;
97 int ok = write(fd, b, n) == (ssize_t)n;
98 return close(fd) == 0 && ok ? 0 : -1;
99}
100
101static int load_key(const char *path, uint8_t sk[32])
102{
103 struct stat st;
104 if (stat(path, &st) != 0 || (st.st_mode & 077) != 0) {
105 fprintf(stderr, "ck_imac_netboot: %s must exist and be readable by its owner only (0600)\n", path);
106 return -1;
107 }
108 if (read_exact(path, sk, 32) != 0) {
109 fprintf(stderr, "ck_imac_netboot: %s is not a 32-byte key\n", path);
110 return -1;
111 }
112 return 0;
113}
114
115static int cmd_keygen(const char *key, const char *pub)
116{
117 uint8_t sk[32], pk[32];
118 char h[65], text[160];
119 if (getrandom(sk, sizeof sk, 0) != (ssize_t)sizeof sk || aienos_ed25519_public_key(pk, sk) != AIENOS_SIG_OK) {
120 fprintf(stderr, "ck_imac_netboot: no randomness or key derivation failed\n");
121 return 3;
122 }
123 if (write_new(key, sk, sizeof sk, 0600, 1) != 0) {
124 fprintf(stderr, "ck_imac_netboot: cannot create %s (%s); an existing key is never overwritten\n", key,
125 strerror(errno));
126 memset(sk, 0, sizeof sk);
127 return 3;
128 }
129 memset(sk, 0, sizeof sk);
130 hex(pk, 32, h);
131 int n = snprintf(text, sizeof text, "# AIENOS lab netboot key (iMac NETLDR.EFI), public half\nowner_root_ed25519 %s\n", h);
132 if (write_new(pub, text, (size_t)n, 0644, 0) != 0) {
133 fprintf(stderr, "ck_imac_netboot: cannot write %s\n", pub);
134 return 3;
135 }
136 printf("keygen: public key %s\n", h);
137 return 0;
138}
139
140static int cmd_pubkey(const char *key)
141{
142 uint8_t sk[32], pk[32];
143 char h[65];
144 if (load_key(key, sk) != 0)
145 return 3;
146 int rc = aienos_ed25519_public_key(pk, sk);
147 memset(sk, 0, sizeof sk);
148 if (rc != AIENOS_SIG_OK)
149 return 3;
150 hex(pk, 32, h);
151 printf("%s\n", h);
152 return 0;
153}
154
155static int cmd_sign(const char *key, const char *tbs, const char *out)
156{
157 uint8_t sk[32], msg[TBS_BYTES], sig[64];
158 if (load_key(key, sk) != 0)
159 return 3;
160 if (read_exact(tbs, msg, sizeof msg) != 0) {
161 memset(sk, 0, sizeof sk);
162 fprintf(stderr, "ck_imac_netboot: %s is not %u to-be-signed bytes\n", tbs, TBS_BYTES);
163 return 3;
164 }
165 int rc = aienos_ed25519_sign(sig, msg, sizeof msg, sk);
166 memset(sk, 0, sizeof sk);
167 if (rc != AIENOS_SIG_OK || write_new(out, sig, sizeof sig, 0644, 0) != 0) {
168 fprintf(stderr, "ck_imac_netboot: signing failed\n");
169 return 3;
170 }
171 printf("sign: %s\n", out);
172 return 0;
173}
174
175/* ---- serve ------------------------------------------------------------------ */
176static int sock = -1, dgram = 0;
177static struct sockaddr_in peer;
178static const uint8_t host_mac[6] = {0x52, 0x54, 0x00, 0x4e, 0x42, 0x01};
179
180static void logf_(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
181static void logf_(const char *fmt, ...)
182{
183 char ts[32];
184 time_t t = time(0);
185 struct tm tm;
186 gmtime_r(&t, &tm);
187 strftime(ts, sizeof ts, "%Y-%m-%dT%H:%M:%SZ", &tm);
188 printf("%s ", ts);
189 va_list ap;
190 va_start(ap, fmt);
191 vprintf(fmt, ap);
192 va_end(ap);
193 printf("\n");
194 fflush(stdout);
195}
196
197static void send_msg(const struct nb_msg *m)
198{
199 uint8_t msg[NB_MSG_MAX];
200 size_t n = nb_build(m, msg, sizeof msg);
201 if (!n)
202 return;
203 if (!dgram) {
204 sendto(sock, msg, n, 0, (struct sockaddr *)&peer, sizeof peer);
205 return;
206 }
207 static uint8_t udp[8 + NB_MSG_MAX], ip[20 + sizeof udp], fr[14 + sizeof ip];
208 const net_ipv4 any = {{0, 0, 0, 0}}, bcast = {{255, 255, 255, 255}};
209 net_udp_header uh = {NB_PORT_SERVER, NB_PORT_LOADER};
210 net_ipv4_header ih = {0, 0, 1, NET_IPPROTO_UDP, any, bcast};
211 net_eth_frame e;
212 size_t uw, iw, ew;
213 if (net_udp_build(&uh, msg, n, any, bcast, udp, sizeof udp, &uw) != NET_OK ||
214 net_ipv4_build(&ih, udp, uw, ip, sizeof ip, &iw) != NET_OK)
215 return;
216 memset(e.destination.b, 0xff, 6);
217 memcpy(e.source.b, host_mac, 6);
218 e.ethertype = NET_ETHERTYPE_IPV4;
219 e.payload = ip;
220 e.payload_len = iw;
221 if (net_eth_build(&e, fr, sizeof fr, &ew) == NET_OK)
222 sendto(sock, fr, ew, 0, (struct sockaddr *)&peer, sizeof peer);
223}
224
225/* Receive one netboot message (payload view into buf). 0 or -1. */
226static int recv_msg(uint8_t *buf, size_t cap, struct nb_msg *m)
227{
228 ssize_t n = recv(sock, buf, cap, 0);
229 if (n <= 0)
230 return -1;
231 if (!dgram)
232 return nb_parse(buf, (size_t)n, m);
233 net_eth_frame e;
234 net_ipv4_header ih;
235 net_udp_header uh;
236 const uint8_t *ipp, *up;
237 size_t ipn, un;
238 if (net_eth_parse(buf, (size_t)n, &e) != NET_OK || e.ethertype != NET_ETHERTYPE_IPV4 ||
239 net_ipv4_parse(e.payload, e.payload_len, &ih, &ipp, &ipn) != NET_OK || ih.protocol != NET_IPPROTO_UDP ||
240 net_udp_parse(ipp, ipn, ih.source, ih.destination, &uh, &up, &un) != NET_OK ||
241 uh.destination_port != NB_PORT_SERVER || uh.source_port != NB_PORT_LOADER)
242 return -1;
243 return nb_parse(up, un, m);
244}
245
246static uint8_t *job;
247static uint32_t job_len;
248static uint8_t job_nonce[16];
249static int job_offered;
250/* Chunks sent at least once to the current nonce. A loader that got every chunk and
251 * then asks again with a new nonce without a DONE we heard has finished that transfer:
252 * the job is retired as unconfirmed, never offered again (no restart loop on one lost DONE). */
253static uint8_t *served;
254static uint32_t served_n;
255
256static void served_reset(void)
257{
258 free(served);
259 served = job ? calloc(1, nb_chunks(job_len) / 8 + 1) : 0;
260 served_n = 0;
261}
262
263static int load_job(const char *path)
264{
265 struct stat st;
266 if (stat(path, &st) != 0)
267 return -1;
268 if (st.st_size < (off_t)NB_OBJECT_MIN || st.st_size > (off_t)NB_OBJECT_MAX) {
269 logf_("job %s refused here: %lld bytes is outside %u..%u", path, (long long)st.st_size, NB_OBJECT_MIN,
270 NB_OBJECT_MAX);
271 return -1;
272 }
273 uint8_t *b = malloc((size_t)st.st_size);
274 if (!b || read_exact(path, b, (size_t)st.st_size) != 0) {
275 free(b);
276 logf_("job %s unreadable", path);
277 return -1;
278 }
279 free(job);
280 job = b;
281 job_len = (uint32_t)st.st_size;
282 job_offered = 0;
283 served_reset();
284 return 0;
285}
286
287static void retire_job(const char *spool, const char *how)
288{
289 char from[4096], to[4096];
290 snprintf(from, sizeof from, "%s/serving.job", spool);
291 snprintf(to, sizeof to, "%s/%s-%lld.job", spool, how, (long long)time(0));
292 rename(from, to);
293 free(job);
294 job = 0;
295 job_len = 0;
296 job_offered = 0;
297 served_reset();
298}
299
300static int parse_mac(const char *s, uint8_t mac[6])
301{
302 unsigned v[6];
303 if (sscanf(s, "%2x:%2x:%2x:%2x:%2x:%2x", &v[0], &v[1], &v[2], &v[3], &v[4], &v[5]) != 6)
304 return -1;
305 for (int i = 0; i < 6; i++)
306 mac[i] = (uint8_t)v[i];
307 return 0;
308}
309
310static int cmd_serve(int argc, char **argv)
311{
312 const char *spool = argv[2], *bcast = "255.255.255.255", *qd = 0;
313 uint8_t only_mac[6];
314 int have_mac = 0;
315 long seconds = 0;
316 for (int i = 3; i < argc; i++) {
317 if (i + 1 >= argc)
318 return usage();
319 if (strcmp(argv[i], "--bcast") == 0)
320 bcast = argv[++i];
321 else if (strcmp(argv[i], "--mac") == 0 && parse_mac(argv[i + 1], only_mac) == 0)
322 have_mac = 1, i++;
323 else if (strcmp(argv[i], "--seconds") == 0)
324 seconds = strtol(argv[++i], 0, 10);
325 else if (strcmp(argv[i], "--qemu-dgram") == 0)
326 qd = argv[++i];
327 else
328 return usage();
329 }
330 char next[4096], serving[4096];
331 snprintf(next, sizeof next, "%s/next.job", spool);
332 snprintf(serving, sizeof serving, "%s/serving.job", spool);
333
334 struct sockaddr_in me = {0};
335 me.sin_family = AF_INET;
336 peer.sin_family = AF_INET;
337 if (qd) {
338 unsigned lp, rp;
339 if (sscanf(qd, "%u:%u", &lp, &rp) != 2 || !lp || lp > 65535 || !rp || rp > 65535)
340 return usage();
341 dgram = 1;
342 me.sin_port = htons((uint16_t)lp);
343 me.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
344 peer.sin_port = htons((uint16_t)rp);
345 peer.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
346 } else {
347 me.sin_port = htons(NB_PORT_SERVER);
348 me.sin_addr.s_addr = htonl(INADDR_ANY);
349 peer.sin_port = htons(NB_PORT_LOADER);
350 if (inet_pton(AF_INET, bcast, &peer.sin_addr) != 1)
351 return usage();
352 }
353 int one = 1;
354 sock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
355 if (sock < 0 || setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one) != 0 ||
356 (!dgram && setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) != 0) ||
357 bind(sock, (struct sockaddr *)&me, sizeof me) != 0) {
358 fprintf(stderr, "ck_imac_netboot: socket/bind: %s\n", strerror(errno));
359 return 3;
360 }
361 if (load_job(serving) == 0)
362 logf_("resuming %s (%u bytes)", serving, job_len);
363 logf_("serving spool=%s transport=%s answer_to=%s:%u", spool, dgram ? "qemu-dgram" : "udp",
364 dgram ? "127.0.0.1" : bcast, dgram ? (unsigned)ntohs(peer.sin_port) : NB_PORT_LOADER);
365
366 time_t end = seconds > 0 ? time(0) + seconds : 0;
367 uint8_t buf[2048];
368 while (!end || time(0) < end) {
369 struct pollfd p = {sock, POLLIN, 0};
370 if (poll(&p, 1, 500) <= 0)
371 continue;
372 struct nb_msg m, r = {0};
373 if (recv_msg(buf, sizeof buf, &m) != 0)
374 continue;
375 memcpy(r.nonce, m.nonce, 16);
376 if (m.type == NB_HELLO) {
377 if (have_mac && memcmp(m.mac, only_mac, 6) != 0)
378 continue;
379 if (job && job_offered && memcmp(job_nonce, m.nonce, 16) != 0 && served_n == nb_chunks(job_len)) {
380 logf_("the loader got every chunk but no DONE was heard; retired as unconfirmed");
381 retire_job(spool, "unconfirmed");
382 }
383 if (!job && rename(next, serving) == 0 && load_job(serving) == 0)
384 logf_("queued job picked up (%u bytes)", job_len);
385 if (job) {
386 if (!job_offered || memcmp(job_nonce, m.nonce, 16) != 0)
387 logf_("offer %u bytes to %02x:%02x:%02x:%02x:%02x:%02x", job_len, m.mac[0], m.mac[1], m.mac[2],
388 m.mac[3], m.mac[4], m.mac[5]);
389 if (!job_offered || memcmp(job_nonce, m.nonce, 16) != 0)
390 served_reset();
391 memcpy(job_nonce, m.nonce, 16);
392 job_offered = 1;
393 r.type = NB_OFFER;
394 r.total = job_len;
395 } else {
396 r.type = NB_WAIT;
397 r.seconds = WAIT_S;
398 }
399 send_msg(&r);
400 } else if (m.type == NB_GET && job && job_offered && memcmp(job_nonce, m.nonce, 16) == 0) {
401 for (uint32_t i = 0; i < m.count; i++) {
402 uint64_t off = (uint64_t)m.offset + (uint64_t)i * NB_CHUNK;
403 if (off >= job_len)
404 break;
405 r.type = NB_DATA;
406 r.offset = (uint32_t)off;
407 r.len = (uint16_t)(job_len - off < NB_CHUNK ? job_len - off : NB_CHUNK);
408 r.data = job + off;
409 uint32_t c = (uint32_t)(off / NB_CHUNK);
410 if (served && !(served[c / 8] & (1u << (c % 8)))) {
411 served[c / 8] |= (uint8_t)(1u << (c % 8));
412 served_n++;
413 }
414 send_msg(&r);
415 }
416 } else if (m.type == NB_DONE && job && job_offered && memcmp(job_nonce, m.nonce, 16) == 0) {
417 char text[NB_TEXT_MAX + 1];
418 memcpy(text, m.data, m.len);
419 text[m.len] = 0;
420 logf_("loader says: %s (%s)", m.status == 0 ? "VERIFIED, starting" : "REFUSED", text);
421 retire_job(spool, m.status == 0 ? "booted" : "refused");
422 }
423 }
424 logf_("serve: deadline reached");
425 return 0;
426}
427
428int main(int argc, char **argv)
429{
430 if (argc == 4 && strcmp(argv[1], "keygen") == 0)
431 return cmd_keygen(argv[2], argv[3]);
432 if (argc == 3 && strcmp(argv[1], "pubkey") == 0)
433 return cmd_pubkey(argv[2]);
434 if (argc == 5 && strcmp(argv[1], "sign") == 0)
435 return cmd_sign(argv[2], argv[3], argv[4]);
436 if (argc >= 3 && strcmp(argv[1], "serve") == 0)
437 return cmd_serve(argc, argv);
438 return usage();
439}