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 / crates / aienos-store-tool / src / main.rs

492 lines · 17791 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//! Host tooling for System Store v1 QEMU qualification images.
17//!
18//! Test-only. Every byte this tool writes is derived from the kernel's own
19//! `store::v1` encoder and CRC, so the qualification scripts carry no second
20//! implementation of the format.
21//!
22//! Commands:
23//! cfg IMAGE BYTE_OFFSET MODE SETTLE [RESPONSE_HEX]
24//! Write the 4096-byte qualification control block.
25//! tear-closure OLD NEW STORE_BYTE_OFFSET SECTOR_BYTES
26//! Prove that every sector-granular tear of the one superblock write that
27//! separates OLD from NEW leaves either the old or the new slot bytes.
28//! operator-respond KEY_HEX CHALLENGE_HEX
29//! Recovery Core operator response (HMAC-SHA256, kernel OperatorAuth).
30//! corrupt-kind IMAGE STORE_BYTE_OFFSET REGION_UNITS KIND
31//! Flip one byte in the first object of KIND (identity-loss tests).
32//! inject IMAGE STORE_BYTE_OFFSET SLOT|inactive CASE [SOURCE]
33//! Overwrite superblock SLOT with one deterministic defect (see `CASES`).
34
35use std::env;
36use std::fs::{self, OpenOptions};
37use std::io::{Read, Seek, SeekFrom, Write};
38use std::process::ExitCode;
39
40use aienos_kernel::store::v1::{
41 crc32c, FormatError, Superblock, STORE_UNIT_BYTES, SUPERBLOCK_CRC_OFFSET,
42};
43
44type Unit = [u8; STORE_UNIT_BYTES];
45
46/// Injection cases. Every case except `bad_crc` and `seeded_garbage` keeps a
47/// valid CRC, so each one reaches exactly the check it names.
48const CASES: &[&str] = &[
49 "bad_crc",
50 "wrong_magic",
51 "nonzero_reserved",
52 "wrong_slot_id",
53 "region_mismatch",
54 "unsupported_version",
55 "seeded_garbage",
56 "new_root",
57];
58
59fn main() -> ExitCode {
60 let args: Vec<String> = env::args().skip(1).collect();
61 let result = match args.first().map(String::as_str) {
62 Some("cfg") => cfg(&args[1..]),
63 Some("tear-closure") => tear_closure(&args[1..]),
64 Some("inject") => inject(&args[1..]),
65 Some("operator-respond") => operator_respond(&args[1..]),
66 Some("corrupt-kind") => corrupt_kind(&args[1..]),
67 _ => Err(format!(
68 "usage: aienos-store-tool cfg|tear-closure|inject|operator-respond|corrupt-kind ... (cases: {})",
69 CASES.join(",")
70 )),
71 };
72 match result {
73 Ok(line) => {
74 println!("{line}");
75 ExitCode::SUCCESS
76 }
77 Err(e) => {
78 eprintln!("aienos-store-tool: {e}");
79 ExitCode::FAILURE
80 }
81 }
82}
83
84fn num(s: &str, what: &str) -> Result<u64, String> {
85 s.parse().map_err(|_| format!("bad {what}: {s}"))
86}
87
88fn arity(args: &[String], min: usize, max: usize) -> Result<(), String> {
89 if args.len() < min || args.len() > max {
90 return Err(format!(
91 "expected {min}..={max} arguments, got {}",
92 args.len()
93 ));
94 }
95 Ok(())
96}
97
98fn read_unit_at(path: &str, offset: u64) -> Result<Unit, String> {
99 let mut f = fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;
100 f.seek(SeekFrom::Start(offset)).map_err(|e| e.to_string())?;
101 let mut unit = [0u8; STORE_UNIT_BYTES];
102 f.read_exact(&mut unit)
103 .map_err(|e| format!("{path}: {e}"))?;
104 Ok(unit)
105}
106
107fn write_at(path: &str, offset: u64, bytes: &[u8]) -> Result<(), String> {
108 let mut f = OpenOptions::new()
109 .write(true)
110 .open(path)
111 .map_err(|e| format!("{path}: {e}"))?;
112 f.seek(SeekFrom::Start(offset)).map_err(|e| e.to_string())?;
113 f.write_all(bytes).map_err(|e| format!("{path}: {e}"))?;
114 f.sync_all().map_err(|e| format!("{path}: {e}"))
115}
116
117fn rechecksum(unit: &mut Unit) {
118 unit[SUPERBLOCK_CRC_OFFSET..SUPERBLOCK_CRC_OFFSET + 4].fill(0);
119 let crc = crc32c(unit);
120 unit[SUPERBLOCK_CRC_OFFSET..SUPERBLOCK_CRC_OFFSET + 4].copy_from_slice(&crc.to_le_bytes());
121}
122
123fn cfg(args: &[String]) -> Result<String, String> {
124 arity(args, 4, 5)?;
125 let offset = num(&args[1], "byte offset")?;
126 let mode = u8::try_from(num(&args[2], "mode")?).map_err(|_| "mode > 255")?;
127 let settle = u8::try_from(num(&args[3], "settle")?).map_err(|_| "settle > 255")?;
128 let mut block = [0u8; STORE_UNIT_BYTES];
129 block[0] = mode;
130 block[1] = settle;
131 // Optional 32-byte operator response for Recovery Core actions.
132 if let Some(hex) = args.get(4) {
133 block[16..48].copy_from_slice(&hex32(hex)?);
134 }
135 write_at(&args[0], offset, &block)?;
136 Ok(format!("cfg mode={mode} settle={settle}"))
137}
138
139fn hex32(s: &str) -> Result<[u8; 32], String> {
140 if s.len() != 64 {
141 return Err(format!("expected 64 hex digits, got {}", s.len()));
142 }
143 let mut out = [0u8; 32];
144 for (i, b) in out.iter_mut().enumerate() {
145 *b = u8::from_str_radix(&s[2 * i..2 * i + 2], 16).map_err(|_| format!("bad hex: {s}"))?;
146 }
147 Ok(out)
148}
149
150fn hex(bytes: &[u8]) -> String {
151 bytes.iter().map(|b| format!("{b:02x}")).collect()
152}
153
154/// Operator side of the Recovery Core challenge: HMAC response for KEY.
155fn operator_respond(args: &[String]) -> Result<String, String> {
156 arity(args, 2, 2)?;
157 let key = hex32(&args[0])?;
158 let challenge = hex32(&args[1])?;
159 Ok(hex(
160 &aienos_kernel::recovery::OperatorAuth::expected_response(&key, &challenge),
161 ))
162}
163
164/// A Store region inside an image file, as a StoreDevice.
165struct FileDevice {
166 file: fs::File,
167 base: u64,
168 units: u64,
169}
170
171impl aienos_kernel::store::engine::StoreDevice for FileDevice {
172 type Error = std::io::Error;
173 fn region_units(&self) -> u64 {
174 self.units
175 }
176 fn read_unit(&mut self, unit: u64, out: &mut Unit) -> std::io::Result<()> {
177 self.file
178 .seek(SeekFrom::Start(self.base + unit * STORE_UNIT_BYTES as u64))?;
179 self.file.read_exact(out)
180 }
181 fn write_unit(&mut self, unit: u64, bytes: &Unit) -> std::io::Result<()> {
182 self.file
183 .seek(SeekFrom::Start(self.base + unit * STORE_UNIT_BYTES as u64))?;
184 self.file.write_all(bytes)
185 }
186 fn flush(&mut self) -> std::io::Result<()> {
187 self.file.sync_all()
188 }
189}
190
191/// Flips one byte in the first unit of the first catalog object of KIND.
192fn corrupt_kind(args: &[String]) -> Result<String, String> {
193 arity(args, 4, 4)?;
194 let offset = num(&args[1], "store offset")?;
195 let units = num(&args[2], "region units")?;
196 let kind = u16::try_from(num(&args[3], "kind")?).map_err(|e| e.to_string())?;
197 let file = OpenOptions::new()
198 .read(true)
199 .write(true)
200 .open(&args[0])
201 .map_err(|e| format!("{}: {e}", args[0]))?;
202 let dev = FileDevice {
203 file,
204 base: offset,
205 units,
206 };
207 let store = aienos_kernel::store::engine::Store::open(dev)
208 .map_err(|e| format!("store does not mount: {e:?}"))?;
209 let entry = store
210 .catalog()
211 .entries
212 .iter()
213 .find(|e| e.kind == kind)
214 .copied()
215 .ok_or(format!("no catalog object of kind {kind}"))?;
216 let at = offset + entry.first_unit * STORE_UNIT_BYTES as u64 + 20;
217 let mut dev = store.into_device();
218 dev.file
219 .seek(SeekFrom::Start(at))
220 .map_err(|e| e.to_string())?;
221 let mut byte = [0u8; 1];
222 dev.file.read_exact(&mut byte).map_err(|e| e.to_string())?;
223 byte[0] ^= 0xff;
224 dev.file
225 .seek(SeekFrom::Start(at))
226 .map_err(|e| e.to_string())?;
227 dev.file.write_all(&byte).map_err(|e| e.to_string())?;
228 dev.file.sync_all().map_err(|e| e.to_string())?;
229 Ok(format!(
230 "corrupt kind={kind} unit={} byte=20",
231 entry.first_unit
232 ))
233}
234
235/// Describes a superblock slot's bytes for reports.
236fn describe(unit: &Unit, slot: u32) -> String {
237 if unit.iter().all(|b| *b == 0) {
238 return "zero".into();
239 }
240 match Superblock::decode(unit, slot) {
241 Ok(sb) => format!("gen{}", sb.generation),
242 Err(e) => format!("undecodable({e:?})"),
243 }
244}
245
246fn tear_closure(args: &[String]) -> Result<String, String> {
247 arity(args, 4, 4)?;
248 let old = fs::read(&args[0]).map_err(|e| format!("{}: {e}", args[0]))?;
249 let new = fs::read(&args[1]).map_err(|e| format!("{}: {e}", args[1]))?;
250 let store_offset =
251 usize::try_from(num(&args[2], "store offset")?).map_err(|e| e.to_string())?;
252 let sector = usize::try_from(num(&args[3], "sector bytes")?).map_err(|e| e.to_string())?;
253 if old.len() != new.len() {
254 return Err("images differ in length".into());
255 }
256 if sector == 0 || !STORE_UNIT_BYTES.is_multiple_of(sector) {
257 return Err(format!(
258 "sector size {sector} does not divide the store unit"
259 ));
260 }
261 if !store_offset.is_multiple_of(sector) {
262 return Err("store offset is not sector aligned".into());
263 }
264
265 // Every differing byte must lie inside one superblock slot of the store.
266 let mut slot_hit: Option<usize> = None;
267 for (i, (a, b)) in old.iter().zip(&new).enumerate() {
268 if a == b {
269 continue;
270 }
271 let rel = i
272 .checked_sub(store_offset)
273 .ok_or_else(|| format!("images differ outside the store at byte {i}"))?;
274 let slot = rel / STORE_UNIT_BYTES;
275 if slot > 1 {
276 return Err(format!(
277 "images differ outside the superblock slots (store unit {slot}); \
278 the two runs did not persist identical payloads"
279 ));
280 }
281 match slot_hit {
282 None => slot_hit = Some(slot),
283 Some(s) if s == slot => {}
284 Some(_) => return Err("both superblock slots differ".into()),
285 }
286 }
287 let slot = slot_hit.ok_or("images are identical: nothing separates old from new")?;
288 let base = store_offset + slot * STORE_UNIT_BYTES;
289 let mut old_unit = [0u8; STORE_UNIT_BYTES];
290 let mut new_unit = [0u8; STORE_UNIT_BYTES];
291 old_unit.copy_from_slice(&old[base..base + STORE_UNIT_BYTES]);
292 new_unit.copy_from_slice(&new[base..base + STORE_UNIT_BYTES]);
293
294 let new_sb = Superblock::decode(&new_unit, slot as u32)
295 .map_err(|e| format!("new slot {slot} is not a valid superblock: {e:?}"))?;
296 let old_desc = describe(&old_unit, slot as u32);
297 if old_desc.starts_with("undecodable") {
298 return Err(format!(
299 "old slot {slot} is {old_desc}; the engine never overwrites such a slot"
300 ));
301 }
302
303 let sectors = STORE_UNIT_BYTES / sector;
304 let differing: Vec<usize> = (0..sectors)
305 .filter(|s| {
306 old_unit[s * sector..(s + 1) * sector] != new_unit[s * sector..(s + 1) * sector]
307 })
308 .collect();
309 let (as_old, as_new) = tear_outcomes(&old_unit, &new_unit, sector).map_err(|mask| {
310 format!(
311 "STORE_ROOT_TEAR_CLOSURE: FAIL (slot={slot} mask={mask:#x} yields a third state; \
312 differing sectors {differing:?})"
313 )
314 })?;
315 Ok(format!(
316 "STORE_ROOT_TEAR_CLOSURE: PASS (slot={slot} old={old_desc} new=gen{} sector_bytes={sector} \
317 differing_sectors={differing:?} combinations={} as_old={as_old} as_new={as_new})",
318 new_sb.generation,
319 1u32 << sectors
320 ))
321}
322
323/// Applies every subset of `sector`-sized blocks of `new` over `old` (each
324/// sector either reached the medium or did not). Returns how many subsets
325/// reproduce `old` and `new`, or the first subset mask that yields neither.
326fn tear_outcomes(old: &Unit, new: &Unit, sector: usize) -> Result<(u32, u32), u32> {
327 let sectors = STORE_UNIT_BYTES / sector;
328 assert!(sectors <= 16, "too many sectors per unit to enumerate");
329 let (mut as_old, mut as_new) = (0u32, 0u32);
330 for mask in 0u32..(1 << sectors) {
331 let mut torn = *old;
332 for s in 0..sectors {
333 if mask & (1 << s) != 0 {
334 torn[s * sector..(s + 1) * sector]
335 .copy_from_slice(&new[s * sector..(s + 1) * sector]);
336 }
337 }
338 if torn == *old {
339 as_old += 1;
340 } else if torn == *new {
341 as_new += 1;
342 } else {
343 return Err(mask);
344 }
345 }
346 Ok((as_old, as_new))
347}
348
349/// The slot the engine would overwrite next: the zero slot, else the valid
350/// superblock with the lower generation. Refuses anything ambiguous.
351fn inactive_slot(image: &str, store_offset: u64) -> Result<u32, String> {
352 let mut generation = [None; 2];
353 for slot in 0..2u32 {
354 let unit = read_unit_at(
355 image,
356 store_offset + u64::from(slot) * STORE_UNIT_BYTES as u64,
357 )?;
358 if unit.iter().all(|b| *b == 0) {
359 return Ok(slot);
360 }
361 generation[slot as usize] = Superblock::decode(&unit, slot).ok().map(|sb| sb.generation);
362 }
363 match generation {
364 [Some(a), Some(b)] if a < b => Ok(0),
365 [Some(a), Some(b)] if b < a => Ok(1),
366 _ => Err("cannot determine the inactive slot (both slots valid at one generation, or one undecodable)".into()),
367 }
368}
369
370/// xorshift64 stream with a fixed seed: the same 4096 bytes on every run.
371fn seeded_garbage() -> Unit {
372 let mut state: u64 = 0x4149_454E_4F53_0136;
373 let mut unit = [0u8; STORE_UNIT_BYTES];
374 for chunk in unit.as_chunks_mut::<8>().0 {
375 state ^= state << 13;
376 state ^= state >> 7;
377 state ^= state << 17;
378 chunk.copy_from_slice(&state.to_le_bytes());
379 }
380 unit
381}
382
383fn inject(args: &[String]) -> Result<String, String> {
384 arity(args, 4, 5)?;
385 let image = &args[0];
386 let store_offset = num(&args[1], "store offset")?;
387 let slot = if args[2] == "inactive" {
388 inactive_slot(image, store_offset)?
389 } else {
390 u32::try_from(num(&args[2], "slot")?).map_err(|e| e.to_string())?
391 };
392 if slot > 1 {
393 return Err("slot must be 0, 1 or inactive".into());
394 }
395 let case = args[3].as_str();
396 let slot_offset = store_offset + u64::from(slot) * STORE_UNIT_BYTES as u64;
397
398 let source = || -> Result<Unit, String> {
399 let path = args.get(4).ok_or("this case needs a SOURCE image")?;
400 let unit = read_unit_at(path, slot_offset)?;
401 Superblock::decode(&unit, slot)
402 .map_err(|e| format!("source slot {slot} is not a valid superblock: {e:?}"))?;
403 Ok(unit)
404 };
405
406 // (bytes, the decode error this case must produce, or None for a valid root)
407 let (unit, expect): (Unit, Option<FormatError>) = match case {
408 "bad_crc" => {
409 let mut u = source()?;
410 u[SUPERBLOCK_CRC_OFFSET] ^= 0x01;
411 (u, Some(FormatError::BadSuperblockCrc))
412 }
413 "wrong_magic" => {
414 let mut u = source()?;
415 u[..8].copy_from_slice(b"AIENBAD1");
416 rechecksum(&mut u);
417 (u, Some(FormatError::BadSuperblockMagic))
418 }
419 "nonzero_reserved" => {
420 let mut u = source()?;
421 u[200] = 0x42;
422 rechecksum(&mut u);
423 (u, Some(FormatError::NonzeroReserved))
424 }
425 "wrong_slot_id" => {
426 let mut u = source()?;
427 u[44..48].copy_from_slice(&(1 - slot).to_le_bytes());
428 rechecksum(&mut u);
429 (u, Some(FormatError::WrongSuperblockSlot))
430 }
431 "region_mismatch" => {
432 // Decodes cleanly; the engine rejects it because region_units does
433 // not match the device.
434 let mut u = source()?;
435 let region = u64::from_le_bytes(u[48..56].try_into().unwrap_or([0; 8]));
436 u[48..56].copy_from_slice(&(region + 1).to_le_bytes());
437 rechecksum(&mut u);
438 (u, None)
439 }
440 "unsupported_version" => {
441 let mut u = source()?;
442 u[8..10].copy_from_slice(&2u16.to_le_bytes());
443 rechecksum(&mut u);
444 (u, Some(FormatError::UnsupportedVersion))
445 }
446 "seeded_garbage" => (seeded_garbage(), Some(FormatError::BadSuperblockMagic)),
447 "new_root" => (source()?, None),
448 other => return Err(format!("unknown case {other}; cases: {}", CASES.join(","))),
449 };
450
451 // Prove the case isolates the defect it names before touching the image.
452 let got = Superblock::decode(&unit, slot).err();
453 if got != expect {
454 return Err(format!(
455 "case {case}: decode gave {got:?}, expected {expect:?}"
456 ));
457 }
458 write_at(image, slot_offset, &unit)?;
459 Ok(format!(
460 "inject case={case} slot={slot} decode={}",
461 expect.map_or("Ok".to_string(), |e| format!("{e:?}"))
462 ))
463}
464
465#[cfg(test)]
466mod tests {
467 use super::*;
468
469 #[test]
470 fn tear_outcomes_detects_a_third_state() {
471 let old = [0u8; STORE_UNIT_BYTES];
472 let mut one_sector = old;
473 one_sector[7] = 1;
474 assert_eq!(tear_outcomes(&old, &one_sector, 512), Ok((128, 128)));
475
476 let mut two_sectors = one_sector;
477 two_sectors[512 * 3] = 1;
478 // Sector 0 alone reaching the medium is neither old nor new.
479 assert_eq!(tear_outcomes(&old, &two_sectors, 512), Err(0x1));
480 }
481
482 #[test]
483 fn garbage_is_stable_and_not_a_superblock() {
484 let a = seeded_garbage();
485 assert_eq!(a, seeded_garbage());
486 assert_ne!(&a[..8], b"AIENSTR1");
487 assert_eq!(
488 Superblock::decode(&a, 1).err(),
489 Some(FormatError::BadSuperblockMagic)
490 );
491 }
492}