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_slot_tool.c

1814 lines · 79321 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* ck_slot_tool -- host tool for the AIENOS native image slots
18 * (native/boot/slot_format.h, slot_select.c; native v1 plan P11, gate N7).
19 * Builds, signs, verifies and inspects slot manifests and control records,
20 * and simulates the loader's decision over them. Hosted C, test and
21 * provisioning tooling only, never part of an image. No outside libraries.
22 *
23 * ck_slot_tool selftest
24 * ck_slot_tool make-manifest --image F --generation N --out M
25 * [--policy-generation N] [--min-rollback N] [--commit HEX40]
26 * [--provenance TEXT] [--timestamp N] unsigned manifest (signature zero)
27 * ck_slot_tool show M print the manifest fields (structural check only)
28 * ck_slot_tool tbs M --pubkey HEX64 --out F the 448 to-be-signed bytes, for an
29 * offline signer: openssl pkeyutl -sign -inkey owner_root.pem -rawin -in F -out SIG
30 * (signer_id = SHA-256(pubkey) lies inside the signed bytes, so it is set
31 * before the bytes are emitted; attach-sig checks the same bytes)
32 * ck_slot_tool attach-sig M --sig SIG --out M2 --pubkey HEX64
33 * ck_slot_tool sign-test M --out M2 [--test2] RFC 8032 TEST 1 (or TEST 2) key. NEVER for hardware.
34 * ck_slot_tool verify M --image F (--keys FILE | --test-key) [--cap BYTES]
35 * FILE: tools/ck_owner_gen.c format, "owner_root_ed25519 <64 hex>"
36 * ck_slot_tool control-init --active 0|1 --out C
37 * ck_slot_tool control-show C
38 * ck_slot_tool stage C --slot N --generation N --out C2
39 * ck_slot_tool promote C --slot N --generation N --policy-generation N --out C2
40 * ck_slot_tool abandon C --out C2
41 * ck_slot_tool select (--control C | --no-control) --a M,IMG|none --b M,IMG|none
42 * (--keys FILE | --test-key) [--cap BYTES] [--out C2] loader decision;
43 * --out writes ctl_out when the loader would have to commit it
44 * ck_slot_tool control-commit --region F --record C torn-slot commit into a
45 * 4-unit region file (512-byte blocks), as the kernel/loader would
46 * ck_slot_tool control-recover --region F --out C
47 * ck_slot_tool keys-c (--keys FILE | --test-key) --out F.c trusted-key table
48 * compiled into SLOTLDR.EFI (native/boot/slot_loader.c)
49 * ck_slot_tool slots-image --disk IMG --bs 512|4096 --first LBA --last LBA
50 * [--a M,IMG] [--b M,IMG] [--control C] write a slots partition (control
51 * region, manifests, images) into a disk image where SLOTLDR.EFI reads it
52 * ck_slot_tool inbox-image --disk IMG --bs 512|4096 --first LBA --last LBA --m M,IMG
53 * write a signed candidate into the update inbox partition (P11 cut 3)
54 * Every refusal prints "refused: <reason>" and exits 1. */
55#include <errno.h>
56#include <stdarg.h>
57#include <stdint.h>
58#include <stdio.h>
59#include <stdlib.h>
60#include <string.h>
61#include "../../boot/slot_format.h"
62#include "../../sig/aienos_sig.h"
63#include "../../argus/sha256.h"
64#include "../../store/torn_slot.h"
65#include "../../boot/slot_control.h"
66#include "../../boot/slot_update.h"
67
68/* RFC 8032 section 7.1 TEST 1: seed and public key (the key ck_owner_gen refuses). */
69static const uint8_t TEST1_SEED[32] = {
70 0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec, 0x2c, 0xc4,
71 0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, 0x7f, 0x60};
72static const uint8_t TEST1_PK[32] = {
73 0xd7, 0x5a, 0x98, 0x01, 0x82, 0xb1, 0x0a, 0xb7, 0xd5, 0x4b, 0xfe, 0xd3, 0xc9, 0x64, 0x07, 0x3a,
74 0x0e, 0xe1, 0x72, 0xf3, 0xda, 0xa6, 0x23, 0x25, 0xaf, 0x02, 0x1a, 0x68, 0xf7, 0x07, 0x51, 0x1a};
75/* RFC 8032 section 7.1 TEST 2 seed: the "unknown signer" of the slot loader gate. */
76static const uint8_t TEST2_SEED[32] = {
77 0x4c, 0xcd, 0x08, 0x9b, 0x28, 0xff, 0x96, 0xda, 0x9d, 0xb6, 0xc3, 0x46, 0xec, 0x11, 0x4e, 0x0f,
78 0x5b, 0x8a, 0x31, 0x9f, 0x35, 0xab, 0xa6, 0x24, 0xda, 0x8c, 0xf6, 0xed, 0x4f, 0xb8, 0xa6, 0xfb};
79static const uint8_t TEST2_PK[32] = {
80 0x3d, 0x40, 0x17, 0xc3, 0xe8, 0x43, 0x89, 0x5a, 0x92, 0xb7, 0x0a, 0xa7, 0x4d, 0x1b, 0x7e, 0xbc,
81 0x9c, 0x98, 0x2c, 0xcf, 0x2e, 0xc4, 0x96, 0x8c, 0xc0, 0xcd, 0x55, 0xf1, 0x2a, 0xf4, 0x66, 0x0c};
82static const uint8_t TEST3_PK[32] = {
83 0xfc, 0x51, 0xcd, 0x8e, 0x62, 0x18, 0xa1, 0xa3, 0x8d, 0xa4, 0x7e, 0xd0, 0x02, 0x30, 0xf0, 0x58,
84 0x08, 0x16, 0xed, 0x13, 0xba, 0x33, 0x03, 0xac, 0x5d, 0xeb, 0x91, 0x15, 0x48, 0x90, 0x80, 0x25};
85
86#define MAX_KEYS 8u
87#define DEFAULT_CAP (16u * 1024u * 1024u)
88
89static int refuse(const char *why)
90{
91 printf("refused: %s\n", why);
92 return 1;
93}
94
95static int read_file(const char *path, uint8_t **out, size_t *len)
96{
97 FILE *f = fopen(path, "rb");
98 uint8_t *buf = 0;
99 size_t cap = 0, n = 0;
100 if (!f)
101 return -1;
102 for (;;) {
103 if (n == cap) {
104 cap = cap ? cap * 2 : 65536;
105 buf = realloc(buf, cap);
106 if (!buf) {
107 fclose(f);
108 return -1;
109 }
110 }
111 size_t r = fread(buf + n, 1, cap - n, f);
112 n += r;
113 if (r == 0)
114 break;
115 }
116 int err = ferror(f);
117 fclose(f);
118 if (err) {
119 free(buf);
120 return -1;
121 }
122 *out = buf;
123 *len = n;
124 return 0;
125}
126
127static int read_unit(const char *path, void *unit)
128{
129 uint8_t *b;
130 size_t n;
131 if (read_file(path, &b, &n) != 0)
132 return -1;
133 if (n != CK_SLOT_UNIT) {
134 free(b);
135 return -2;
136 }
137 memcpy(unit, b, CK_SLOT_UNIT);
138 free(b);
139 return 0;
140}
141
142static int write_file(const char *path, const void *p, size_t n)
143{
144 FILE *f = fopen(path, "wb");
145 if (!f)
146 return -1;
147 size_t w = fwrite(p, 1, n, f);
148 if (fclose(f) != 0 || w != n)
149 return -1;
150 return 0;
151}
152
153static int hexval(int c)
154{
155 if (c >= '0' && c <= '9')
156 return c - '0';
157 if (c >= 'a' && c <= 'f')
158 return c - 'a' + 10;
159 if (c >= 'A' && c <= 'F')
160 return c - 'A' + 10;
161 return -1;
162}
163
164static int parse_hex(const char *s, uint8_t *out, size_t n)
165{
166 if (strlen(s) != 2 * n)
167 return -1;
168 for (size_t i = 0; i < n; i++) {
169 int hi = hexval(s[2 * i]), lo = hexval(s[2 * i + 1]);
170 if (hi < 0 || lo < 0)
171 return -1;
172 out[i] = (uint8_t)(hi * 16 + lo);
173 }
174 return 0;
175}
176
177static int parse_u64(const char *s, uint64_t *v)
178{
179 char *end;
180 errno = 0;
181 if (!s || !*s)
182 return -1;
183 unsigned long long x = strtoull(s, &end, 10);
184 if (errno || *end)
185 return -1;
186 *v = x;
187 return 0;
188}
189
190static int is_test_key(const uint8_t pk[32])
191{
192 return memcmp(pk, TEST1_PK, 32) == 0 || memcmp(pk, TEST2_PK, 32) == 0 ||
193 memcmp(pk, TEST3_PK, 32) == 0;
194}
195
196/* Owner public keys file (tools/ck_owner_gen.c format). */
197static int load_keys(const char *path, uint8_t keys[MAX_KEYS][32], unsigned *nkeys, const char **why)
198{
199 uint8_t *b;
200 size_t n;
201 unsigned count = 0;
202 if (read_file(path, &b, &n) != 0) {
203 *why = "cannot read the keys file";
204 return -1;
205 }
206 char *text = malloc(n + 1);
207 if (!text) {
208 free(b);
209 *why = "out of memory";
210 return -1;
211 }
212 memcpy(text, b, n);
213 text[n] = 0;
214 free(b);
215 char *save = 0;
216 for (char *line = strtok_r(text, "\n", &save); line; line = strtok_r(0, "\n", &save)) {
217 while (*line == ' ' || *line == '\t' || *line == '\r')
218 line++;
219 if (*line == 0 || *line == '#')
220 continue;
221 char *name = line;
222 char *sp = strpbrk(line, " \t");
223 if (!sp) {
224 free(text);
225 *why = "keys file line without a value";
226 return -1;
227 }
228 *sp++ = 0;
229 while (*sp == ' ' || *sp == '\t')
230 sp++;
231 char *end = sp + strlen(sp);
232 while (end > sp && (end[-1] == ' ' || end[-1] == '\t' || end[-1] == '\r'))
233 *--end = 0;
234 if (strcmp(name, "owner_root_ed25519") != 0) {
235 free(text);
236 *why = "keys file names an unknown key";
237 return -1;
238 }
239 if (count == MAX_KEYS) {
240 free(text);
241 *why = "too many keys";
242 return -1;
243 }
244 if (parse_hex(sp, keys[count], 32) != 0) {
245 free(text);
246 *why = "owner_root_ed25519 is not 64 hex characters";
247 return -1;
248 }
249 {
250 uint8_t acc = 0;
251 for (unsigned i = 0; i < 32; i++)
252 acc |= (uint8_t)(keys[count][i] ^ keys[count][0]);
253 if (acc == 0) {
254 free(text);
255 *why = "owner key has all bytes equal";
256 return -1;
257 }
258 }
259 if (is_test_key(keys[count])) {
260 free(text);
261 *why = "owner key is a known TEST key (use --test-key for tests)";
262 return -1;
263 }
264 count++;
265 }
266 free(text);
267 if (count == 0) {
268 *why = "keys file holds no owner_root_ed25519";
269 return -1;
270 }
271 *nkeys = count;
272 return 0;
273}
274
275static void fill_manifest(struct ck_slot_manifest *m, const uint8_t *image, uint64_t image_len,
276 uint64_t generation, uint64_t policy_generation, uint64_t min_rollback,
277 const char *commit, const char *provenance, uint64_t timestamp)
278{
279 memset(m, 0, sizeof *m);
280 memcpy(m->magic, CK_SLOT_MANIFEST_MAGIC, 8);
281 m->version = CK_SLOT_MANIFEST_VERSION;
282 m->payload_kind = CK_SLOT_PAYLOAD_BOOTAA64;
283 m->loader_abi = CK_SLOT_LOADER_ABI;
284 m->kernel_abi = CK_SLOT_KERNEL_ABI;
285 m->generation = generation;
286 m->policy_generation = policy_generation;
287 m->min_rollback_generation = min_rollback;
288 m->image_len = image_len;
289 aienos_sha512(image, (size_t)image_len, m->image_sha512);
290 memcpy(m->kernel_sha512, m->image_sha512, 64);
291 memcpy(m->commit, commit, CK_SLOT_COMMIT_CHARS);
292 {
293 size_t pl = strlen(provenance);
294 if (pl > CK_SLOT_PROVENANCE_CHARS)
295 pl = CK_SLOT_PROVENANCE_CHARS;
296 memcpy(m->provenance, provenance, pl);
297 }
298 m->timestamp = timestamp;
299}
300
301static void sign_manifest(struct ck_slot_manifest *m, const uint8_t seed[32])
302{
303 uint8_t pk[32];
304 aienos_ed25519_public_key(pk, seed);
305 sha256_hash(pk, 32, m->signer_id);
306 aienos_ed25519_sign(m->signature, (const uint8_t *)m, CK_SLOT_TBS_BYTES, seed);
307}
308
309static const char *opt(int argc, char **argv, const char *name)
310{
311 for (int i = 2; i + 1 < argc; i++)
312 if (strcmp(argv[i], name) == 0)
313 return argv[i + 1];
314 return 0;
315}
316
317static int flag(int argc, char **argv, const char *name)
318{
319 for (int i = 2; i < argc; i++)
320 if (strcmp(argv[i], name) == 0)
321 return 1;
322 return 0;
323}
324
325static int get_keys(int argc, char **argv, uint8_t keys[MAX_KEYS][32], unsigned *nkeys)
326{
327 const char *why;
328 const char *kf = opt(argc, argv, "--keys");
329 if (flag(argc, argv, "--test-key")) {
330 memcpy(keys[0], TEST1_PK, 32);
331 *nkeys = 1;
332 printf("keys: RFC 8032 TEST 1 (tests only, never for hardware)\n");
333 return 0;
334 }
335 if (!kf)
336 return refuse("give --keys FILE or --test-key");
337 if (load_keys(kf, keys, nkeys, &why) != 0)
338 return refuse(why);
339 printf("keys: %u owner key(s) from %s\n", *nkeys, kf);
340 return 0;
341}
342
343static void print_control(const struct ck_slot_control *c)
344{
345 printf("control: active=%u candidate=%s tries=%u flags=0x%02x floor=%llu last_good=%llu\n",
346 c->active_slot,
347 c->candidate_slot == CK_SLOT_NONE ? "none" : (c->candidate_slot ? "1" : "0"),
348 c->tries_remaining, c->flags, (unsigned long long)c->generation_floor,
349 (unsigned long long)c->last_good_generation);
350}
351
352static void print_manifest(const struct ck_slot_manifest *m)
353{
354 printf("manifest: generation=%llu policy=%llu min_rollback=%llu image_len=%llu kernel_abi=%u loader_abi=%u timestamp=%llu\n",
355 (unsigned long long)m->generation, (unsigned long long)m->policy_generation,
356 (unsigned long long)m->min_rollback_generation, (unsigned long long)m->image_len,
357 m->kernel_abi, m->loader_abi, (unsigned long long)m->timestamp);
358 printf(" commit=%.40s provenance=%.64s\n", (const char *)m->commit, (const char *)m->provenance);
359 printf(" image_sha512=");
360 for (unsigned i = 0; i < 64; i++)
361 printf("%02x", m->image_sha512[i]);
362 printf("\n signer_id=");
363 for (unsigned i = 0; i < 32; i++)
364 printf("%02x", m->signer_id[i]);
365 printf("\n");
366}
367
368/* ---- file-backed torn-slot device (512-byte blocks) ------------------------ */
369struct filedev {
370 uint8_t *bytes;
371 size_t len;
372};
373
374static int fd_read(void *ctx, uint64_t lba, uint32_t count, uint8_t *buf)
375{
376 struct filedev *d = ctx;
377 if ((lba + count) * 512 > d->len)
378 return -1;
379 memcpy(buf, d->bytes + lba * 512, (size_t)count * 512);
380 return 0;
381}
382
383static int fd_write(void *ctx, uint64_t lba, uint32_t count, const uint8_t *buf)
384{
385 struct filedev *d = ctx;
386 if ((lba + count) * 512 > d->len)
387 return -1;
388 memcpy(d->bytes + lba * 512, buf, (size_t)count * 512);
389 return 0;
390}
391
392static int fd_flush(void *ctx)
393{
394 (void)ctx;
395 return 0;
396}
397
398static void bind_dev(ts_device *dev, struct filedev *d)
399{
400 dev->ctx = d;
401 dev->block_size = 512;
402 dev->block_count = d->len / 512;
403 dev->read = fd_read;
404 dev->write = fd_write;
405 dev->flush = fd_flush;
406}
407
408/* ---- keys-c rendering ------------------------------------------------------- */
409/* Bounded append: on truncation or an encoding error *n becomes cap, which the
410 * caller refuses as "key table too large"; never writes past buf[cap - 1] and
411 * never computes a size from an offset past cap. */
412static void app(char *buf, size_t cap, size_t *n, const char *fmt, ...)
413{
414 va_list ap;
415 int r;
416 if (*n >= cap)
417 return;
418 va_start(ap, fmt);
419 r = vsnprintf(buf + *n, cap - *n, fmt, ap);
420 va_end(ap);
421 if (r < 0 || (size_t)r >= cap - *n)
422 *n = cap;
423 else
424 *n += (size_t)r;
425}
426
427/* The C key table SLOTLDR.EFI is built with. Returns its length, or cap when
428 * it does not fit (the caller refuses). */
429static size_t keys_c_render(char *text, size_t cap, const uint8_t (*keys)[32], unsigned nkeys, int test)
430{
431 size_t n = 0;
432 app(text, cap, &n,
433 "/* Generated by ck_slot_tool keys-c (native/kernel/Makefile slot-loader). Do not edit. */\n"
434 "#include <stdint.h>\n"
435 "const unsigned ck_slot_loader_nkeys = %u;\n"
436 "const char ck_slot_loader_key_note[] = \"%s\";\n"
437 "const uint8_t ck_slot_loader_keys[%u][32] = {\n",
438 nkeys,
439 test ? "TEST-ONLY key (RFC 8032 TEST 1): never for hardware"
440 : "trusted keys: owner_root_ed25519 from CK_SLOT_KEYS",
441 nkeys);
442 for (unsigned k = 0; k < nkeys; k++) {
443 app(text, cap, &n, " {");
444 for (unsigned i = 0; i < 32; i++)
445 app(text, cap, &n, "0x%02x%s", keys[k][i], i == 31 ? "" : ", ");
446 app(text, cap, &n, "},\n");
447 }
448 app(text, cap, &n, "};\n");
449 return n;
450}
451
452/* ---- self-test ------------------------------------------------------------- */
453static unsigned g_checks, g_fails;
454
455static void check(int ok, const char *what)
456{
457 g_checks++;
458 if (!ok) {
459 g_fails++;
460 printf(" FAIL: %s\n", what);
461 }
462}
463
464static void expect_refused(const struct ck_slot_manifest *m, const uint8_t *img, uint64_t cap,
465 const uint8_t (*keys)[32], unsigned nkeys, const char *why, const char *what)
466{
467 struct ck_slot_eval ev;
468 ck_slot_verify(m, img, cap, keys, nkeys, &ev);
469 g_checks++;
470 if (ev.valid || !ev.why || strcmp(ev.why, why) != 0) {
471 g_fails++;
472 printf(" FAIL: %s: valid=%d why=%s (expected %s)\n", what, ev.valid, ev.why ? ev.why : "(none)", why);
473 }
474}
475
476/* ---- P11 cut 3: the inactive-slot updater (native/boot/slot_update.c) ------- */
477/* In-memory disk (512-byte blocks) with a write counter and an injected I/O
478 * error at one backend write index. */
479struct memdisk {
480 uint8_t *bytes;
481 uint64_t len;
482 long fail_at; /* backend write index that fails, -1 = none */
483 long writes;
484};
485static int md_read(void *ctx, uint64_t lba, uint32_t count, uint8_t *buf)
486{
487 struct memdisk *d = ctx;
488 if ((lba + count) * 512 > d->len)
489 return DISK_ERANGE;
490 memcpy(buf, d->bytes + lba * 512, (size_t)count * 512);
491 return DISK_OK;
492}
493static int md_write(void *ctx, uint64_t lba, uint32_t count, const uint8_t *buf)
494{
495 struct memdisk *d = ctx;
496 if (d->fail_at >= 0 && d->writes++ == d->fail_at)
497 return DISK_EIO;
498 if (d->fail_at < 0)
499 d->writes++;
500 if ((lba + count) * 512 > d->len)
501 return DISK_ERANGE;
502 memcpy(d->bytes + lba * 512, buf, (size_t)count * 512);
503 return DISK_OK;
504}
505static int md_flush(void *ctx)
506{
507 (void)ctx;
508 return DISK_OK;
509}
510static void md_bind(disk_dev *dd, ts_device *td, struct memdisk *m)
511{
512 dd->ctx = m;
513 dd->block_size = 512;
514 dd->block_count = m->len / 512;
515 dd->read = md_read;
516 dd->write = md_write;
517 dd->flush = md_flush;
518 dd->max_blocks_per_io = 64; /* 32 KiB: disk_write splits the updater's chunks */
519 if (td) {
520 td->ctx = m;
521 td->block_size = 512;
522 td->block_count = m->len / 512;
523 td->read = md_read;
524 td->write = md_write;
525 td->flush = md_flush;
526 }
527}
528
529#define UPD_SLOT_UNITS (4u + 2u * 80u) /* cap 80 units per slot */
530#define UPD_IMG_BYTES 300000u /* 74 units: two updater chunks */
531static uint8_t upd_slots[UPD_SLOT_UNITS * CK_SLOT_UNIT], upd_ref[sizeof upd_slots];
532static uint8_t upd_inbox[(1u + 90u) * CK_SLOT_UNIT];
533static uint8_t upd_buf[80u * CK_SLOT_UNIT];
534static uint8_t upd_img[UPD_IMG_BYTES];
535
536struct upd_rig {
537 struct memdisk ms, mi;
538 disk_dev slots, inbox;
539 ts_device tdev;
540 ts_region r;
541 struct ck_slot_control ctl;
542 struct ck_slot_update_io io;
543};
544
545/* Fresh media: slot A holds a valid generation-1 image and is active; slot B
546 * holds old bytes; the inbox holds manifest m and image img (inbox_units units). */
547static void upd_media(const struct ck_slot_manifest *m, const uint8_t *img, uint64_t len, uint64_t inbox_units)
548{
549 static struct ck_slot_manifest a;
550 struct memdisk md = {upd_slots, sizeof upd_slots, -1, 0};
551 disk_dev dd;
552 ts_device td;
553 ts_region r;
554 struct ck_slot_control c;
555 uint64_t seq;
556 uint64_t cap = ck_slot_cap_units(UPD_SLOT_UNITS);
557 memset(upd_slots, 0xEE, sizeof upd_slots); /* old bytes everywhere */
558 memset(upd_slots, 0, CK_SLOT_CONTROL_UNITS * CK_SLOT_UNIT);
559 fill_manifest(&a, upd_img, 5000, 1, 1, 1, "0123456789abcdef0123456789abcdef01234567", "slot A", 1700000000);
560 sign_manifest(&a, TEST1_SEED);
561 memcpy(upd_slots + ck_slot_manifest_unit(0, cap) * CK_SLOT_UNIT, &a, sizeof a);
562 memcpy(upd_slots + (ck_slot_manifest_unit(0, cap) + 1) * CK_SLOT_UNIT, upd_img, 5000);
563 md_bind(&dd, &td, &md);
564 ck_slot_control_init(&c, 0);
565 c.generation_floor = 1;
566 c.last_good_generation = 1;
567 if (ts_open(&r, &td, 0) != TS_OK || ts_recover(&r, (uint8_t *)&a, &seq, 0) != TS_EMPTY ||
568 ck_slot_control_commit(&r, &c, &seq) != TS_OK)
569 check(0, "update: rig control commit");
570 memcpy(upd_ref, upd_slots, sizeof upd_slots);
571 memset(upd_inbox, 0, sizeof upd_inbox);
572 memcpy(upd_inbox, m, sizeof *m);
573 memcpy(upd_inbox + CK_SLOT_UNIT, img, (size_t)len);
574 (void)inbox_units;
575}
576
577static int upd_stop_at(void *ctx, const char *step, uint64_t done, uint64_t total)
578{
579 (void)done;
580 (void)total;
581 return ctx && strcmp(step, (const char *)ctx) == 0;
582}
583
584static int upd_run_hook(struct upd_rig *g, uint64_t inbox_units, long fail_at, unsigned booted, const uint8_t (*keys)[32],
585 unsigned nkeys, const char *stop, struct ck_slot_update_result *res, const char **why)
586{
587 uint64_t seq;
588 memset(g, 0, sizeof *g);
589 g->ms = (struct memdisk){upd_slots, sizeof upd_slots, -1, 0};
590 g->mi = (struct memdisk){upd_inbox, inbox_units * CK_SLOT_UNIT, -1, 0};
591 md_bind(&g->slots, &g->tdev, &g->ms);
592 md_bind(&g->inbox, 0, &g->mi);
593 int have = ts_open(&g->r, &g->tdev, 0) == TS_OK && ts_recover(&g->r, (uint8_t *)&g->ctl, &seq, 0) == TS_OK;
594 g->ms.fail_at = fail_at;
595 g->ms.writes = 0;
596 g->io = (struct ck_slot_update_io){&g->slots, &g->inbox, &g->r, have ? &g->ctl : 0, booted, keys, nkeys,
597 upd_buf, sizeof upd_buf, upd_stop_at, (void *)stop};
598 return ck_slot_update(&g->io, res, why);
599}
600static int upd_run(struct upd_rig *g, uint64_t inbox_units, long fail_at, unsigned booted, const uint8_t (*keys)[32],
601 unsigned nkeys, struct ck_slot_update_result *res, const char **why)
602{
603 return upd_run_hook(g, inbox_units, fail_at, booted, keys, nkeys, 0, res, why);
604}
605
606/* The control record now on the slots media (NULL when none). */
607static const struct ck_slot_control *upd_control(void)
608{
609 static struct ck_slot_control c;
610 struct memdisk md = {upd_slots, sizeof upd_slots, -1, 0};
611 disk_dev dd;
612 ts_device td;
613 ts_region r;
614 uint64_t seq;
615 md_bind(&dd, &td, &md);
616 return ts_open(&r, &td, 0) == TS_OK && ts_recover(&r, (uint8_t *)&c, &seq, 0) == TS_OK ? &c : 0;
617}
618
619static int upd_same(uint64_t from_unit, uint64_t units)
620{
621 return memcmp(upd_slots + from_unit * CK_SLOT_UNIT, upd_ref + from_unit * CK_SLOT_UNIT, units * CK_SLOT_UNIT) == 0;
622}
623
624/* Slot s evaluated from the media, as the loader would. */
625static int upd_slot_valid(unsigned s, uint64_t *gen)
626{
627 uint64_t cap = ck_slot_cap_units(UPD_SLOT_UNITS), mu = ck_slot_manifest_unit(s, cap);
628 struct ck_slot_eval ev;
629 int ok = ck_slot_verify((const struct ck_slot_manifest *)(upd_slots + mu * CK_SLOT_UNIT),
630 upd_slots + (mu + 1) * CK_SLOT_UNIT, (cap - 1) * CK_SLOT_UNIT, &TEST1_PK, 1, &ev);
631 if (gen)
632 *gen = ev.generation;
633 return ok;
634}
635
636static void selftest_update(void)
637{
638 static struct upd_rig g;
639 static struct ck_slot_manifest m, bad;
640 struct ck_slot_update_result res;
641 const char *why;
642 const uint64_t cap = ck_slot_cap_units(UPD_SLOT_UNITS), au = ck_slot_manifest_unit(0, cap),
643 bu = ck_slot_manifest_unit(1, cap), inu = 1 + (UPD_IMG_BYTES + CK_SLOT_UNIT - 1) / CK_SLOT_UNIT;
644 const struct ck_slot_control *c;
645 uint64_t gen = 0;
646 uint32_t x = 0xC0FFEEu;
647 for (size_t i = 0; i < sizeof upd_img; i++) {
648 x = x * 1664525u + 1013904223u;
649 upd_img[i] = (uint8_t)(x >> 24);
650 }
651 fill_manifest(&m, upd_img, UPD_IMG_BYTES, 2, 2, 1, "89abcdef0123456789abcdef0123456789abcdef", "slot B update",
652 1700000100);
653 sign_manifest(&m, TEST1_SEED);
654
655 /* Positive: B written, verified, staged; A and the control region otherwise untouched. */
656 upd_media(&m, upd_img, UPD_IMG_BYTES, inu);
657 int rc = upd_run(&g, inu, -1, 0, &TEST1_PK, 1, &res, &why);
658 long total = g.ms.writes;
659 c = upd_control();
660 check(rc == 0 && res.target == 1 && res.generation == 2 && res.image_len == UPD_IMG_BYTES &&
661 res.units_written == inu,
662 "update: inbox image written into inactive slot B and staged");
663 check(c && c->active_slot == 0 && c->candidate_slot == 1 && c->tries_remaining == CK_SLOT_MAX_TRIES &&
664 c->generation_floor == 1,
665 "update: control record names B candidate, A stays active, floor unchanged");
666 check(upd_slot_valid(1, &gen) && gen == 2 && upd_slot_valid(0, 0) && upd_same(au, cap),
667 "update: slot B verifies from the disk bytes; slot A bytes unchanged");
668 {
669 struct ck_slot_eval ev[2];
670 struct ck_slot_decision d;
671 upd_slot_valid(0, 0);
672 ev[0] = (struct ck_slot_eval){1, 1, 1, 0};
673 ev[1] = (struct ck_slot_eval){1, 2, 2, 0};
674 ck_slot_select(c, ev, &d);
675 check(d.boot_slot == 1 && d.reason == CK_SLOT_R_CANDIDATE_TRY && d.loader_write,
676 "update: the loader's next decision is a candidate try of B");
677 struct ck_slot_control ex = *c;
678 ex.tries_remaining = 0;
679 ck_slot_select(&ex, ev, &d);
680 check(d.boot_slot == 0 && d.reason == CK_SLOT_R_CANDIDATE_EXHAUSTED,
681 "update: exhausted tries -> the loader boots A (rollback to the previous active)");
682 ev[1] = (struct ck_slot_eval){0, 0, 0, "x"};
683 ck_slot_select(c, ev, &d);
684 check(d.boot_slot == 0 && d.reason == CK_SLOT_R_CANDIDATE_INVALID,
685 "update: a failed (invalid) candidate -> the loader boots A");
686 }
687 check(upd_run(&g, inu, -1, 0, &TEST1_PK, 1, &res, &why) != 0 && !res.wrote && strstr(why, "already staged"),
688 "update: refused while a candidate is staged, nothing written");
689
690 /* An I/O error at every backend write: control record untouched (or the
691 * staging commit failed), slot A untouched, B invalid unless only the commit failed. */
692 {
693 int all = 1;
694 long n = 0;
695 for (long k = 0; k < total; k++, n++) {
696 upd_media(&m, upd_img, UPD_IMG_BYTES, inu);
697 rc = upd_run(&g, inu, k, 0, &TEST1_PK, 1, &res, &why);
698 c = upd_control();
699 int ctl_same = c && c->candidate_slot == CK_SLOT_NONE && c->active_slot == 0;
700 int b_ok = !upd_slot_valid(1, 0) || strstr(why, "staging commit") != 0;
701 if (rc == 0 || !ctl_same || !upd_same(au, cap) || !b_ok || !res.wrote)
702 all = 0;
703 }
704 char what[160];
705 snprintf(what, sizeof what,
706 "update: I/O error at each of %ld writes -> refused, A + control untouched, B invalid or unstaged", n);
707 check(all && total > 4, what);
708 }
709 /* Interrupted at each step (power cut model: the hook stops the run there). */
710 {
711 static const char *const steps[] = {"verified", "invalidated", "image", "manifest"};
712 for (unsigned s = 0; s < 4; s++) {
713 upd_media(&m, upd_img, UPD_IMG_BYTES, inu);
714 rc = upd_run_hook(&g, inu, -1, 0, &TEST1_PK, 1, steps[s], &res, &why);
715 c = upd_control();
716 char what[128];
717 snprintf(what, sizeof what, "update: stopped at \"%s\" -> refused, A + control untouched, B %s", steps[s],
718 s == 0 ? "untouched" : s == 3 ? "valid but not staged" : "invalid");
719 check(rc != 0 && c && c->candidate_slot == CK_SLOT_NONE && upd_same(au, cap) &&
720 (s == 0 ? upd_same(bu, cap) : s == 3 ? upd_slot_valid(1, 0) : !upd_slot_valid(1, 0)),
721 what);
722 }
723 }
724
725 /* Negative controls: refused before any write, the media byte-identical. */
726 {
727 struct {
728 const char *what;
729 int kind;
730 } neg[] = {
731 {"update: bad signature refused, nothing written", 1},
732 {"update: wrong key (TEST 2 signer) refused, nothing written", 2},
733 {"update: wrong digest (image byte flipped) refused, nothing written", 3},
734 {"update: truncated inbox refused, nothing written", 4},
735 {"update: generation at the floor refused (no rollback), nothing written", 5},
736 {"update: booted slot != active slot refused, nothing written", 6},
737 {"update: image with no trusted key refused, nothing written", 7},
738 {"update: no control record refused, nothing written", 8},
739 {"update: image larger than the slot refused, nothing written", 9},
740 {"update: corrupt inbox manifest refused, nothing written", 10},
741 };
742 for (unsigned i = 0; i < sizeof neg / sizeof neg[0]; i++) {
743 bad = m;
744 uint64_t in_units = inu;
745 unsigned booted = 0, nk = 1;
746 switch (neg[i].kind) {
747 case 1: bad.signature[7] ^= 1; break;
748 case 2: sign_manifest(&bad, TEST2_SEED); break;
749 case 4: in_units = inu - 3; break;
750 case 5:
751 fill_manifest(&bad, upd_img, UPD_IMG_BYTES, 1, 1, 1, "89abcdef0123456789abcdef0123456789abcdef",
752 "slot B old", 1700000100);
753 sign_manifest(&bad, TEST1_SEED);
754 break;
755 case 6: booted = 1; break;
756 case 7: nk = 0; break;
757 case 9: bad.image_len = (cap + 2) * CK_SLOT_UNIT; break;
758 case 10: bad.magic[0] ^= 1; break;
759 default: break;
760 }
761 upd_media(&bad, upd_img, UPD_IMG_BYTES, in_units);
762 if (neg[i].kind == 3)
763 upd_inbox[CK_SLOT_UNIT + 4242] ^= 0x40;
764 if (neg[i].kind == 8)
765 memset(upd_slots, 0, CK_SLOT_CONTROL_UNITS * CK_SLOT_UNIT), memcpy(upd_ref, upd_slots, sizeof upd_slots);
766 rc = upd_run(&g, in_units, -1, booted, &TEST1_PK, nk, &res, &why);
767 check(rc != 0 && !res.wrote && g.ms.writes == 0 && memcmp(upd_slots, upd_ref, sizeof upd_slots) == 0,
768 neg[i].what);
769 }
770 }
771}
772
773static int selftest(void)
774{
775 uint8_t keys[MAX_KEYS][32];
776 uint8_t pk[32];
777 static uint8_t img[10000];
778 struct ck_slot_manifest good, m;
779 struct ck_slot_eval ev;
780 const char *why;
781 uint32_t x = 0x12345678u;
782
783 for (size_t i = 0; i < sizeof img; i++) {
784 x = x * 1664525u + 1013904223u;
785 img[i] = (uint8_t)(x >> 24);
786 }
787 aienos_ed25519_public_key(pk, TEST1_SEED);
788 check(memcmp(pk, TEST1_PK, 32) == 0, "TEST 1 public key derives from the seed");
789 aienos_ed25519_public_key(pk, TEST2_SEED);
790 check(memcmp(pk, TEST2_PK, 32) == 0, "TEST 2 public key derives from the seed");
791 aienos_ed25519_public_key(pk, TEST1_SEED);
792 memcpy(keys[0], TEST1_PK, 32);
793
794 fill_manifest(&good, img, sizeof img, 7, 5, 3, "0123456789abcdef0123456789abcdef01234567",
795 "selftest build", 1760000000ull);
796 check(ck_slot_manifest_check(&good, &why) == 0, "unsigned manifest is structurally valid");
797 sign_manifest(&good, TEST1_SEED);
798 check(ck_slot_verify(&good, img, sizeof img, keys, 1, &ev) == 1, "signed manifest verifies");
799 check(ev.generation == 7 && ev.policy_generation == 5, "eval carries generation and policy");
800 check(ck_slot_verify(&good, img, sizeof img + 4096, keys, 1, &ev) == 1, "larger capacity still verifies");
801
802 /* Mutations: each must be refused with the named reason. */
803#define MUT(stmt, why_s, what) do { m = good; stmt; expect_refused(&m, img, sizeof img, keys, 1, why_s, what); } while (0)
804 MUT(m.magic[0] ^= 1, "bad magic", "magic");
805 MUT(m.version = 2, "unsupported manifest version", "version");
806 MUT(m.payload_kind = 2, "unsupported payload kind", "payload kind");
807 MUT(m.loader_abi = 2, "loader ABI mismatch", "loader abi");
808 MUT(m.kernel_abi = 2, "kernel ABI mismatch", "kernel abi");
809 MUT(m.generation = 0, "generation is zero", "generation 0");
810 MUT(m.policy_generation = 8, "policy_generation above generation", "policy above");
811 MUT(m.min_rollback_generation = 8, "min_rollback_generation above generation", "rollback above");
812 MUT(m.image_len = 0, "image_len is zero", "image_len 0");
813 MUT(m.kernel_sha512[3] ^= 1, "kernel_sha512 differs from image_sha512 (payload kind 1)", "kernel digest");
814 MUT(m.timestamp = 0, "timestamp is zero", "timestamp");
815 MUT(m.flags = 1, "flags nonzero", "flags");
816 MUT(m.reserved0 = 1, "reserved bytes nonzero", "reserved0");
817 MUT(m.reserved1[50] = 1, "reserved bytes nonzero", "reserved1");
818 MUT(m.pad[100] = 1, "pad nonzero", "pad");
819 MUT(m.commit[5] = 'A', "commit is not 40 lower-case hex characters", "commit upper");
820 MUT(m.commit[39] = 'g', "commit is not 40 lower-case hex characters", "commit non-hex");
821 MUT(m.provenance[2] = 0x01, "provenance is not zero-padded printable ASCII", "provenance control char");
822 MUT(m.provenance[63] = 'x', "provenance is not zero-padded printable ASCII", "provenance after terminator");
823 MUT(m.image_len = sizeof img + 1, "image_len exceeds the slot capacity", "image_len over capacity");
824 MUT(m.image_len = sizeof img - 1, "signature does not verify", "image_len changed under the signature");
825 MUT(m.generation = 9, "signature does not verify", "generation changed under the signature");
826 MUT(m.signer_id[0] ^= 1, "signer_id names no trusted key", "signer_id");
827 MUT(m.signature[10] ^= 1, "signature does not verify", "signature byte");
828 MUT(m.signature[63] ^= 0x80, "signature does not verify", "signature high bit");
829 MUT(m.image_sha512[0] ^= 1; m.kernel_sha512[0] ^= 1, "signature does not verify", "image digest under the signature");
830#undef MUT
831 {
832 static uint8_t img2[sizeof img];
833 memcpy(img2, img, sizeof img);
834 img2[sizeof img - 1] ^= 1;
835 ck_slot_verify(&good, img2, sizeof img, keys, 1, &ev);
836 check(!ev.valid && strcmp(ev.why, "image SHA-512 mismatch") == 0, "flipped image byte");
837 ck_slot_verify(&good, img, sizeof img - 1, keys, 1, &ev);
838 check(!ev.valid && strcmp(ev.why, "image_len exceeds the slot capacity") == 0, "capacity below image_len");
839 memcpy(keys[1], TEST2_PK, 32);
840 ck_slot_verify(&good, img, sizeof img, keys + 1, 1, &ev);
841 check(!ev.valid && strcmp(ev.why, "signer_id names no trusted key") == 0, "wrong key set");
842 ck_slot_verify(&good, img, sizeof img, keys, 0, &ev);
843 check(!ev.valid && strcmp(ev.why, "signer_id names no trusted key") == 0, "empty key set");
844 ck_slot_verify(&good, img, sizeof img, keys, 2, &ev);
845 check(ev.valid, "two-key set containing the signer verifies");
846 ck_slot_verify(&good, 0, sizeof img, keys, 1, &ev);
847 check(!ev.valid && strcmp(ev.why, "no image bytes") == 0, "null image");
848 /* A manifest signed by a key that is NOT in the set, but whose signer_id is forged
849 * to name a trusted key, must fail on the signature, not pass. */
850 m = good;
851 {
852 uint8_t other_seed[32];
853 memset(other_seed, 0x42, 32);
854 aienos_ed25519_sign(m.signature, (const uint8_t *)&m, CK_SLOT_TBS_BYTES, other_seed);
855 }
856 ck_slot_verify(&m, img, sizeof img, keys, 1, &ev);
857 check(!ev.valid && strcmp(ev.why, "signature does not verify") == 0, "forged signer_id with another key");
858 }
859
860 /* Control record structure. */
861 {
862 struct ck_slot_control c, d;
863 ck_slot_control_init(&c, 0);
864 check(ck_slot_control_check(&c, &why) == 0, "fresh control is valid");
865#define CMUT(stmt, why_s, what) do { d = c; stmt; g_checks++; if (ck_slot_control_check(&d, &why) == 0 || strcmp(why, why_s) != 0) { g_fails++; printf(" FAIL: control %s: %s\n", what, why ? why : "(accepted)"); } } while (0)
866 CMUT(d.magic[7] ^= 1, "bad control magic", "magic");
867 CMUT(d.version = 0, "unsupported control version", "version");
868 CMUT(d.active_slot = 2, "active_slot out of range", "active range");
869 CMUT(d.candidate_slot = 2, "candidate_slot out of range", "candidate range");
870 CMUT(d.candidate_slot = 0, "candidate_slot equals active_slot", "candidate == active");
871 CMUT(d.candidate_slot = 1; d.tries_remaining = 4, "tries_remaining above the bound", "tries bound");
872 CMUT(d.tries_remaining = 1, "tries_remaining without a candidate", "tries without candidate");
873 CMUT(d.flags = 2, "unknown control flags", "flags");
874 CMUT(d.generation_floor = 5; d.last_good_generation = 4, "last_good_generation below the floor", "last_good < floor");
875 CMUT(d.reserved[1000] = 1, "control reserved bytes nonzero", "reserved");
876#undef CMUT
877 }
878
879 /* Selection rules. */
880 {
881 struct ck_slot_control c;
882 struct ck_slot_eval e[2];
883 struct ck_slot_decision dec;
884#define EV(i, v, g) do { e[i].valid = (v); e[i].generation = (g); e[i].policy_generation = (g); e[i].why = 0; } while (0)
885 EV(0, 1, 5); EV(1, 1, 7);
886 ck_slot_select(0, e, &dec);
887 check(dec.boot_slot == -1 && dec.reason == CK_SLOT_R_RECOVERY_REQUIRED && !dec.loader_write,
888 "no control with signed images: recovery required, not rollback");
889 EV(0, 1, 7); EV(1, 1, 7);
890 ck_slot_select(0, e, &dec);
891 check(dec.boot_slot == -1 && dec.reason == CK_SLOT_R_RECOVERY_REQUIRED,
892 "no control with signed tie: recovery required");
893 EV(0, 0, 0); EV(1, 0, 0);
894 ck_slot_select(0, e, &dec);
895 check(dec.boot_slot == -1 && dec.reason == CK_SLOT_R_RECOVERY_REQUIRED, "no control, nothing valid: recovery");
896 ck_slot_control_init(&c, 0);
897 c.magic[0] ^= 1;
898 EV(0, 1, 5); EV(1, 1, 7);
899 ck_slot_select(&c, e, &dec);
900 check(dec.boot_slot == -1 && dec.reason == CK_SLOT_R_RECOVERY_REQUIRED,
901 "corrupt control with signed images: recovery required");
902
903 ck_slot_control_init(&c, 0);
904 EV(0, 1, 5); EV(1, 1, 7);
905 ck_slot_select(&c, e, &dec);
906 check(dec.boot_slot == 0 && dec.reason == CK_SLOT_R_ACTIVE && !dec.loader_write, "active boots, no write");
907 EV(0, 0, 0); EV(1, 1, 7);
908 ck_slot_select(&c, e, &dec);
909 check(dec.boot_slot == 1 && dec.reason == CK_SLOT_R_ACTIVE_INVALID_FALLBACK && !dec.loader_write, "active invalid: fallback to the other slot");
910 EV(0, 0, 0); EV(1, 0, 0);
911 ck_slot_select(&c, e, &dec);
912 check(dec.boot_slot == -1 && dec.reason == CK_SLOT_R_RECOVERY_REQUIRED, "both invalid: recovery");
913
914 /* Candidate tries, bounded. */
915 ck_slot_control_init(&c, 0);
916 c.generation_floor = 3;
917 c.last_good_generation = 5;
918 check(ck_slot_stage_candidate(&c, 1, 7, &why) == 0 && c.tries_remaining == 3, "stage candidate B gen 7");
919 EV(0, 1, 5); EV(1, 1, 7);
920 ck_slot_select(&c, e, &dec);
921 check(dec.boot_slot == 1 && dec.reason == CK_SLOT_R_CANDIDATE_TRY && dec.loader_write && dec.ctl_out.tries_remaining == 2, "candidate try 1: tries 3 -> 2, loader write");
922 c = dec.ctl_out;
923 ck_slot_select(&c, e, &dec);
924 check(dec.boot_slot == 1 && dec.loader_write && dec.ctl_out.tries_remaining == 1, "candidate try 2");
925 c = dec.ctl_out;
926 ck_slot_select(&c, e, &dec);
927 check(dec.boot_slot == 1 && dec.loader_write && dec.ctl_out.tries_remaining == 0, "candidate try 3");
928 c = dec.ctl_out;
929 check(ck_slot_control_check(&c, &why) == 0, "control with 0 tries and a candidate is valid");
930 ck_slot_select(&c, e, &dec);
931 check(dec.boot_slot == 0 && dec.reason == CK_SLOT_R_CANDIDATE_EXHAUSTED && !dec.loader_write, "tries exhausted: active boots, no write");
932 ck_slot_select(&c, e, &dec);
933 check(dec.boot_slot == 0 && dec.reason == CK_SLOT_R_CANDIDATE_EXHAUSTED, "exhausted again: deterministic, no loop");
934 EV(0, 0, 0);
935 ck_slot_select(&c, e, &dec);
936 check(dec.boot_slot == -1 && dec.reason == CK_SLOT_R_RECOVERY_REQUIRED, "exhausted candidate never boots on its own authority");
937 EV(0, 1, 5); EV(1, 0, 0);
938 c.tries_remaining = 3;
939 ck_slot_select(&c, e, &dec);
940 check(dec.boot_slot == 0 && dec.reason == CK_SLOT_R_CANDIDATE_INVALID && !dec.loader_write, "invalid candidate: active boots, tries untouched");
941 check(c.tries_remaining == 3, "select never mutates its input");
942
943 /* Floor. */
944 ck_slot_control_init(&c, 0);
945 c.generation_floor = 10;
946 EV(0, 1, 5); EV(1, 1, 12);
947 ck_slot_select(&c, e, &dec);
948 check(dec.boot_slot == 1 && dec.reason == CK_SLOT_R_ACTIVE_INVALID_FALLBACK, "active below the floor: fallback to B above it");
949 EV(1, 1, 9);
950 ck_slot_select(&c, e, &dec);
951 check(dec.boot_slot == -1 && dec.reason == CK_SLOT_R_RECOVERY_REQUIRED, "both below the floor: recovery");
952 check(ck_slot_stage_candidate(&c, 1, 9, &why) != 0 && strcmp(why, "candidate generation below the security floor") == 0, "stage below floor refused");
953 check(ck_slot_stage_candidate(&c, 0, 12, &why) != 0 && strcmp(why, "cannot stage the active slot as a candidate") == 0, "stage active slot refused");
954 check(ck_slot_stage_candidate(&c, 2, 12, &why) != 0, "stage slot 2 refused");
955 c.last_good_generation = 12;
956 check(ck_slot_stage_candidate(&c, 1, 12, &why) != 0 && strcmp(why, "candidate generation not above the last good generation") == 0, "stage not above last good refused");
957 check(ck_slot_stage_candidate(&c, 1, 13, &why) == 0, "stage gen 13 accepted");
958
959 /* Promotion. */
960 check(ck_slot_promote(&c, 0, 13, 11, &why) != 0 && strcmp(why, "only the staged candidate can be promoted") == 0, "promote non-candidate refused");
961 check(ck_slot_promote(&c, 1, 13, 14, &why) != 0 && strcmp(why, "policy_generation above generation") == 0, "promote with policy above generation refused");
962 check(ck_slot_promote(&c, 1, 13, 11, &why) == 0, "promote candidate");
963 check(c.active_slot == 1 && c.candidate_slot == CK_SLOT_NONE && c.tries_remaining == 0, "promotion flips active, clears candidate");
964 check(c.generation_floor == 11 && c.last_good_generation == 13, "promotion raises the floor to policy_generation");
965 check(ck_slot_stage_candidate(&c, 0, 14, &why) == 0 && ck_slot_promote(&c, 0, 14, 4, &why) == 0 && c.generation_floor == 11, "promotion never lowers the floor");
966 check(ck_slot_control_check(&c, &why) == 0, "control valid after two promotions");
967 check(ck_slot_abandon_candidate(&c, &why) != 0 && strcmp(why, "no candidate to abandon") == 0, "abandon without candidate refused");
968 check(ck_slot_stage_candidate(&c, 1, 15, &why) == 0 && ck_slot_abandon_candidate(&c, &why) == 0, "abandon candidate");
969 check(c.candidate_slot == CK_SLOT_NONE && c.tries_remaining == 0 && (c.flags & CK_SLOT_CTL_FLAG_CANDIDATE_FAILED), "abandon clears candidate, sets the failed flag");
970 check(ck_slot_stage_candidate(&c, 1, 16, &why) == 0 && !(c.flags & CK_SLOT_CTL_FLAG_CANDIDATE_FAILED), "a new stage clears the failed flag");
971 check(ck_slot_control_check(&c, &why) == 0, "control valid at the end of the transitions");
972 check(strcmp(ck_slot_reason_text(CK_SLOT_R_RECOVERY_REQUIRED), "recovery_required") == 0, "reason text");
973#undef EV
974 }
975
976 /* Torn-slot persistence of the control record over 512-byte blocks. */
977 {
978 static uint8_t media[CK_SLOT_CONTROL_UNITS * CK_SLOT_UNIT];
979 struct filedev fd = {media, sizeof media};
980 ts_device dev;
981 ts_region r;
982 uint8_t rec[TS_RECORD_BYTES];
983 uint64_t seq;
984 struct ck_slot_control c, back;
985 memset(media, 0, sizeof media);
986 bind_dev(&dev, &fd);
987 check(ts_open(&r, &dev, 0) == TS_OK, "torn-slot region opens at LBA 0");
988 check(ts_recover(&r, rec, &seq, 0) == TS_EMPTY, "blank region recovers EMPTY");
989 ck_slot_control_init(&c, 0);
990 c.generation_floor = 2;
991 check(ts_commit(&r, (const uint8_t *)&c) == TS_OK, "commit control #1");
992 check(ts_recover(&r, (uint8_t *)&back, &seq, 0) == TS_OK && memcmp(&back, &c, sizeof c) == 0 && seq == 1, "recover control #1");
993 check(ck_slot_stage_candidate(&c, 1, 9, &why) == 0 && ts_commit(&r, (const uint8_t *)&c) == TS_OK, "commit control #2 (staged)");
994 check(ts_recover(&r, (uint8_t *)&back, &seq, 0) == TS_OK && back.candidate_slot == 1 && seq == 2, "recover control #2");
995 /* Torn write: the next target is the slot that does NOT hold seq 2.
996 * Overwrite only the first 512 bytes of that body (as a power cut
997 * after one block would) and make sure #2 still comes back. */
998 {
999 int target = r.newest_slot == 0 ? 1 : 0;
1000 uint8_t partial[512];
1001 memset(partial, 0xEE, sizeof partial);
1002 fd_write(&fd, (uint64_t)target * 2u * 8u, 1, partial);
1003 check(ts_recover(&r, (uint8_t *)&back, &seq, 0) == TS_OK && seq == 2 && back.candidate_slot == 1, "torn body: previous record still recovered");
1004 }
1005 check(ck_slot_control_check(&back, &why) == 0, "recovered control is structurally valid");
1006 }
1007
1008 /* P11 cut 2b: the boot record SLOTLDR.EFI hands the kernel, and the pure
1009 * kernel decision over it (svc/slot_service.c). Every check that flips one
1010 * field must be refused; every scenario names the action and the record. */
1011 {
1012 static struct ck_slot_boot_record b, bm;
1013 static struct ck_slot_control c, out;
1014 static struct ck_slot_manifest man;
1015 enum ck_slot_action a;
1016 fill_manifest(&man, img, sizeof img, 9, 4, 0, "0123456789abcdef0123456789abcdef01234567",
1017 "selftest candidate", 1760000000ull);
1018 memset(&b, 0, sizeof b);
1019 memcpy(b.magic, CK_SLOT_BOOT_MAGIC, 8);
1020 b.version = CK_SLOT_BOOT_VERSION;
1021 b.boot_slot = 1;
1022 b.reason = CK_SLOT_R_CANDIDATE_TRY;
1023 b.tries = 2;
1024 b.control_present = 1;
1025 b.control_seq = 5;
1026 b.generation = man.generation;
1027 b.policy_generation = man.policy_generation;
1028 memcpy(b.image_sha512, man.image_sha512, 64);
1029 memcpy(b.loader_commit, "0123456789abcdef0123456789abcdef01234567", 40);
1030 ck_slot_boot_seal(&b);
1031 check(ck_slot_boot_check(&b, &why) == 0, "boot record: sealed record is valid");
1032#define BM(stmt, want, what) \
1033 do { \
1034 bm = b; \
1035 stmt; \
1036 ck_slot_boot_seal(&bm); \
1037 check(ck_slot_boot_check(&bm, &why) != 0 && strcmp(why, want) == 0, "boot record: " what); \
1038 } while (0)
1039 bm = b;
1040 bm.tries ^= 1;
1041 check(ck_slot_boot_check(&bm, &why) != 0 && strcmp(why, "boot record digest mismatch") == 0,
1042 "boot record: one changed byte without a reseal refused (digest)");
1043 BM(bm.magic[0] ^= 1, "bad boot record magic", "bad magic refused");
1044 BM(bm.version = 2, "unsupported boot record version", "version 2 refused");
1045 BM(bm.boot_slot = 2, "boot record slot out of range", "slot 2 refused");
1046 BM(bm.reason = CK_SLOT_R_NONE, "boot record reason out of range", "reason none refused");
1047 BM(bm.reason = CK_SLOT_R_RECOVERY_REQUIRED, "boot record reason out of range", "reason recovery_required refused");
1048 BM(bm.control_present = 2, "boot record control flag out of range", "control flag 2 refused");
1049 BM(bm.tries = CK_SLOT_MAX_TRIES + 1, "boot record tries above the bound", "tries above the bound refused");
1050 BM(bm.generation = 0, "boot record generation fields", "generation 0 refused");
1051 BM(bm.policy_generation = bm.generation + 1, "boot record generation fields", "policy above generation refused");
1052 BM(bm.reserved[79] = 1, "boot record reserved bytes nonzero", "reserved byte refused");
1053 BM(bm.control_present = 0, "boot record claims a decision without a control record",
1054 "decision without control refused");
1055 BM(bm.reason = CK_SLOT_R_NO_CONTROL, "boot record claims no control with a control record",
1056 "no_control with a control record refused");
1057#undef BM
1058
1059 /* Candidate B on its try, control still names it. */
1060 ck_slot_control_init(&c, 0);
1061 c.generation_floor = 1;
1062 check(ck_slot_stage_candidate(&c, 1, 9, &why) == 0, "kernel action: fixture staged");
1063 c.tries_remaining = 2;
1064 a = ck_slot_kernel_action(&b, &c, &man, 0, &out, &why);
1065 check(a == CK_SLOT_A_WAIT && strcmp(why, "health milestone not reached") == 0,
1066 "kernel action: candidate not healthy -> WAIT (nothing written)");
1067 a = ck_slot_kernel_action(&b, &c, &man, 1, &out, &why);
1068 check(a == CK_SLOT_A_PROMOTE && out.active_slot == 1 && out.candidate_slot == CK_SLOT_NONE &&
1069 out.tries_remaining == 0 && out.generation_floor == 4 && out.last_good_generation == 9 &&
1070 ck_slot_control_check(&out, &why) == 0,
1071 "kernel action: healthy candidate -> PROMOTE (active=B, floor=policy 4, last_good=9)");
1072 check(ck_slot_kernel_action(&b, 0, &man, 1, &out, &why) == CK_SLOT_A_REFUSE &&
1073 strcmp(why, "no control record on disk") == 0,
1074 "kernel action: no control record -> REFUSE");
1075 out = c;
1076 out.version = 9;
1077 check(ck_slot_kernel_action(&b, &out, &man, 1, &out, &why) == CK_SLOT_A_REFUSE,
1078 "kernel action: corrupt control record -> REFUSE");
1079 check(ck_slot_kernel_action(&b, &c, 0, 1, &out, &why) == CK_SLOT_A_REFUSE &&
1080 strcmp(why, "started slot's manifest unreadable") == 0,
1081 "kernel action: unreadable manifest -> REFUSE");
1082 m = man;
1083 m.image_sha512[0] ^= 1;
1084 m.kernel_sha512[0] ^= 1; /* v1: kernel_sha512 == image_sha512, so the manifest stays well formed */
1085 check(ck_slot_kernel_action(&b, &c, &m, 1, &out, &why) == CK_SLOT_A_REFUSE &&
1086 strcmp(why, "started slot's manifest on disk differs from the boot record") == 0,
1087 "kernel action: manifest digest differs from the boot record -> REFUSE");
1088 m = man;
1089 m.generation = 10;
1090 check(ck_slot_kernel_action(&b, &c, &m, 1, &out, &why) == CK_SLOT_A_REFUSE,
1091 "kernel action: manifest generation differs from the boot record -> REFUSE");
1092 bm = b;
1093 bm.digest[0] ^= 1;
1094 check(ck_slot_kernel_action(&bm, &c, &man, 1, &out, &why) == CK_SLOT_A_REFUSE &&
1095 strcmp(why, "boot record digest mismatch") == 0,
1096 "kernel action: damaged boot record -> REFUSE");
1097 out = c;
1098 out.candidate_slot = CK_SLOT_NONE;
1099 out.tries_remaining = 0;
1100 check(ck_slot_kernel_action(&b, &out, &man, 1, &out, &why) == CK_SLOT_A_NONE,
1101 "kernel action: control no longer names the started slot -> NONE");
1102
1103 /* A booted because B ran out of tries / failed verification. */
1104 fill_manifest(&m, img, sizeof img, 3, 1, 0, "0123456789abcdef0123456789abcdef01234567", "selftest active",
1105 1760000000ull);
1106 bm = b;
1107 bm.boot_slot = 0;
1108 bm.reason = CK_SLOT_R_CANDIDATE_EXHAUSTED;
1109 bm.tries = 0;
1110 bm.generation = 3;
1111 bm.policy_generation = 1;
1112 memcpy(bm.image_sha512, m.image_sha512, 64);
1113 ck_slot_boot_seal(&bm);
1114 c.tries_remaining = 0;
1115 a = ck_slot_kernel_action(&bm, &c, &m, 0, &out, &why);
1116 check(a == CK_SLOT_A_ABANDON && out.active_slot == 0 && out.candidate_slot == CK_SLOT_NONE &&
1117 (out.flags & CK_SLOT_CTL_FLAG_CANDIDATE_FAILED) && out.generation_floor == 1 &&
1118 ck_slot_control_check(&out, &why) == 0,
1119 "kernel action: exhausted candidate -> ABANDON (failed flag, active A stays, not gated on health)");
1120 bm.reason = CK_SLOT_R_CANDIDATE_INVALID;
1121 ck_slot_boot_seal(&bm);
1122 check(ck_slot_kernel_action(&bm, &c, &m, 1, &out, &why) == CK_SLOT_A_ABANDON,
1123 "kernel action: invalid candidate -> ABANDON");
1124 bm.reason = CK_SLOT_R_ACTIVE;
1125 ck_slot_boot_seal(&bm);
1126 check(ck_slot_kernel_action(&bm, &c, &m, 1, &out, &why) == CK_SLOT_A_NONE,
1127 "kernel action: steady active boot -> NONE");
1128 bm.reason = CK_SLOT_R_CANDIDATE_EXHAUSTED;
1129 bm.boot_slot = 1;
1130 memcpy(bm.image_sha512, man.image_sha512, 64);
1131 bm.generation = 9;
1132 bm.policy_generation = 4;
1133 ck_slot_boot_seal(&bm);
1134 check(ck_slot_kernel_action(&bm, &c, &man, 1, &out, &why) == CK_SLOT_A_NONE,
1135 "kernel action: exhausted reason on the non-active slot -> NONE (never abandons its own active)");
1136 check(strcmp(ck_slot_action_text(CK_SLOT_A_PROMOTE), "promote") == 0, "action text");
1137 }
1138
1139 /* The shared control-commit routine: commit, read back, sequence. */
1140 {
1141 static uint8_t media[CK_SLOT_CONTROL_UNITS * CK_SLOT_UNIT];
1142 struct filedev fd = {media, sizeof media};
1143 ts_device dev;
1144 ts_region r;
1145 uint64_t seq = 0, s2 = 0;
1146 static struct ck_slot_control c, back;
1147 memset(media, 0, sizeof media);
1148 bind_dev(&dev, &fd);
1149 check(ts_open(&r, &dev, 0) == TS_OK && ts_recover(&r, (uint8_t *)&back, &seq, 0) == TS_EMPTY,
1150 "control commit: blank region");
1151 ck_slot_control_init(&c, 0);
1152 check(ck_slot_control_commit(&r, &c, &seq) == TS_OK && seq == 1, "control commit: first record seq 1");
1153 check(ck_slot_stage_candidate(&c, 1, 2, &why) == 0 && ck_slot_control_commit(&r, &c, &s2) == TS_OK && s2 == 2,
1154 "control commit: second record seq 2");
1155 check(ts_recover(&r, (uint8_t *)&back, &seq, 0) == TS_OK && seq == 2 && memcmp(&back, &c, sizeof c) == 0,
1156 "control commit: read back equals what was committed");
1157 }
1158
1159 /* keys-c rendering: bounded, refuses instead of overflowing. */
1160 {
1161 static char kt[8192], small[sizeof kt];
1162 size_t full = keys_c_render(kt, sizeof kt, &TEST1_PK, 1, 1);
1163 check(full > 0 && full < sizeof kt && strstr(kt, "TEST-ONLY key") != 0, "keys-c: TEST key table renders");
1164 check(keys_c_render(small, full + 1, &TEST1_PK, 1, 1) == full && memcmp(small, kt, full) == 0,
1165 "keys-c: exact-fit buffer gives the same bytes");
1166 check(keys_c_render(small, full, &TEST1_PK, 1, 1) == full, "keys-c: one byte short is refused (length = cap)");
1167 check(keys_c_render(small, 64, &TEST1_PK, 1, 1) == 64, "keys-c: a 64-byte buffer is refused (length = cap)");
1168 memset(keys, 0x5a, sizeof keys);
1169 check(keys_c_render(small, 512, (const uint8_t (*)[32])keys, MAX_KEYS, 0) == 512,
1170 "keys-c: eight keys into 512 bytes refused, no write past the buffer");
1171 }
1172
1173 selftest_update();
1174
1175 printf("CK_SLOT_TOOL_SELFTEST: %s (%u checks, %u failures)\n", g_fails ? "FAIL" : "PASS", g_checks, g_fails);
1176 return g_fails ? 1 : 0;
1177}
1178
1179/* ---- CLI ------------------------------------------------------------------- */
1180static int cmd_make_manifest(int argc, char **argv)
1181{
1182 const char *image = opt(argc, argv, "--image"), *out = opt(argc, argv, "--out");
1183 const char *commit = opt(argc, argv, "--commit"), *prov = opt(argc, argv, "--provenance");
1184 uint64_t gen, pol = 0, minrb = 0, ts = 1;
1185 uint8_t *img;
1186 size_t len;
1187 struct ck_slot_manifest m;
1188 const char *why;
1189 if (!image || !out || parse_u64(opt(argc, argv, "--generation"), &gen) != 0)
1190 return refuse("make-manifest needs --image, --generation and --out");
1191 if (opt(argc, argv, "--policy-generation") && parse_u64(opt(argc, argv, "--policy-generation"), &pol) != 0)
1192 return refuse("bad --policy-generation");
1193 if (opt(argc, argv, "--min-rollback") && parse_u64(opt(argc, argv, "--min-rollback"), &minrb) != 0)
1194 return refuse("bad --min-rollback");
1195 if (opt(argc, argv, "--timestamp") && parse_u64(opt(argc, argv, "--timestamp"), &ts) != 0)
1196 return refuse("bad --timestamp");
1197 if (!commit)
1198 commit = "0000000000000000000000000000000000000000";
1199 if (strlen(commit) != CK_SLOT_COMMIT_CHARS)
1200 return refuse("--commit must be 40 characters");
1201 if (!prov)
1202 prov = "unspecified";
1203 if (strlen(prov) > CK_SLOT_PROVENANCE_CHARS)
1204 return refuse("--provenance longer than 64 characters");
1205 if (read_file(image, &img, &len) != 0)
1206 return refuse("cannot read the image");
1207 if (len == 0)
1208 return refuse("image is empty");
1209 fill_manifest(&m, img, len, gen, pol, minrb, commit, prov, ts);
1210 free(img);
1211 if (ck_slot_manifest_check(&m, &why) != 0)
1212 return refuse(why);
1213 if (write_file(out, &m, sizeof m) != 0)
1214 return refuse("cannot write the manifest");
1215 print_manifest(&m);
1216 printf("manifest written (unsigned): %s\n", out);
1217 return 0;
1218}
1219
1220static int load_manifest(const char *path, struct ck_slot_manifest *m)
1221{
1222 int rc = read_unit(path, m);
1223 if (rc == -1)
1224 return refuse("cannot read the manifest");
1225 if (rc == -2)
1226 return refuse("manifest is not exactly 4096 bytes");
1227 return 0;
1228}
1229
1230static int cmd_show(int argc, char **argv)
1231{
1232 struct ck_slot_manifest m;
1233 const char *why;
1234 if (argc < 3)
1235 return refuse("show M");
1236 if (load_manifest(argv[2], &m) != 0)
1237 return 1;
1238 print_manifest(&m);
1239 if (ck_slot_manifest_check(&m, &why) != 0)
1240 return refuse(why);
1241 printf("structure: OK (signature not checked; use verify)\n");
1242 return 0;
1243}
1244
1245static int cmd_tbs(int argc, char **argv)
1246{
1247 struct ck_slot_manifest m;
1248 const char *out = opt(argc, argv, "--out"), *pkh = opt(argc, argv, "--pubkey");
1249 uint8_t pk[32];
1250 if (argc < 3 || !out || !pkh)
1251 return refuse("tbs M --pubkey HEX64 --out F");
1252 if (load_manifest(argv[2], &m) != 0)
1253 return 1;
1254 if (parse_hex(pkh, pk, 32) != 0)
1255 return refuse("--pubkey is not 64 hex characters");
1256 if (is_test_key(pk))
1257 return refuse("--pubkey is a known TEST key");
1258 /* signer_id is inside the signed bytes [0, CK_SLOT_TBS_BYTES): attach-sig and
1259 * the loader check the signature over the manifest with signer_id set, so the
1260 * offline signer must sign those same bytes. */
1261 sha256_hash(pk, 32, m.signer_id);
1262 if (write_file(out, &m, CK_SLOT_TBS_BYTES) != 0)
1263 return refuse("cannot write the to-be-signed bytes");
1264 printf("tbs: %u bytes written to %s\n", CK_SLOT_TBS_BYTES, out);
1265 return 0;
1266}
1267
1268static int cmd_sign_test(int argc, char **argv)
1269{
1270 struct ck_slot_manifest m;
1271 const char *out = opt(argc, argv, "--out");
1272 const char *why;
1273 if (argc < 3 || !out)
1274 return refuse("sign-test M --out M2");
1275 if (load_manifest(argv[2], &m) != 0)
1276 return 1;
1277 sign_manifest(&m, flag(argc, argv, "--test2") ? TEST2_SEED : TEST1_SEED);
1278 if (ck_slot_manifest_check(&m, &why) != 0)
1279 return refuse(why);
1280 if (write_file(out, &m, sizeof m) != 0)
1281 return refuse("cannot write the manifest");
1282 printf("signed with RFC 8032 TEST %d: tests only, NEVER for hardware (ck_owner_gen refuses this key)\n",
1283 flag(argc, argv, "--test2") ? 2 : 1);
1284 return 0;
1285}
1286
1287static int cmd_attach_sig(int argc, char **argv)
1288{
1289 struct ck_slot_manifest m;
1290 const char *out = opt(argc, argv, "--out"), *sigf = opt(argc, argv, "--sig"), *pkh = opt(argc, argv, "--pubkey");
1291 uint8_t *sig, pk[32];
1292 size_t n;
1293 const char *why;
1294 if (argc < 3 || !out || !sigf || !pkh)
1295 return refuse("attach-sig M --sig SIG --out M2 --pubkey HEX64");
1296 if (load_manifest(argv[2], &m) != 0)
1297 return 1;
1298 if (parse_hex(pkh, pk, 32) != 0)
1299 return refuse("--pubkey is not 64 hex characters");
1300 if (is_test_key(pk))
1301 return refuse("--pubkey is a known TEST key");
1302 if (read_file(sigf, &sig, &n) != 0)
1303 return refuse("cannot read the signature");
1304 if (n != 64) {
1305 free(sig);
1306 return refuse("signature is not 64 bytes");
1307 }
1308 sha256_hash(pk, 32, m.signer_id);
1309 memcpy(m.signature, sig, 64);
1310 free(sig);
1311 if (aienos_ed25519_verify(m.signature, (const uint8_t *)&m, CK_SLOT_TBS_BYTES, pk) != AIENOS_SIG_OK)
1312 return refuse("signature does not verify under --pubkey over the manifest's to-be-signed bytes");
1313 if (ck_slot_manifest_check(&m, &why) != 0)
1314 return refuse(why);
1315 if (write_file(out, &m, sizeof m) != 0)
1316 return refuse("cannot write the manifest");
1317 printf("signature attached and verified: %s\n", out);
1318 return 0;
1319}
1320
1321static uint64_t cap_opt(int argc, char **argv)
1322{
1323 uint64_t cap = DEFAULT_CAP;
1324 if (opt(argc, argv, "--cap") && parse_u64(opt(argc, argv, "--cap"), &cap) != 0)
1325 return 0;
1326 return cap;
1327}
1328
1329static int cmd_verify(int argc, char **argv)
1330{
1331 struct ck_slot_manifest m;
1332 struct ck_slot_eval ev;
1333 uint8_t keys[MAX_KEYS][32];
1334 unsigned nkeys;
1335 uint8_t *img;
1336 size_t len;
1337 const char *image = opt(argc, argv, "--image");
1338 uint64_t cap = cap_opt(argc, argv);
1339 if (argc < 3 || !image || !cap)
1340 return refuse("verify M --image F (--keys FILE | --test-key) [--cap BYTES]");
1341 if (load_manifest(argv[2], &m) != 0)
1342 return 1;
1343 if (get_keys(argc, argv, keys, &nkeys) != 0)
1344 return 1;
1345 if (read_file(image, &img, &len) != 0)
1346 return refuse("cannot read the image");
1347 if (m.image_len != len) {
1348 free(img);
1349 return refuse("image file length differs from manifest image_len");
1350 }
1351 ck_slot_verify(&m, img, cap, keys, nkeys, &ev);
1352 free(img);
1353 print_manifest(&m);
1354 if (!ev.valid)
1355 return refuse(ev.why);
1356 printf("verify: OK generation=%llu\n", (unsigned long long)ev.generation);
1357 return 0;
1358}
1359
1360static int load_control(const char *path, struct ck_slot_control *c)
1361{
1362 const char *why;
1363 int rc = read_unit(path, c);
1364 if (rc == -1)
1365 return refuse("cannot read the control record");
1366 if (rc == -2)
1367 return refuse("control record is not exactly 4096 bytes");
1368 if (ck_slot_control_check(c, &why) != 0)
1369 return refuse(why);
1370 return 0;
1371}
1372
1373static int save_control(const char *path, const struct ck_slot_control *c)
1374{
1375 if (write_file(path, c, sizeof *c) != 0)
1376 return refuse("cannot write the control record");
1377 print_control(c);
1378 printf("control written: %s\n", path);
1379 return 0;
1380}
1381
1382static int cmd_control_init(int argc, char **argv)
1383{
1384 struct ck_slot_control c;
1385 uint64_t active;
1386 const char *out = opt(argc, argv, "--out");
1387 if (!out || parse_u64(opt(argc, argv, "--active"), &active) != 0 || active > 1)
1388 return refuse("control-init --active 0|1 --out C");
1389 ck_slot_control_init(&c, (unsigned)active);
1390 return save_control(out, &c);
1391}
1392
1393static int cmd_control_show(int argc, char **argv)
1394{
1395 struct ck_slot_control c;
1396 if (argc < 3)
1397 return refuse("control-show C");
1398 if (load_control(argv[2], &c) != 0)
1399 return 1;
1400 print_control(&c);
1401 return 0;
1402}
1403
1404static int cmd_transition(int argc, char **argv, const char *which)
1405{
1406 struct ck_slot_control c;
1407 const char *out = opt(argc, argv, "--out"), *why = 0;
1408 uint64_t slot = 0, gen = 0, pol = 0;
1409 int rc;
1410 if (argc < 3 || !out)
1411 return refuse("needs the control file and --out");
1412 if (load_control(argv[2], &c) != 0)
1413 return 1;
1414 if (strcmp(which, "abandon") != 0) {
1415 if (parse_u64(opt(argc, argv, "--slot"), &slot) != 0 || parse_u64(opt(argc, argv, "--generation"), &gen) != 0)
1416 return refuse("needs --slot and --generation");
1417 }
1418 if (strcmp(which, "stage") == 0)
1419 rc = ck_slot_stage_candidate(&c, (unsigned)slot, gen, &why);
1420 else if (strcmp(which, "promote") == 0) {
1421 if (parse_u64(opt(argc, argv, "--policy-generation"), &pol) != 0)
1422 return refuse("promote needs --policy-generation");
1423 rc = ck_slot_promote(&c, (unsigned)slot, gen, pol, &why);
1424 } else
1425 rc = ck_slot_abandon_candidate(&c, &why);
1426 if (rc != 0)
1427 return refuse(why);
1428 return save_control(out, &c);
1429}
1430
1431static int load_slot(const char *spec, uint64_t cap, const uint8_t (*keys)[32], unsigned nkeys,
1432 struct ck_slot_eval *ev, const char *name)
1433{
1434 struct ck_slot_manifest m;
1435 uint8_t *img;
1436 size_t len;
1437 char path[1024];
1438 const char *comma;
1439 ev->valid = 0;
1440 ev->why = "absent";
1441 ev->generation = 0;
1442 ev->policy_generation = 0;
1443 if (!spec || strcmp(spec, "none") == 0)
1444 return 0;
1445 comma = strchr(spec, ',');
1446 if (!comma || (size_t)(comma - spec) >= sizeof path)
1447 return refuse("slot spec must be MANIFEST,IMAGE or none");
1448 memcpy(path, spec, (size_t)(comma - spec));
1449 path[comma - spec] = 0;
1450 if (read_unit(path, &m) != 0) {
1451 printf("slot %s: manifest unreadable or not 4096 bytes, treated as invalid\n", name);
1452 ev->why = "manifest unreadable";
1453 return 0;
1454 }
1455 if (read_file(comma + 1, &img, &len) != 0) {
1456 printf("slot %s: image unreadable, treated as invalid\n", name);
1457 ev->why = "image unreadable";
1458 return 0;
1459 }
1460 ck_slot_verify(&m, img, len < cap ? len : cap, keys, nkeys, ev);
1461 if (ev->valid && m.image_len != len) {
1462 ev->valid = 0;
1463 ev->why = "image file length differs from manifest image_len";
1464 }
1465 free(img);
1466 return 0;
1467}
1468
1469static int cmd_select(int argc, char **argv)
1470{
1471 struct ck_slot_control c, *ctl = 0;
1472 struct ck_slot_eval ev[2];
1473 struct ck_slot_decision d;
1474 uint8_t keys[MAX_KEYS][32];
1475 unsigned nkeys;
1476 const char *cf = opt(argc, argv, "--control"), *out = opt(argc, argv, "--out");
1477 uint64_t cap = cap_opt(argc, argv);
1478 if (!cap || (!cf && !flag(argc, argv, "--no-control")))
1479 return refuse("select (--control C | --no-control) --a M,IMG|none --b M,IMG|none (--keys FILE | --test-key) [--cap BYTES] [--out C2]");
1480 if (get_keys(argc, argv, keys, &nkeys) != 0)
1481 return 1;
1482 if (cf) {
1483 const char *why;
1484 int rc = read_unit(cf, &c);
1485 if (rc == 0 && ck_slot_control_check(&c, &why) == 0)
1486 ctl = &c;
1487 else
1488 printf("control: unreadable or corrupt, recovery required\n");
1489 }
1490 if (load_slot(opt(argc, argv, "--a"), cap, keys, nkeys, &ev[0], "A") != 0)
1491 return 1;
1492 if (load_slot(opt(argc, argv, "--b"), cap, keys, nkeys, &ev[1], "B") != 0)
1493 return 1;
1494 for (unsigned i = 0; i < 2; i++)
1495 printf("slot %c: %s%s%s generation=%llu\n", 'A' + i, ev[i].valid ? "valid" : "invalid",
1496 ev[i].valid ? "" : " (", ev[i].valid ? "" : ev[i].why, (unsigned long long)ev[i].generation);
1497 if (ctl)
1498 print_control(ctl);
1499 ck_slot_select(ctl, ev, &d);
1500 printf("decision: boot_slot=%s reason=%s loader_write=%d\n",
1501 d.boot_slot < 0 ? "none" : (d.boot_slot ? "B" : "A"), ck_slot_reason_text(d.reason), d.loader_write);
1502 if (d.loader_write) {
1503 print_control(&d.ctl_out);
1504 if (out && write_file(out, &d.ctl_out, sizeof d.ctl_out) != 0)
1505 return refuse("cannot write ctl_out");
1506 }
1507 return d.boot_slot < 0 ? 2 : 0;
1508}
1509
1510static int cmd_control_commit(int argc, char **argv)
1511{
1512 const char *region = opt(argc, argv, "--region"), *recf = opt(argc, argv, "--record");
1513 struct ck_slot_control c;
1514 uint8_t *bytes;
1515 size_t len;
1516 struct filedev fd;
1517 ts_device dev;
1518 ts_region r;
1519 uint8_t rec[TS_RECORD_BYTES];
1520 uint64_t seq;
1521 int rc;
1522 if (!region || !recf)
1523 return refuse("control-commit --region F --record C");
1524 if (load_control(recf, &c) != 0)
1525 return 1;
1526 if (read_file(region, &bytes, &len) != 0)
1527 return refuse("cannot read the region file");
1528 if (len != CK_SLOT_CONTROL_UNITS * CK_SLOT_UNIT) {
1529 free(bytes);
1530 return refuse("region file must be exactly 4 units (16384 bytes)");
1531 }
1532 fd.bytes = bytes;
1533 fd.len = len;
1534 bind_dev(&dev, &fd);
1535 if (ts_open(&r, &dev, 0) != TS_OK)
1536 return refuse("torn-slot open failed");
1537 rc = ts_recover(&r, rec, &seq, 0);
1538 if (rc != TS_OK && rc != TS_EMPTY) {
1539 free(bytes);
1540 return refuse("region is corrupt or conflicting: fail closed, not committing");
1541 }
1542 if (ts_commit(&r, (const uint8_t *)&c) != TS_OK) {
1543 free(bytes);
1544 return refuse("torn-slot commit failed");
1545 }
1546 if (write_file(region, bytes, len) != 0) {
1547 free(bytes);
1548 return refuse("cannot write the region file");
1549 }
1550 free(bytes);
1551 printf("control committed: seq=%llu into %s\n", (unsigned long long)r.newest_seq, region);
1552 return 0;
1553}
1554
1555static int cmd_control_recover(int argc, char **argv)
1556{
1557 const char *region = opt(argc, argv, "--region"), *out = opt(argc, argv, "--out");
1558 uint8_t *bytes;
1559 size_t len;
1560 struct filedev fd;
1561 ts_device dev;
1562 ts_region r;
1563 struct ck_slot_control c;
1564 uint64_t seq;
1565 ts_slot_state st[2];
1566 int rc;
1567 const char *why;
1568 if (!region)
1569 return refuse("control-recover --region F [--out C]");
1570 if (read_file(region, &bytes, &len) != 0)
1571 return refuse("cannot read the region file");
1572 if (len != CK_SLOT_CONTROL_UNITS * CK_SLOT_UNIT) {
1573 free(bytes);
1574 return refuse("region file must be exactly 4 units (16384 bytes)");
1575 }
1576 fd.bytes = bytes;
1577 fd.len = len;
1578 bind_dev(&dev, &fd);
1579 if (ts_open(&r, &dev, 0) != TS_OK)
1580 return refuse("torn-slot open failed");
1581 rc = ts_recover(&r, (uint8_t *)&c, &seq, st);
1582 free(bytes);
1583 printf("torn-slot: rc=%d slotA=%d slotB=%d\n", rc, (int)st[0], (int)st[1]);
1584 if (rc == TS_EMPTY) {
1585 printf("control: none committed (loader rule: no control)\n");
1586 return 2;
1587 }
1588 if (rc != TS_OK)
1589 return refuse("region is corrupt or conflicting");
1590 if (ck_slot_control_check(&c, &why) != 0)
1591 return refuse(why);
1592 printf("seq=%llu\n", (unsigned long long)seq);
1593 print_control(&c);
1594 if (out && write_file(out, &c, sizeof c) != 0)
1595 return refuse("cannot write the control record");
1596 return 0;
1597}
1598
1599/* keys-c: the trusted-key table SLOTLDR.EFI is built with (native/kernel
1600 * Makefile slot-loader). --keys FILE takes owner keys (TEST keys refused by
1601 * load_keys); --test-key embeds RFC 8032 TEST 1 and a TEST-ONLY note that the
1602 * Makefile's slot loader checks look for. Writes F only when it changes. */
1603static int cmd_keys_c(int argc, char **argv)
1604{
1605 uint8_t keys[MAX_KEYS][32];
1606 unsigned nkeys = 0;
1607 const char *out = opt(argc, argv, "--out"), *kf = opt(argc, argv, "--keys"), *why;
1608 int test = flag(argc, argv, "--test-key");
1609 char text[8192];
1610 size_t n = 0;
1611 uint8_t *old;
1612 size_t oldn;
1613 if (!out || (test == !!kf))
1614 return refuse("keys-c (--keys FILE | --test-key) --out F.c");
1615 if (test) {
1616 memcpy(keys[0], TEST1_PK, 32);
1617 nkeys = 1;
1618 } else if (load_keys(kf, keys, &nkeys, &why) != 0) {
1619 return refuse(why);
1620 }
1621 n = keys_c_render(text, sizeof text, (const uint8_t (*)[32])keys, nkeys, test);
1622 if (n >= sizeof text)
1623 return refuse("key table too large");
1624 if (read_file(out, &old, &oldn) == 0) {
1625 int same = oldn == n && memcmp(old, text, n) == 0;
1626 free(old);
1627 if (same) {
1628 printf("keys-c: %u key(s), %s unchanged\n", nkeys, out);
1629 return 0;
1630 }
1631 }
1632 if (write_file(out, text, n) != 0)
1633 return refuse("cannot write the key table");
1634 printf("keys-c: %u key(s)%s written to %s\n", nkeys, test ? " (TEST-ONLY)" : "", out);
1635 return 0;
1636}
1637
1638/* slots-image: write a slots partition's content into a disk image, at the
1639 * partition's LBAs, exactly where SLOTLDR.EFI reads it (slot_format.h
1640 * geometry): the control region (zeroed, then the record committed through
1641 * the torn-slot protocol when --control is given), and for each slot its
1642 * manifest unit and image (or a zero manifest unit when absent). Test and
1643 * provisioning tooling for the QEMU gate scripts/qemu_ck_slot_loader_test.sh.
1644 * slots-image --disk IMG --bs 512|4096 --first LBA --last LBA
1645 * [--a M,IMG] [--b M,IMG] [--control C]
1646 * Prints "slots: units=U cap_units=C image_cap=B control_off=O a_off=X b_off=Y"
1647 * (byte offsets in the disk image). */
1648static int put_slot(FILE *f, const char *spec, uint64_t off, uint64_t cap, const char *name)
1649{
1650 static uint8_t zero[CK_SLOT_UNIT];
1651 struct ck_slot_manifest m;
1652 uint8_t *img = 0;
1653 size_t len = 0;
1654 char path[1024];
1655 const char *comma;
1656 if (fseeko(f, (off_t)off, SEEK_SET) != 0)
1657 return refuse("seek failed");
1658 if (!spec) {
1659 if (fwrite(zero, 1, sizeof zero, f) != sizeof zero)
1660 return refuse("write failed");
1661 printf("slot %s: empty (zero manifest unit)\n", name);
1662 return 0;
1663 }
1664 comma = strchr(spec, ',');
1665 if (!comma || (size_t)(comma - spec) >= sizeof path)
1666 return refuse("slot spec must be MANIFEST,IMAGE");
1667 memcpy(path, spec, (size_t)(comma - spec));
1668 path[comma - spec] = 0;
1669 if (load_manifest(path, &m) != 0)
1670 return 1;
1671 if (read_file(comma + 1, &img, &len) != 0)
1672 return refuse("cannot read the slot image");
1673 if (len > cap) {
1674 free(img);
1675 return refuse("slot image larger than the slot capacity");
1676 }
1677 if (fwrite(&m, 1, sizeof m, f) != sizeof m || fwrite(img, 1, len, f) != len) {
1678 free(img);
1679 return refuse("write failed");
1680 }
1681 if (len % CK_SLOT_UNIT && fwrite(zero, 1, CK_SLOT_UNIT - len % CK_SLOT_UNIT, f) != CK_SLOT_UNIT - len % CK_SLOT_UNIT) {
1682 free(img);
1683 return refuse("write failed");
1684 }
1685 free(img);
1686 printf("slot %s: manifest + %zu image bytes\n", name, len);
1687 return 0;
1688}
1689
1690static int cmd_slots_image(int argc, char **argv)
1691{
1692 const char *disk = opt(argc, argv, "--disk"), *cf = opt(argc, argv, "--control");
1693 uint64_t bsz, first, last;
1694 static uint8_t region[CK_SLOT_CONTROL_UNITS * CK_SLOT_UNIT];
1695 if (!disk || parse_u64(opt(argc, argv, "--bs"), &bsz) != 0 || (bsz != 512 && bsz != 4096) ||
1696 parse_u64(opt(argc, argv, "--first"), &first) != 0 || parse_u64(opt(argc, argv, "--last"), &last) != 0 ||
1697 last < first)
1698 return refuse("slots-image --disk IMG --bs 512|4096 --first LBA --last LBA [--a M,IMG] [--b M,IMG] [--control C]");
1699 uint64_t units = (last - first + 1) * bsz / CK_SLOT_UNIT, cap_units = ck_slot_cap_units(units);
1700 if (cap_units < CK_SLOT_MIN_CAP_UNITS)
1701 return refuse("partition too small for two slots");
1702 uint64_t base = first * bsz, cap = (cap_units - 1) * CK_SLOT_UNIT;
1703 uint64_t a_off = base + ck_slot_manifest_unit(0, cap_units) * CK_SLOT_UNIT;
1704 uint64_t b_off = base + ck_slot_manifest_unit(1, cap_units) * CK_SLOT_UNIT;
1705 memset(region, 0, sizeof region);
1706 if (cf) {
1707 struct ck_slot_control c;
1708 struct filedev fd = {region, sizeof region};
1709 ts_device dev;
1710 ts_region r;
1711 uint8_t rec[TS_RECORD_BYTES];
1712 uint64_t seq;
1713 if (load_control(cf, &c) != 0)
1714 return 1;
1715 bind_dev(&dev, &fd);
1716 if (ts_open(&r, &dev, 0) != TS_OK || ts_recover(&r, rec, &seq, 0) != TS_EMPTY ||
1717 ts_commit(&r, (const uint8_t *)&c) != TS_OK)
1718 return refuse("torn-slot commit into the fresh region failed");
1719 print_control(&c);
1720 }
1721 FILE *f = fopen(disk, "r+b");
1722 if (!f)
1723 return refuse("cannot open the disk image");
1724 if (fseeko(f, (off_t)base, SEEK_SET) != 0 || fwrite(region, 1, sizeof region, f) != sizeof region) {
1725 fclose(f);
1726 return refuse("control region write failed");
1727 }
1728 if (put_slot(f, opt(argc, argv, "--a"), a_off, cap, "A") != 0 ||
1729 put_slot(f, opt(argc, argv, "--b"), b_off, cap, "B") != 0) {
1730 fclose(f);
1731 return 1;
1732 }
1733 if (fclose(f) != 0)
1734 return refuse("disk image close failed");
1735 printf("slots: units=%llu cap_units=%llu image_cap=%llu control_off=%llu a_off=%llu b_off=%llu\n",
1736 (unsigned long long)units, (unsigned long long)cap_units, (unsigned long long)cap,
1737 (unsigned long long)base, (unsigned long long)a_off, (unsigned long long)b_off);
1738 return 0;
1739}
1740
1741/* inbox-image: write a signed candidate (manifest + image) into the update
1742 * inbox partition of a disk image (CK_SLOT_INBOX_TYPE, one slot's shape:
1743 * manifest at unit 0, image from unit 1), where the kernel verb `update`
1744 * reads it (native/boot/slot_update.h). The rest of the partition is zeroed.
1745 * inbox-image --disk IMG --bs 512|4096 --first LBA --last LBA --m M,IMG */
1746static int cmd_inbox_image(int argc, char **argv)
1747{
1748 const char *disk = opt(argc, argv, "--disk"), *spec = opt(argc, argv, "--m");
1749 uint64_t bsz, first, last;
1750 static uint8_t zero[CK_SLOT_UNIT];
1751 if (!disk || !spec || parse_u64(opt(argc, argv, "--bs"), &bsz) != 0 || (bsz != 512 && bsz != 4096) ||
1752 parse_u64(opt(argc, argv, "--first"), &first) != 0 || parse_u64(opt(argc, argv, "--last"), &last) != 0 ||
1753 last < first)
1754 return refuse("inbox-image --disk IMG --bs 512|4096 --first LBA --last LBA --m M,IMG");
1755 uint64_t units = (last - first + 1) * bsz / CK_SLOT_UNIT;
1756 if (units < 2)
1757 return refuse("inbox partition too small");
1758 FILE *f = fopen(disk, "r+b");
1759 if (!f)
1760 return refuse("cannot open the disk image");
1761 for (uint64_t u = 0; u < units; u++)
1762 if (fseeko(f, (off_t)(first * bsz + u * CK_SLOT_UNIT), SEEK_SET) != 0 || fwrite(zero, 1, sizeof zero, f) != sizeof zero) {
1763 fclose(f);
1764 return refuse("inbox clear failed");
1765 }
1766 if (put_slot(f, spec, first * bsz, (units - 1) * CK_SLOT_UNIT, "inbox") != 0) {
1767 fclose(f);
1768 return 1;
1769 }
1770 if (fclose(f) != 0)
1771 return refuse("disk image close failed");
1772 printf("inbox: units=%llu image_cap=%llu off=%llu\n", (unsigned long long)units,
1773 (unsigned long long)((units - 1) * CK_SLOT_UNIT), (unsigned long long)(first * bsz));
1774 return 0;
1775}
1776
1777int main(int argc, char **argv)
1778{
1779 if (argc < 2)
1780 return refuse("no mode (see the header of ck_slot_tool.c)");
1781 if (strcmp(argv[1], "selftest") == 0)
1782 return selftest();
1783 if (strcmp(argv[1], "make-manifest") == 0)
1784 return cmd_make_manifest(argc, argv);
1785 if (strcmp(argv[1], "show") == 0)
1786 return cmd_show(argc, argv);
1787 if (strcmp(argv[1], "tbs") == 0)
1788 return cmd_tbs(argc, argv);
1789 if (strcmp(argv[1], "sign-test") == 0)
1790 return cmd_sign_test(argc, argv);
1791 if (strcmp(argv[1], "attach-sig") == 0)
1792 return cmd_attach_sig(argc, argv);
1793 if (strcmp(argv[1], "verify") == 0)
1794 return cmd_verify(argc, argv);
1795 if (strcmp(argv[1], "control-init") == 0)
1796 return cmd_control_init(argc, argv);
1797 if (strcmp(argv[1], "control-show") == 0)
1798 return cmd_control_show(argc, argv);
1799 if (strcmp(argv[1], "stage") == 0 || strcmp(argv[1], "promote") == 0 || strcmp(argv[1], "abandon") == 0)
1800 return cmd_transition(argc, argv, argv[1]);
1801 if (strcmp(argv[1], "select") == 0)
1802 return cmd_select(argc, argv);
1803 if (strcmp(argv[1], "control-commit") == 0)
1804 return cmd_control_commit(argc, argv);
1805 if (strcmp(argv[1], "keys-c") == 0)
1806 return cmd_keys_c(argc, argv);
1807 if (strcmp(argv[1], "slots-image") == 0)
1808 return cmd_slots_image(argc, argv);
1809 if (strcmp(argv[1], "inbox-image") == 0)
1810 return cmd_inbox_image(argc, argv);
1811 if (strcmp(argv[1], "control-recover") == 0)
1812 return cmd_control_recover(argc, argv);
1813 return refuse("unknown mode");
1814}