Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/crates/aienos-artifact-tool/src/corpus.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / crates / aienos-artifact-tool / src / corpus.rs` 512 lines · 17483 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 //! P2-7 negative-test corpus: deterministic Binary Artifact v0 cases that the 17 //! kernel must refuse at a stable stage with a stable reason, or admit and 18 //! then contain. Every case starts from one valid, TEST-ONLY-signed baseline 19 //! and changes exactly one thing. Debug builds with `seed0b-test-signing` 20 //! only; never part of the kernel or release tooling. 21 22 use std::error::Error; 23 use std::fs; 24 use std::path::Path; 25 26 use aienos_artifact::signature::{artifact_signature_message, signer_fingerprint}; 27 use aienos_artifact::verify::parse_and_identify; 28 use `ed25519`_dalek::{Signer, SigningKey}; 29 30 use crate::{pack_bytes, CapabilityManifest, Manifest, ResourceManifest}; 31 32 /// Expected kernel outcome for one case. 33 #[derive(Clone, Debug, Eq, PartialEq)] 34 pub enum Expect { 35 /// Refused before execution: kernel stage name, reason name, §7.3 code. 36 Rejected { 37 stage: &'static str, 38 reason: &'static str, 39 code: u16, 40 }, 41 /// Admitted; `exec` is the kernel report's `exec=` value. 42 Admitted { exec: &'static str, caps: usize }, 43 } 44 45 pub struct Case { 46 pub name: &'static str, 47 pub what: &'static str, 48 pub bytes: Vec, 49 pub expect: Expect, 50 } 51 52 /// RFC 8032 TEST 3 seed: a well-formed Ed25519 key no anchor set trusts. 53 const UNTRUSTED_SEED: [u8; 32] = [ 54 0xc5, 0xaa, 0x8d, 0xf4, 0x3f, 0x9f, 0x83, 0x7b, 0xed, 0xb7, 0x44, 0x2f, 0x31, 0xdc, 0xb7, 0xb1, 55 0x66, 0xd3, 0x85, 0x35, 0x07, 0x6f, 0x09, 0x4b, 0x85, 0xce, 0x3a, 0x2e, 0x0b, 0x44, 0x58, 0xf7, 56 ]; 57 58 // AArch64 instruction words (checked against GNU as). 59 const MOV_X0_0: u32 = 0xd280_0000; 60 const MOV_X8_2: u32 = 0xd280_0048; 61 const MOV_X8_6: u32 = 0xd280_00c8; 62 const MOV_X8_99: u32 = 0xd280_0c68; 63 const SVC_0: u32 = 0xd400_0001; 64 const B_SELF: u32 = 0x1400_0000; 65 const BR_X2: u32 = 0xd61f_0040; 66 // SUB X9, SP, #16. SP starts at the stack top (the guard page) when no caps 67 // are granted, so the target must be below it to land on a mapped stack page. 68 const SUB_X9_SP_16: u32 = 0xd100_43e9; 69 const BR_X9: u32 = 0xd61f_0120; 70 71 // Canonical offsets (ADR 0014 §2). 72 const SECTION_CODE: usize = 128; 73 const SECTION_DATA: usize = 160; 74 const CAPS: usize = 192; 75 const CAP_SIZE: usize = 48; 76 77 fn words(w: &[u32]) -> Vec { 78 w.iter().flat_map(|x| x.to_le_bytes()).collect() 79 } 80 81 fn exit0() -> Vec { 82 words(&[MOV_X0_0, MOV_X8_2, SVC_0, B_SELF]) 83 } 84 85 fn seed_read(rights: u32) -> CapabilityManifest { 86 CapabilityManifest { 87 resource_kind: 3, 88 resource_id: 1, 89 rights, 90 bounds_kind: 1, 91 max_operations: 4, 92 max_bytes: 32, 93 byte_offset: 0, 94 byte_length: 32, 95 } 96 } 97 98 fn resources(code: u32, data: u32, stack: u32, caps: u16, syscalls: u32) -> ResourceManifest { 99 ResourceManifest { 100 code_pages: code, 101 data_pages: data, 102 stack_pages: stack, 103 max_capabilities: caps, 104 ipc_messages: 0, 105 ipc_bytes: 0, 106 cpu_ticks: 100_000_000, 107 elapsed_ticks: 100_000_000, 108 syscall_count: syscalls, 109 } 110 } 111 112 fn manifest(caps: Vec, res: ResourceManifest) -> Manifest { 113 Manifest { 114 entry_offset: 0, 115 capabilities: caps, 116 resources: res, 117 } 118 } 119 120 /// Sign packed bytes in place with `seed` (valid Ed25519, any key). 121 fn sign_with(bytes: &mut [u8], seed: &[u8; 32]) -> Result<(), Box> { 122 let id = parse_and_identify(bytes) 123 .map_err(|e| format!("baseline does not parse: {e:?}"))? 124 .artifact_id; 125 let key = SigningKey::from_bytes(seed); 126 let start = bytes.len() - 100; 127 bytes[start + 4..start + 36] 128 .copy_from_slice(&signer_fingerprint(&key.verifying_key().to_bytes())); 129 bytes[start + 36..].copy_from_slice(&key.sign(&artifact_signature_message(&id)).to_bytes()); 130 Ok(()) 131 } 132 133 fn signed(m: &Manifest, code: &[u8], data: &[u8]) -> Result, Box> { 134 let mut bytes = pack_bytes(m, code, data)?; 135 sign_with(&mut bytes, &crate::test_only_seed())?; 136 Ok(bytes) 137 } 138 139 fn baseline() -> Result, Box> { 140 signed( 141 &manifest(vec![seed_read(1)], resources(1, 1, 1, 1, 8)), 142 &exit0(), 143 b"BASELINE", 144 ) 145 } 146 147 fn put16(b: &mut [u8], at: usize, v: u16) { 148 b[at..at + 2].copy_from_slice(&v.to_le_bytes()); 149 } 150 fn put32(b: &mut [u8], at: usize, v: u32) { 151 b[at..at + 4].copy_from_slice(&v.to_le_bytes()); 152 } 153 fn get32(b: &[u8], at: usize) -> u32 { 154 u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]) 155 } 156 157 fn rejected(stage: &'static str, reason: &'static str, code: u16) -> Expect { 158 Expect::Rejected { 159 stage, 160 reason, 161 code, 162 } 163 } 164 165 fn verified(reason: &'static str, code: u16) -> Expect { 166 rejected("verified", reason, code) 167 } 168 169 /// The whole corpus, in a fixed order with fixed names. 170 pub fn corpus() -> Result, Box> { 171 let base = baseline()?; 172 let payload = get32(&base, 56) as usize; 173 let resource = CAPS + CAP_SIZE; 174 let sig = base.len() - 100; 175 let with = |f: &dyn Fn(&mut Vec)| { 176 let mut b = base.clone(); 177 f(&mut b); 178 b 179 }; 180 let v = vec![ 181 Case { 182 name: "H01-BAD-MAGIC.AIEN", 183 what: "magic is not AIENART\\0", 184 bytes: with(&|b| b[0] = b'X'), 185 expect: verified("BadMagic", 1), 186 }, 187 Case { 188 name: "H02-VERSION.AIEN", 189 what: "format_version 1 (unsupported)", 190 bytes: with(&|b| put16(b, 8, 1)), 191 expect: verified("UnsupportedVersion", 2), 192 }, 193 Case { 194 name: "H03-TARGET.AIEN", 195 what: "target_arch 2 (not AArch64 LE)", 196 bytes: with(&|b| put16(b, 12, 2)), 197 expect: verified("WrongTarget", 3), 198 }, 199 Case { 200 name: "H04-ABI.AIEN", 201 what: "abi_version 2 (not ABI v1)", 202 bytes: with(&|b| put16(b, 14, 2)), 203 expect: verified("WrongAbi", 4), 204 }, 205 Case { 206 name: "H05-TRUNCATED.AIEN", 207 what: "last 10 bytes cut off", 208 bytes: with(&|b| b.truncate(b.len() - 10)), 209 expect: verified("WrongLength", 7), 210 }, 211 Case { 212 name: "H06-TRAILING.AIEN", 213 what: "one byte appended after the signature block", 214 bytes: with(&|b| b.push(0)), 215 expect: verified("WrongLength", 7), 216 }, 217 Case { 218 name: "H07-TOTAL-LENGTH.AIEN", 219 what: "total_length field one larger than the file", 220 bytes: with(&|b| { 221 let t = get32(b, 20); 222 put32(b, 20, t + 1) 223 }), 224 expect: verified("WrongLength", 7), 225 }, 226 Case { 227 name: "H08-OFFSET-OVERFLOW.AIEN", 228 what: "payload_length 0xffffffff (offset + length overflows)", 229 bytes: with(&|b| put32(b, 60, u32::MAX)), 230 expect: verified("ResourceLimit", 14), 231 }, 232 Case { 233 name: "H09-SECTION-OVERLAP.AIEN", 234 what: "data section starts inside the code section", 235 bytes: with(&|b| put32(b, SECTION_DATA + 8, 4)), 236 expect: verified("BadSection", 11), 237 }, 238 Case { 239 name: "H10-ENTRY-OUTSIDE.AIEN", 240 what: "entry_offset beyond the code bytes", 241 bytes: with(&|b| put32(b, 36, 0x1000)), 242 expect: verified("BadEntryPoint", 12), 243 }, 244 Case { 245 name: "H11-PAYLOAD-MUTATED.AIEN", 246 what: "one code byte changed after signing", 247 bytes: with(&|b| b[payload] ^= 0x01), 248 expect: verified("BadSignature", 18), 249 }, 250 Case { 251 name: "H12-CAPS-MUTATED.AIEN", 252 what: "requested rights READ -> READ|WRITE after signing", 253 bytes: with(&|b| put32(b, CAPS + 8, 3)), 254 expect: verified("BadSignature", 18), 255 }, 256 Case { 257 name: "H13-ENVELOPE-MUTATED.AIEN", 258 what: "stack_pages 1 -> 2 after signing", 259 bytes: with(&|b| put32(b, resource + 8, 2)), 260 expect: verified("BadSignature", 18), 261 }, 262 Case { 263 name: "H14-SIGNATURE-MUTATED.AIEN", 264 what: "one signature byte changed", 265 bytes: with(&|b| b[sig + 40] ^= 0x01), 266 expect: verified("BadSignature", 18), 267 }, 268 Case { 269 name: "H15-UNKNOWN-SIGNER.AIEN", 270 what: "valid Ed25519 signature by a key no anchor trusts", 271 bytes: { 272 let mut b = base.clone(); 273 sign_with(&mut b, &UNTRUSTED_SEED)?; 274 b 275 }, 276 expect: verified("UntrustedSigner", 17), 277 }, 278 Case { 279 name: "H16-SIG-FORMAT.AIEN", 280 what: "signature block algorithm 2", 281 bytes: with(&|b| put16(b, sig, 2)), 282 expect: verified("BadSignatureFormat", 15), 283 }, 284 Case { 285 name: "H17-RESERVED-HEADER.AIEN", 286 what: "reserved header byte 100 nonzero", 287 bytes: with(&|b| b[100] = 1), 288 expect: verified("ReservedNonZero", 8), 289 }, 290 Case { 291 name: "H18-RIGHTS-UNKNOWN.AIEN", 292 what: "requested rights bit 6 (undefined)", 293 bytes: with(&|b| put32(b, CAPS + 8, 1 | (1 << 6))), 294 expect: verified("MalformedCapability", 13), 295 }, 296 Case { 297 name: "H19-CAP-COUNT.AIEN", 298 what: "capability_count 17 (> 16)", 299 bytes: with(&|b| put16(b, 44, 17)), 300 expect: verified("ResourceLimit", 14), 301 }, 302 Case { 303 name: "H20-ENVELOPE-LIMIT.AIEN", 304 what: "code_pages 65 (> 64); refused while parsing, before signature checks", 305 bytes: { 306 let mut b = base.clone(); 307 put32(&mut b, resource, 65); 308 b 309 }, 310 expect: verified("ResourceLimit", 14), 311 }, 312 Case { 313 name: "H21-LARGEST-ENVELOPE.AIEN", 314 what: "largest valid envelope: 64 code, 64 data, 16 stack pages", 315 bytes: signed( 316 &manifest(vec![], resources(64, 64, 16, 0, 4)), 317 &exit0(), 318 b"LARGEST!", 319 )?, 320 expect: Expect::Admitted { 321 exec: "exited:0x0", 322 caps: 0, 323 }, 324 }, 325 Case { 326 name: "H22-WX-SECTION.AIEN", 327 what: "code section permissions R|W|X", 328 bytes: with(&|b| put16(b, SECTION_CODE + 2, 0b111)), 329 expect: verified("BadSection", 11), 330 }, 331 Case { 332 name: "H23-EXEC-DATA.AIEN", 333 what: "branches into its own data page (mapped RW+NX)", 334 bytes: signed( 335 &manifest(vec![], resources(1, 1, 1, 0, 4)), 336 &words(&[BR_X2]), 337 b"DATAPAGE", 338 )?, 339 expect: Expect::Admitted { 340 exec: "fault:exec-nx", 341 caps: 0, 342 }, 343 }, 344 Case { 345 name: "H24-EXEC-STACK.AIEN", 346 what: "branches onto its own stack (mapped RW+NX)", 347 bytes: signed( 348 &manifest(vec![], resources(1, 1, 1, 0, 4)), 349 &words(&[SUB_X9_SP_16, BR_X9]), 350 b"STACKPAG", 351 )?, 352 expect: Expect::Admitted { 353 exec: "fault:exec-nx", 354 caps: 0, 355 }, 356 }, 357 Case { 358 name: "H25-BAD-SYSCALL.AIEN", 359 what: "invokes undefined syscall 99", 360 bytes: signed( 361 &manifest(vec![], resources(1, 1, 1, 0, 4)), 362 &words(&[MOV_X8_99, SVC_0, B_SELF]), 363 b"BADSYSCL", 364 )?, 365 expect: Expect::Admitted { 366 exec: "bad-syscall:99", 367 caps: 0, 368 }, 369 }, 370 Case { 371 name: "H26-SYSCALL-BUDGET.AIEN", 372 what: "third syscall exceeds syscall_count 2", 373 bytes: signed( 374 &manifest(vec![], resources(1, 1, 1, 0, 2)), 375 &words(&[ 376 MOV_X0_0, MOV_X8_6, SVC_0, SVC_0, SVC_0, MOV_X8_2, SVC_0, B_SELF, 377 ]), 378 b"OVERRUN!", 379 )?, 380 expect: Expect::Admitted { 381 exec: "resource-overrun", 382 caps: 0, 383 }, 384 }, 385 Case { 386 name: "H27-POLICY-IPC.AIEN", 387 what: "requests 1 IPC message; local policy allows none", 388 bytes: { 389 let mut r = resources(1, 1, 1, 1, 8); 390 r.ipc_messages = 1; 391 r.ipc_bytes = 64; 392 signed(&manifest(vec![seed_read(1)], r), &exit0(), b"IPCWANTS")? 393 }, 394 expect: rejected("authorized", "ResourceLimit", 14), 395 }, 396 Case { 397 name: "H28-WRITE-ONLY-REQUEST.AIEN", 398 what: "requests only WRITE on the SEED object; policy grants READ at most", 399 bytes: signed( 400 &manifest(vec![seed_read(2)], resources(1, 1, 1, 1, 8)), 401 &exit0(), 402 b"WRITEREQ", 403 )?, 404 expect: Expect::Admitted { 405 exec: "exited:0x0", 406 caps: 0, 407 }, 408 }, 409 Case { 410 name: "H29-READ-WRITE-REQUEST.AIEN", 411 what: "requests READ|WRITE; granted READ only", 412 bytes: signed( 413 &manifest(vec![seed_read(3)], resources(1, 1, 1, 1, 8)), 414 &exit0(), 415 b"RWREQUST", 416 )?, 417 expect: Expect::Admitted { 418 exec: "exited:0x0", 419 caps: 1, 420 }, 421 }, 422 ]; 423 Ok(v) 424 } 425 426 /// `negative-corpus OUT_DIR`: write every case and `expected.txt`. 427 pub fn write_corpus(out: &Path) -> Result<(), Box> { 428 fs::create_dir_all(out)?; 429 let mut expected = String::new(); 430 for case in corpus()? { 431 fs::write(out.join(case.name), &case.bytes)?; 432 match &case.expect { 433 Expect::Rejected { 434 stage, 435 reason, 436 code, 437 } => expected.push_str(&format!( 438 "{} rejected {stage} {reason} {code:#x} # {}\n", 439 case.name, case.what 440 )), 441 Expect::Admitted { exec, caps } => expected.push_str(&format!( 442 "{} admitted {exec} {caps} # {}\n", 443 case.name, case.what 444 )), 445 } 446 } 447 fs::write(out.join("expected.txt"), expected)?; 448 println!("NEGATIVE_CORPUS: TEST ONLY SEED-0B qualification inputs written"); 449 Ok(()) 450 } 451 452 #[cfg(test)] 453 mod tests { 454 use super::*; 455 use aienos_artifact::signature::seed0b_test_anchor::Seed0bTestAnchorSet; 456 use aienos_artifact::signature::{ 457 ArtifactVerifier, ConfiguredArtifactVerifier, Ed25519Verifier, 458 }; 459 460 #[test] 461 fn corpus_is_deterministic_and_names_are_unique_and_sorted() { 462 let a = corpus().unwrap(); 463 let b = corpus().unwrap(); 464 assert_eq!(a.len(), b.len()); 465 for (x, y) in a.iter().zip(&b) { 466 assert_eq!(x.name, y.name); 467 assert_eq!(x.bytes, y.bytes, "{}", x.name); 468 } 469 let names: Vec<_> = a.iter().map(|c| c.name).collect(); 470 let mut sorted = names.clone(); 471 sorted.sort(); 472 sorted.dedup(); 473 assert_eq!(names, sorted); 474 assert!(a 475 .iter() 476 .all(|c| c.name.len() <= 32 && c.name.ends_with(".AIEN"))); 477 } 478 479 /// Every "verified"-stage expectation is exactly what the shared 480 /// parser/verifier returns; every other case authenticates. 481 #[test] 482 fn verifier_stage_expectations_match_the_shared_verifier() { 483 let anchors = Seed0bTestAnchorSet; 484 let verifier = ConfiguredArtifactVerifier::new(&anchors, Ed25519Verifier); 485 for case in corpus().unwrap() { 486 let result = verifier.verify(&case.bytes); 487 match case.expect { 488 Expect::Rejected { 489 stage: "verified", 490 reason, 491 code, 492 } => { 493 let error = result.expect_err(case.name); 494 assert_eq!(format!("{error:?}"), reason, "{}", case.name); 495 assert_eq!(error as u16, code, "{}", case.name); 496 } 497 _ => assert!(result.is_ok(), "{} must authenticate", case.name), 498 } 499 } 500 } 501 502 #[test] 503 fn baseline_is_valid_and_each_case_differs_from_it() { 504 let base = baseline().unwrap(); 505 let anchors = Seed0bTestAnchorSet; 506 let verifier = ConfiguredArtifactVerifier::new(&anchors, Ed25519Verifier); 507 assert!(verifier.verify(&base).is_ok()); 508 for case in corpus().unwrap() { 509 assert_ne!(case.bytes, base, "{}", case.name); 510 } 511 } 512 }