diff --git a/crates/aienos-artifact-tool/src/main.rs b/crates/aienos-artifact-tool/src/main.rs index 1e77e317..354241ed 100644 --- a/crates/aienos-artifact-tool/src/main.rs +++ b/crates/aienos-artifact-tool/src/main.rs @@ -27,6 +27,8 @@ use serde::Deserialize; #[cfg(all(feature = "seed0b-test-signing", not(debug_assertions)))] compile_error!("the SEED-0B test signing identity is unavailable to release builds"); +mod receipt_cmd; + const PAGE_SIZE: u32 = 4096; const SIGNATURE_OFFSET_HEADER: usize = 64; const SIGNATURE_LENGTH_HEADER: usize = 68; @@ -93,13 +95,17 @@ fn run() -> Result<(), Box> { } Some("sign") if args.len() == 4 => sign_file(Path::new(&args[2]), Path::new(&args[3]))?, Some("verify") if args.len() == 3 => verify_file(&fs::read(&args[2])?)?, + Some("receipt") => receipt_cmd::run(&args[2..])?, _ => return Err(usage().into()), } Ok(()) } -fn usage() -> &'static str { - "usage: aienos-artifact-tool pack MANIFEST.json CODE.bin DATA.bin OUTPUT.aien | inspect FILE.aien | id FILE.aien | sign INPUT.aien OUTPUT.aien | verify FILE.aien" +fn usage() -> String { + format!( + "usage: aienos-artifact-tool pack MANIFEST.json CODE.bin DATA.bin OUTPUT.aien | inspect FILE.aien | id FILE.aien | sign INPUT.aien OUTPUT.aien | verify FILE.aien | {}", + receipt_cmd::USAGE + ) } fn pack_bytes(manifest: &Manifest, code: &[u8], data: &[u8]) -> Result, Box> { @@ -264,7 +270,7 @@ fn sign_file(input: &Path, output: &Path) -> Result<(), Box> { fs::write(output, bytes)?; println!("SIGN: TEST ONLY SEED-0B QUALIFICATION IDENTITY"); println!("SIGNER_FINGERPRINT: {}", hex(&fingerprint)); - return Ok(()); + Ok(()) } #[cfg(not(feature = "seed0b-test-signing"))] { @@ -291,7 +297,7 @@ fn verify_file(bytes: &[u8]) -> Result<(), Box> { ); println!("SIGNER_FINGERPRINT: {}", hex(verified.signer_fingerprint())); println!("TRUST_TIER: SEED-0B-QUALIFICATION-TEST-ONLY"); - return Ok(()); + Ok(()) } #[cfg(not(feature = "seed0b-test-signing"))] { diff --git a/crates/aienos-artifact-tool/src/receipt_cmd.rs b/crates/aienos-artifact-tool/src/receipt_cmd.rs new file mode 100644 index 00000000..383c3703 --- /dev/null +++ b/crates/aienos-artifact-tool/src/receipt_cmd.rs @@ -0,0 +1,327 @@ +//! `receipt` subcommands: inspect, cross-check against the artifact the +//! host supplied, TEST-ONLY signing, and verification (ADR 0014 §7). + +use std::error::Error; +use std::fs; + +use aienos_artifact::canonical::{requested_capability_digest, resource_envelope_digest}; +use aienos_artifact::receipt::{ + decode, is_unsigned, receipt_digest, verify, Receipt, ReceiptDecision, RECEIPT_SIZE, +}; +use aienos_artifact::signature::Ed25519Verifier; +use aienos_artifact::verify::parse_and_identify; + +use crate::hex; + +pub const USAGE: &str = "receipt inspect FILE.bin | receipt check EMITTED.bin ARTIFACT.aien | receipt from-hex HEX OUT.bin | receipt sign-test IN.bin OUT.bin | receipt verify FILE.bin"; + +pub fn run(args: &[String]) -> Result<(), Box> { + match (args.first().map(String::as_str), args.len()) { + (Some("inspect"), 2) => inspect(&read(&args[1])?), + (Some("check"), 3) => check(&read(&args[1])?, &fs::read(&args[2])?), + (Some("from-hex"), 3) => from_hex(&args[1], &args[2]), + (Some("sign-test"), 3) => sign_test(&read(&args[1])?, &args[2]), + (Some("verify"), 2) => verify_file(&read(&args[1])?), + _ => Err(USAGE.into()), + } +} + +fn read(path: &str) -> Result<[u8; RECEIPT_SIZE], Box> { + let bytes = fs::read(path)?; + let record: [u8; RECEIPT_SIZE] = bytes.as_slice().try_into().map_err(|_| { + format!( + "receipt must be exactly {RECEIPT_SIZE} bytes, got {}", + bytes.len() + ) + })?; + Ok(record) +} + +fn decoded(record: &[u8; RECEIPT_SIZE]) -> Result> { + decode(record).map_err(|e| format!("receipt rejected: {e:?}").into()) +} + +fn inspect(record: &[u8; RECEIPT_SIZE]) -> Result<(), Box> { + let r = decoded(record)?; + println!("RECEIPT_DIGEST: {}", hex(&receipt_digest(record))); + println!("SIGNED: {}", if is_unsigned(record) { "no" } else { "yes" }); + println!("DECISION: {:?}", r.decision); + println!("TIER: {}", r.tier.label()); + println!("SEQUENCE: {}", r.sequence); + println!( + "REJECTION: stage={} reason={:#x}", + r.rejection_stage, r.rejection_reason + ); + println!( + "EXECUTION: status={:?} exit={} syscalls={} reads_ok={} denials={}", + r.execution_status, r.exit_status, r.syscalls, r.object_reads_ok, r.denials + ); + println!("RESULT_FLAGS: {:#04x}", r.result_flags); + println!("FRAMES_RESERVED: {}", r.frames_reserved); + for (name, digest) in [ + ("ARTIFACT_ID", &r.artifact_id), + ("PAYLOAD_SHA256", &r.payload_digest), + ("ARTIFACT_SIGNER", &r.artifact_signer_fingerprint), + ("POLICY_DIGEST", &r.policy_digest), + ("REQUESTED_CAPS_DIGEST", &r.requested_capability_digest), + ("GRANTED_CAPS_DIGEST", &r.granted_capability_digest), + ("RESOURCE_ENVELOPE_DIGEST", &r.resource_envelope_digest), + ("VERIFIER_IDENTITY", &r.verifier_identity), + ] { + println!("{name}: {}", hex(digest)); + } + Ok(()) +} + +/// A kernel-emitted record must be unsigned and must bind exactly the +/// artifact the host supplied. Fields the failing stage had not computed may +/// be zero; any nonzero identity field must match. +fn check(record: &[u8; RECEIPT_SIZE], artifact: &[u8]) -> Result<(), Box> { + if !is_unsigned(record) { + return Err("kernel-emitted receipts must be unsigned".into()); + } + let r = decoded(record)?; + let admitted = r.decision == ReceiptDecision::Admitted; + let expected = match parse_and_identify(artifact) { + Ok(identified) => Some(( + *identified.artifact_id.as_bytes(), + identified.payload_digest, + *identified.artifact.signer_fingerprint, + requested_capability_digest(identified.artifact.capability_request_bytes), + resource_envelope_digest(identified.artifact.resource_envelope_bytes), + )), + Err(_) => None, + }; + let fields = [ + ("artifact_id", r.artifact_id), + ("payload_digest", r.payload_digest), + ("artifact_signer_fingerprint", r.artifact_signer_fingerprint), + ("requested_capability_digest", r.requested_capability_digest), + ("resource_envelope_digest", r.resource_envelope_digest), + ]; + match expected { + None => { + if admitted { + return Err("admitted receipt for an artifact the host cannot parse".into()); + } + for (name, value) in fields { + if value != [0; 32] { + return Err(format!("{name} must be zero for an unparseable artifact").into()); + } + } + } + Some((id, payload, signer, requested, resources)) => { + for ((name, value), want) in fields + .into_iter() + .zip([id, payload, signer, requested, resources]) + { + let zero_allowed = !admitted; + if value != want && !(zero_allowed && value == [0; 32]) { + return Err(format!("{name} does not bind the supplied artifact").into()); + } + } + if admitted && r.granted_capability_digest == [0; 32] { + return Err("admitted receipt without a granted-capability digest".into()); + } + } + } + println!( + "RECEIPT_CHECK: PASS digest={} decision={:?} tier={} stage={} reason={:#x} status={:?} exit={} syscalls={} reads_ok={} denials={} flags={:#04x}", + hex(&receipt_digest(record)), + r.decision, + r.tier.label(), + r.rejection_stage, + r.rejection_reason, + r.execution_status, + r.exit_status, + r.syscalls, + r.object_reads_ok, + r.denials, + r.result_flags + ); + Ok(()) +} + +fn from_hex(text: &str, out: &str) -> Result<(), Box> { + let text = text.trim(); + if text.len() != RECEIPT_SIZE * 2 + || !text.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f')) + { + return Err(format!("expected {} lowercase hex characters", RECEIPT_SIZE * 2).into()); + } + let bytes: Vec = (0..RECEIPT_SIZE) + .map(|i| u8::from_str_radix(&text[2 * i..2 * i + 2], 16)) + .collect::>()?; + fs::write(out, bytes)?; + println!("FROM_HEX: PASS"); + Ok(()) +} + +fn sign_test(record: &[u8; RECEIPT_SIZE], out: &str) -> Result<(), Box> { + #[cfg(feature = "seed0b-test-signing")] + { + use aienos_artifact::receipt::{sign, signature_message}; + use aienos_artifact::signature::ReceiptSigner; + use aienos_crypto::sha256::{hash, Digest}; + use ed25519_dalek::{Signer, SigningKey}; + + struct TestReceiptKey(SigningKey); + impl ReceiptSigner for TestReceiptKey { + fn signer_fingerprint(&self) -> Digest { + hash(&self.0.verifying_key().to_bytes()) + } + fn sign_receipt_digest( + &self, + digest: &Digest, + ) -> Result<[u8; 64], aienos_artifact::ArtifactError> { + Ok(self.0.sign(&signature_message(digest)).to_bytes()) + } + } + + let key = TestReceiptKey(SigningKey::from_bytes(&test_only_receipt_seed())); + let mut signed = *record; + sign(&mut signed, &key).map_err(|e| format!("cannot sign receipt: {e:?}"))?; + fs::write(out, signed)?; + println!("RECEIPT_SIGN: TEST ONLY SEED-0B QUALIFICATION RECEIPT KEY"); + println!( + "RECEIPT_SIGNER_FINGERPRINT: {}", + hex(&key.signer_fingerprint()) + ); + Ok(()) + } + #[cfg(not(feature = "seed0b-test-signing"))] + { + let _ = (record, out); + Err("receipt signing requires explicit feature seed0b-test-signing; production receipt keys are not available".into()) + } +} + +fn verify_file(record: &[u8; RECEIPT_SIZE]) -> Result<(), Box> { + #[cfg(feature = "seed0b-test-signing")] + { + use aienos_artifact::receipt::seed0b_test_receipt_anchor::Seed0bTestReceiptAnchorSet; + let r = verify(record, &Seed0bTestReceiptAnchorSet, &Ed25519Verifier) + .map_err(|e| format!("receipt verification failed: {e:?}"))?; + println!( + "RECEIPT_VERIFY: PASS digest={} decision={:?} tier={} trust=SEED-0B-TEST-ONLY", + hex(&receipt_digest(record)), + r.decision, + r.tier.label() + ); + Ok(()) + } + #[cfg(not(feature = "seed0b-test-signing"))] + { + verify( + record, + &aienos_artifact::receipt::EmptyReceiptAnchorSet, + &Ed25519Verifier, + ) + .map_err(|e| { + format!("receipt verification failed: {e:?} (no production receipt anchors before M5)") + })?; + Ok(()) + } +} + +#[cfg(feature = "seed0b-test-signing")] +fn test_only_receipt_seed() -> [u8; 32] { + // RFC 8032 TEST 2 seed. TEST-ONLY SEED-0B receipt key; never a secret. + [ + 0x4c, 0xcd, 0x08, 0x9b, 0x28, 0xff, 0x96, 0xda, 0x9d, 0xb6, 0xc3, 0x46, 0xec, 0x11, 0x4e, + 0x0f, 0x5b, 0x8a, 0x31, 0x9f, 0x35, 0xab, 0xa6, 0x24, 0xda, 0x8c, 0xf6, 0xed, 0x4f, 0xb8, + 0xa6, 0xfb, + ] +} + +#[cfg(test)] +mod tests { + use super::*; + use aienos_artifact::receipt::{ + encode, receipt_nonce, ExecutionStatusCode, QualificationTier, RESULT_RECLAIMED, + }; + + fn artifact() -> Vec { + let manifest: crate::Manifest = serde_json::from_str( + r#"{"entry_offset":0,"capabilities":[{"resource_kind":3,"resource_id":1,"rights":1,"bounds_kind":1,"max_operations":4,"max_bytes":32,"byte_offset":0,"byte_length":32}],"resources":{"code_pages":1,"data_pages":1,"stack_pages":1,"max_capabilities":1,"ipc_messages":0,"ipc_bytes":0,"cpu_ticks":1000,"elapsed_ticks":1000,"syscall_count":8}}"#, + ) + .unwrap(); + crate::pack_bytes(&manifest, &[0xc0, 0x03, 0x5f, 0xd6], b"DATA").unwrap() + } + + fn binding(bytes: &[u8], decision: ReceiptDecision) -> Receipt { + let identified = parse_and_identify(bytes).unwrap(); + let verifier_identity = [7u8; 32]; + let admitted = decision == ReceiptDecision::Admitted; + Receipt { + flags: 0, + decision, + tier: QualificationTier::Seed0bQemu, + sequence: 1, + nonce: receipt_nonce(&verifier_identity, 1), + observed_time_ns: 0, + execution_status: if admitted { + ExecutionStatusCode::Exited + } else { + ExecutionStatusCode::NotRun + }, + exit_status: 0, + result_flags: RESULT_RECLAIMED, + rejection_stage: if admitted { 0 } else { 3 }, + rejection_reason: if admitted { 0 } else { 17 }, + syscalls: 0, + object_reads_ok: 0, + denials: 0, + frames_reserved: 0, + artifact_id: *identified.artifact_id.as_bytes(), + payload_digest: identified.payload_digest, + artifact_signer_fingerprint: *identified.artifact.signer_fingerprint, + policy_digest: [1; 32], + requested_capability_digest: requested_capability_digest( + identified.artifact.capability_request_bytes, + ), + granted_capability_digest: if admitted { [2; 32] } else { [0; 32] }, + resource_envelope_digest: resource_envelope_digest( + identified.artifact.resource_envelope_bytes, + ), + verifier_identity, + machine_id_digest: [0; 32], + generation: 0, + context_id: 0, + } + } + + #[test] + fn check_accepts_only_receipts_that_bind_the_supplied_artifact() { + let bytes = artifact(); + let admitted = binding(&bytes, ReceiptDecision::Admitted); + assert!(check(&encode(&admitted), &bytes).is_ok()); + let rejected = Receipt { + artifact_signer_fingerprint: [0; 32], + ..binding(&bytes, ReceiptDecision::Rejected) + }; + assert!(check(&encode(&rejected), &bytes).is_ok()); + let wrong_id = Receipt { + artifact_id: [9; 32], + ..admitted + }; + assert!(check(&encode(&wrong_id), &bytes).is_err()); + let zero_in_admitted = Receipt { + payload_digest: [0; 32], + ..admitted + }; + assert!(check(&encode(&zero_in_admitted), &bytes).is_err()); + let no_grants = Receipt { + granted_capability_digest: [0; 32], + ..admitted + }; + assert!(check(&encode(&no_grants), &bytes).is_err()); + let mut signed_bytes = encode(&admitted); + signed_bytes[400] = 1; + assert!(check(&signed_bytes, &bytes).is_err()); + let mut other = bytes.clone(); + let last = other.len() - 101; + other[last] ^= 1; + assert!(check(&encode(&admitted), &other).is_err()); + } +} diff --git a/crates/aienos-artifact/src/error.rs b/crates/aienos-artifact/src/error.rs index a2611d69..deb9217d 100644 --- a/crates/aienos-artifact/src/error.rs +++ b/crates/aienos-artifact/src/error.rs @@ -21,4 +21,6 @@ pub enum ArtifactError { UntrustedSigner = 17, BadSignature = 18, RightsEscalation = 19, + /// Admission Receipt v0 record violates §7 (never a candidate reason). + MalformedReceipt = 20, } diff --git a/crates/aienos-artifact/src/lib.rs b/crates/aienos-artifact/src/lib.rs index f8273329..712b1d63 100644 --- a/crates/aienos-artifact/src/lib.rs +++ b/crates/aienos-artifact/src/lib.rs @@ -28,3 +28,6 @@ pub use signature::{ #[cfg(test)] mod tests; + +#[cfg(test)] +mod receipt_tests; diff --git a/crates/aienos-artifact/src/receipt.rs b/crates/aienos-artifact/src/receipt.rs index a8624eb5..3f24069e 100644 --- a/crates/aienos-artifact/src/receipt.rs +++ b/crates/aienos-artifact/src/receipt.rs @@ -1,5 +1,15 @@ -//! Admission Receipt v0 constants. Canonical receipt encoding and signing are -//! implemented with the admission lifecycle and qualification receipt work. +//! Admission Receipt v0 (ADR 0014 §7): a 512-byte canonical record of one +//! candidate's verification, admission and execution outcome. +//! +//! The in-memory [`Receipt`] is a view only; the contract is the byte layout +//! produced by [`encode`]. The kernel emits unsigned records (signature block +//! all zero); only host qualification tooling signs them (§7.3). + +use aienos_crypto::sha256::{hash, Digest, Sha256}; + +use crate::error::ArtifactError; +use crate::format::SIGNATURE_ALGORITHM_ED25519; +use crate::signature::{ReceiptSigner, SignatureVerifier, PUBLIC_KEY_SIZE, SIGNATURE_SIZE}; pub const RECEIPT_MAGIC: &[u8; 8] = b"AIENRCP\0"; pub const RECEIPT_VERSION: u16 = 0; @@ -8,6 +18,24 @@ pub const RECEIPT_SIZE: usize = 512; pub const RECEIPT_SIGNATURE_OFFSET: usize = 400; pub const RECEIPT_SIGNATURE_DOMAIN: &[u8] = b"AIENOS-ADMISSION-RECEIPT-SIGNATURE-V1\0"; pub const RECEIPT_DIGEST_DOMAIN: &[u8] = b"AIENOS-ADMISSION-RECEIPT-V1\0"; +pub const RECEIPT_NONCE_DOMAIN: &[u8] = b"AIENOS-ADMISSION-RECEIPT-NONCE-V1\0"; + +/// Presence flags (offset 16). +pub const FLAG_MACHINE_ID: u32 = 1 << 0; +pub const FLAG_CONTEXT_ID: u32 = 1 << 1; +pub const FLAG_TIMESTAMP: u32 = 1 << 2; +pub const VALID_FLAGS: u32 = FLAG_MACHINE_ID | FLAG_CONTEXT_ID | FLAG_TIMESTAMP; + +/// Result flags (offset 72). +pub const RESULT_READ_OK: u32 = 1 << 0; +pub const RESULT_WRITE_DENIED: u32 = 1 << 1; +pub const RESULT_RECLAIMED: u32 = 1 << 2; +pub const RESULT_CANARY_PASSED: u32 = 1 << 3; +pub const RESULT_FORGED_DENIED: u32 = 1 << 4; +pub const RESULT_MAPPED_BYTES_MATCH: u32 = 1 << 5; +pub const RESULT_EXECUTED_BYTES_MATCH: u32 = 1 << 6; +pub const RESULT_WX_SEALED: u32 = 1 << 7; +pub const VALID_RESULT_FLAGS: u32 = 0xff; #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(u16)] @@ -17,3 +45,443 @@ pub enum ReceiptDecision { CanaryFailed = 3, Destroyed = 4, } + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[repr(u16)] +pub enum QualificationTier { + Seed0bQemu = 1, + Seed0bMachine1 = 2, +} + +/// Offset 64; §7.3 mapping of the task runtime outcome. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[repr(u32)] +pub enum ExecutionStatusCode { + NotRun = 0, + Exited = 1, + Timeout = 2, + Fault = 3, + BadSyscall = 4, + ResourceOverrun = 5, + CanaryFailed = 6, +} + +/// In-memory view of one receipt. Encoding is explicit and field by field. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Receipt { + pub flags: u32, + pub decision: ReceiptDecision, + pub tier: QualificationTier, + pub sequence: u64, + pub nonce: [u8; 16], + pub observed_time_ns: u64, + pub execution_status: ExecutionStatusCode, + pub exit_status: i32, + pub result_flags: u32, + pub rejection_stage: u16, + pub rejection_reason: u16, + pub syscalls: u32, + pub object_reads_ok: u32, + pub denials: u32, + pub frames_reserved: u32, + pub artifact_id: Digest, + pub payload_digest: Digest, + pub artifact_signer_fingerprint: Digest, + pub policy_digest: Digest, + pub requested_capability_digest: Digest, + pub granted_capability_digest: Digest, + pub resource_envelope_digest: Digest, + pub verifier_identity: Digest, + pub machine_id_digest: Digest, + pub generation: u64, + pub context_id: u64, +} + +/// Canonical 512-byte record with an all-zero signature block. +pub fn encode(r: &Receipt) -> [u8; RECEIPT_SIZE] { + let mut b = [0u8; RECEIPT_SIZE]; + b[0..8].copy_from_slice(RECEIPT_MAGIC); + put16(&mut b, 8, RECEIPT_VERSION); + put16(&mut b, 10, RECEIPT_HEADER_SIZE as u16); + put32(&mut b, 12, RECEIPT_SIZE as u32); + put32(&mut b, 16, r.flags); + put16(&mut b, 20, r.decision as u16); + put16(&mut b, 22, r.tier as u16); + put64(&mut b, 24, r.sequence); + b[32..48].copy_from_slice(&r.nonce); + put64(&mut b, 48, r.observed_time_ns); + put32(&mut b, 64, r.execution_status as u32); + b[68..72].copy_from_slice(&r.exit_status.to_le_bytes()); + put32(&mut b, 72, r.result_flags); + put16(&mut b, 76, r.rejection_stage); + put16(&mut b, 78, r.rejection_reason); + put32(&mut b, 80, r.syscalls); + put32(&mut b, 84, r.object_reads_ok); + put32(&mut b, 88, r.denials); + put32(&mut b, 92, r.frames_reserved); + for (offset, digest) in [ + (96, &r.artifact_id), + (128, &r.payload_digest), + (160, &r.artifact_signer_fingerprint), + (192, &r.policy_digest), + (224, &r.requested_capability_digest), + (256, &r.granted_capability_digest), + (288, &r.resource_envelope_digest), + (320, &r.verifier_identity), + (352, &r.machine_id_digest), + ] { + b[offset..offset + 32].copy_from_slice(digest); + } + put64(&mut b, 384, r.generation); + put64(&mut b, 392, r.context_id); + b +} + +/// `SHA256("AIENOS-ADMISSION-RECEIPT-V1\0" || bytes[0..400])`. +pub fn receipt_digest(bytes: &[u8; RECEIPT_SIZE]) -> Digest { + let mut h = Sha256::new(); + h.update(RECEIPT_DIGEST_DOMAIN); + h.update(&bytes[..RECEIPT_SIGNATURE_OFFSET]); + h.finalize() +} + +/// Deterministic per-context nonce (§7.3). +pub fn receipt_nonce(verifier_identity: &Digest, sequence: u64) -> [u8; 16] { + let mut h = Sha256::new(); + h.update(RECEIPT_NONCE_DOMAIN); + h.update(verifier_identity); + h.update(&sequence.to_le_bytes()); + let d = h.finalize(); + let mut nonce = [0u8; 16]; + nonce.copy_from_slice(&d[..16]); + nonce +} + +/// Canonical verifier build identity bytes (§7.1): 40 lowercase hex commit +/// characters, target u16 LE, ABI u16 LE, qualification feature id. +/// Returns `None` unless `commit` is exactly 40 lowercase hex digits. +pub fn verifier_identity_bytes( + commit: &[u8], + target: u16, + abi: u16, + feature: u8, +) -> Option<[u8; 45]> { + if commit.len() != 40 + || !commit + .iter() + .all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f')) + { + return None; + } + let mut out = [0u8; 45]; + out[..40].copy_from_slice(commit); + out[40..42].copy_from_slice(&target.to_le_bytes()); + out[42..44].copy_from_slice(&abi.to_le_bytes()); + out[44] = feature; + Some(out) +} + +/// Stage codes (§7.3). +pub const MAX_REJECTION_STAGE: u16 = 9; +/// Loader reason codes (§7.3), after the `ArtifactError` range 1..=19. +pub const LOADER_REASON_FIRST: u16 = 0x101; +pub const LOADER_REASON_LAST: u16 = 0x10a; + +impl ReceiptDecision { + pub const fn from_u16(v: u16) -> Option { + match v { + 1 => Some(Self::Admitted), + 2 => Some(Self::Rejected), + 3 => Some(Self::CanaryFailed), + 4 => Some(Self::Destroyed), + _ => None, + } + } +} + +impl QualificationTier { + pub const fn from_u16(v: u16) -> Option { + match v { + 1 => Some(Self::Seed0bQemu), + 2 => Some(Self::Seed0bMachine1), + _ => None, + } + } + + pub const fn label(self) -> &'static str { + match self { + Self::Seed0bQemu => "SEED-0B-QEMU", + Self::Seed0bMachine1 => "SEED-0B-MACHINE1", + } + } +} + +impl ExecutionStatusCode { + pub const fn from_u32(v: u32) -> Option { + match v { + 0 => Some(Self::NotRun), + 1 => Some(Self::Exited), + 2 => Some(Self::Timeout), + 3 => Some(Self::Fault), + 4 => Some(Self::BadSyscall), + 5 => Some(Self::ResourceOverrun), + 6 => Some(Self::CanaryFailed), + _ => None, + } + } +} + +const fn valid_reason(code: u16) -> bool { + matches!(code, 1..=19) || (code >= LOADER_REASON_FIRST && code <= LOADER_REASON_LAST) +} + +/// Strictly decode one record (signed or unsigned). Error mapping: +/// short → `Truncated`, long → `WrongLength`, magic → `BadMagic`, +/// version/header/record size → `UnsupportedVersion`, unknown presence or +/// result bits → `UnsupportedFlags`, reserved bytes → `ReservedNonZero`, +/// signature algorithm → `BadSignatureFormat`, and every enum, code, +/// presence, consistency or nonce violation → `MalformedReceipt`. +pub fn decode(bytes: &[u8]) -> Result { + if bytes.len() < RECEIPT_SIZE { + return Err(ArtifactError::Truncated); + } + if bytes.len() > RECEIPT_SIZE { + return Err(ArtifactError::WrongLength); + } + if &bytes[0..8] != RECEIPT_MAGIC { + return Err(ArtifactError::BadMagic); + } + if get16(bytes, 8) != RECEIPT_VERSION + || usize::from(get16(bytes, 10)) != RECEIPT_HEADER_SIZE + || get32(bytes, 12) as usize != RECEIPT_SIZE + { + return Err(ArtifactError::UnsupportedVersion); + } + let flags = get32(bytes, 16); + let result_flags = get32(bytes, 72); + if flags & !VALID_FLAGS != 0 || result_flags & !VALID_RESULT_FLAGS != 0 { + return Err(ArtifactError::UnsupportedFlags); + } + if bytes[56..64].iter().any(|b| *b != 0) || bytes[500..512].iter().any(|b| *b != 0) { + return Err(ArtifactError::ReservedNonZero); + } + if bytes[400..500].iter().any(|b| *b != 0) { + if get16(bytes, 400) != SIGNATURE_ALGORITHM_ED25519 { + return Err(ArtifactError::BadSignatureFormat); + } + if bytes[402..404].iter().any(|b| *b != 0) { + return Err(ArtifactError::ReservedNonZero); + } + } + let malformed = ArtifactError::MalformedReceipt; + let decision = ReceiptDecision::from_u16(get16(bytes, 20)).ok_or(malformed)?; + let tier = QualificationTier::from_u16(get16(bytes, 22)).ok_or(malformed)?; + let execution_status = ExecutionStatusCode::from_u32(get32(bytes, 64)).ok_or(malformed)?; + let mut nonce = [0u8; 16]; + nonce.copy_from_slice(&bytes[32..48]); + let digest_at = |at: usize| { + let mut d = [0u8; 32]; + d.copy_from_slice(&bytes[at..at + 32]); + d + }; + let r = Receipt { + flags, + decision, + tier, + sequence: get64(bytes, 24), + nonce, + observed_time_ns: get64(bytes, 48), + execution_status, + exit_status: i32::from_le_bytes([bytes[68], bytes[69], bytes[70], bytes[71]]), + result_flags, + rejection_stage: get16(bytes, 76), + rejection_reason: get16(bytes, 78), + syscalls: get32(bytes, 80), + object_reads_ok: get32(bytes, 84), + denials: get32(bytes, 88), + frames_reserved: get32(bytes, 92), + artifact_id: digest_at(96), + payload_digest: digest_at(128), + artifact_signer_fingerprint: digest_at(160), + policy_digest: digest_at(192), + requested_capability_digest: digest_at(224), + granted_capability_digest: digest_at(256), + resource_envelope_digest: digest_at(288), + verifier_identity: digest_at(320), + machine_id_digest: digest_at(352), + generation: get64(bytes, 384), + context_id: get64(bytes, 392), + }; + validate(&r)?; + Ok(r) +} + +/// §7.1/§7.3 semantic rules shared by `decode` and producers. +pub fn validate(r: &Receipt) -> Result<(), ArtifactError> { + let bad = Err(ArtifactError::MalformedReceipt); + if r.flags & FLAG_MACHINE_ID == 0 && r.machine_id_digest != [0; 32] { + return bad; + } + if r.flags & FLAG_CONTEXT_ID == 0 && (r.generation != 0 || r.context_id != 0) { + return bad; + } + if r.flags & FLAG_TIMESTAMP == 0 && r.observed_time_ns != 0 { + return bad; + } + if r.rejection_stage > MAX_REJECTION_STAGE + || (r.rejection_reason != 0 && !valid_reason(r.rejection_reason)) + { + return bad; + } + match r.decision { + ReceiptDecision::Rejected => { + if r.rejection_stage == 0 + || r.rejection_reason == 0 + || r.execution_status != ExecutionStatusCode::NotRun + || r.exit_status != 0 + || r.syscalls != 0 + || r.object_reads_ok != 0 + || r.denials != 0 + || r.result_flags & !RESULT_RECLAIMED != 0 + { + return bad; + } + } + _ => { + if r.rejection_stage != 0 || r.rejection_reason != 0 { + return bad; + } + } + } + if r.result_flags & RESULT_CANARY_PASSED != 0 + && (r.execution_status != ExecutionStatusCode::Exited || r.exit_status != 0) + { + return bad; + } + if r.nonce != receipt_nonce(&r.verifier_identity, r.sequence) { + return bad; + } + Ok(()) +} + +/// True when bytes 400..512 are all zero (kernel-emitted record). +pub fn is_unsigned(bytes: &[u8; RECEIPT_SIZE]) -> bool { + bytes[RECEIPT_SIGNATURE_OFFSET..].iter().all(|b| *b == 0) +} + +/// `RECEIPT_SIGNATURE_DOMAIN || ReceiptDigest`. +pub fn signature_message(digest: &Digest) -> [u8; RECEIPT_SIGNATURE_DOMAIN.len() + 32] { + let mut m = [0u8; RECEIPT_SIGNATURE_DOMAIN.len() + 32]; + m[..RECEIPT_SIGNATURE_DOMAIN.len()].copy_from_slice(RECEIPT_SIGNATURE_DOMAIN); + m[RECEIPT_SIGNATURE_DOMAIN.len()..].copy_from_slice(digest); + m +} + +/// Sign a valid unsigned record in place. +pub fn sign( + bytes: &mut [u8; RECEIPT_SIZE], + signer: &impl ReceiptSigner, +) -> Result<(), ArtifactError> { + if !is_unsigned(bytes) { + return Err(ArtifactError::BadSignatureFormat); + } + decode(bytes)?; + let digest = receipt_digest(bytes); + let signature = signer.sign_receipt_digest(&digest)?; + put16(bytes, 400, SIGNATURE_ALGORITHM_ED25519); + bytes[404..436].copy_from_slice(&signer.signer_fingerprint()); + bytes[436..500].copy_from_slice(&signature); + Ok(()) +} + +/// Receipt signing keys the verifier trusts. Distinct from artifact anchors. +pub trait ReceiptAnchorSet { + fn find(&self, fingerprint: &Digest) -> Option<[u8; PUBLIC_KEY_SIZE]>; +} + +/// Production receipt anchors are empty until M5 and fail closed. +#[derive(Clone, Copy, Debug, Default)] +pub struct EmptyReceiptAnchorSet; + +impl ReceiptAnchorSet for EmptyReceiptAnchorSet { + fn find(&self, _fingerprint: &Digest) -> Option<[u8; PUBLIC_KEY_SIZE]> { + None + } +} + +/// Decode and authenticate a signed record. +pub fn verify( + bytes: &[u8], + anchors: &impl ReceiptAnchorSet, + signatures: &impl SignatureVerifier, +) -> Result { + let receipt = decode(bytes)?; + let mut record = [0u8; RECEIPT_SIZE]; + record.copy_from_slice(bytes); + if is_unsigned(&record) { + return Err(ArtifactError::BadSignatureFormat); + } + let mut fingerprint = [0u8; 32]; + fingerprint.copy_from_slice(&record[404..436]); + let key = anchors + .find(&fingerprint) + .ok_or(ArtifactError::UntrustedSigner)?; + if hash(&key) != fingerprint { + return Err(ArtifactError::UntrustedSigner); + } + let mut signature = [0u8; SIGNATURE_SIZE]; + signature.copy_from_slice(&record[436..500]); + let message = signature_message(&receipt_digest(&record)); + if !signatures.verify(&key, &message, &signature) { + return Err(ArtifactError::BadSignature); + } + Ok(receipt) +} + +/// TEST-ONLY SEED-0B receipt signing identity: RFC 8032 TEST 2 public key, +/// distinct from the artifact test key (TEST 1). Its seed exists only in +/// debug host qualification tooling and tests. +#[cfg(feature = "seed0b-test-anchor")] +pub mod seed0b_test_receipt_anchor { + use super::ReceiptAnchorSet; + use aienos_crypto::sha256::{hash, Digest}; + + pub const LABEL: &str = "SEED-0B QUALIFICATION RECEIPT KEY — TEST ONLY"; + + pub const PUBLIC_KEY: [u8; 32] = [ + 0x3d, 0x40, 0x17, 0xc3, 0xe8, 0x43, 0x89, 0x5a, 0x92, 0xb7, 0x0a, 0xa7, 0x4d, 0x1b, 0x7e, + 0xbc, 0x9c, 0x98, 0x2c, 0xcf, 0x2e, 0xc4, 0x96, 0x8c, 0xc0, 0xcd, 0x55, 0xf1, 0x2a, 0xf4, + 0x66, 0x0c, + ]; + + #[derive(Clone, Copy, Debug, Default)] + pub struct Seed0bTestReceiptAnchorSet; + + impl ReceiptAnchorSet for Seed0bTestReceiptAnchorSet { + fn find(&self, fingerprint: &Digest) -> Option<[u8; 32]> { + (*fingerprint == hash(&PUBLIC_KEY)).then_some(PUBLIC_KEY) + } + } +} + +fn get16(b: &[u8], at: usize) -> u16 { + u16::from_le_bytes([b[at], b[at + 1]]) +} +fn get32(b: &[u8], at: usize) -> u32 { + u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]) +} +fn get64(b: &[u8], at: usize) -> u64 { + let mut v = [0u8; 8]; + v.copy_from_slice(&b[at..at + 8]); + u64::from_le_bytes(v) +} + +fn put16(b: &mut [u8], at: usize, v: u16) { + b[at..at + 2].copy_from_slice(&v.to_le_bytes()); +} +fn put32(b: &mut [u8], at: usize, v: u32) { + b[at..at + 4].copy_from_slice(&v.to_le_bytes()); +} +fn put64(b: &mut [u8], at: usize, v: u64) { + b[at..at + 8].copy_from_slice(&v.to_le_bytes()); +} diff --git a/crates/aienos-artifact/src/receipt_tests.rs b/crates/aienos-artifact/src/receipt_tests.rs new file mode 100644 index 00000000..99dd7dd5 --- /dev/null +++ b/crates/aienos-artifact/src/receipt_tests.rs @@ -0,0 +1,584 @@ +//! Admission Receipt v0 tests: layout, golden bytes, strict decoding, +//! mutation and signature behaviour. + +use std::vec::Vec; + +use ed25519_dalek::{Signer, SigningKey}; + +use crate::error::ArtifactError; +use crate::receipt::*; +use crate::signature::{Ed25519Verifier, ReceiptSigner}; +use aienos_crypto::sha256::{hash, Digest}; + +/// RFC 8032 TEST 2 seed: TEST-ONLY receipt key for SEED-0B qualification. +const TEST2_SEED: [u8; 32] = [ + 0x4c, 0xcd, 0x08, 0x9b, 0x28, 0xff, 0x96, 0xda, 0x9d, 0xb6, 0xc3, 0x46, 0xec, 0x11, 0x4e, 0x0f, + 0x5b, 0x8a, 0x31, 0x9f, 0x35, 0xab, 0xa6, 0x24, 0xda, 0x8c, 0xf6, 0xed, 0x4f, 0xb8, 0xa6, 0xfb, +]; +/// RFC 8032 TEST 3 seed: a key no receipt anchor trusts. +const TEST3_SEED: [u8; 32] = [ + 0xc5, 0xaa, 0x8d, 0xf4, 0x3f, 0x9f, 0x83, 0x7b, 0xed, 0xb7, 0x44, 0x2f, 0x31, 0xdc, 0xb7, 0xb1, + 0x66, 0xd3, 0x85, 0x35, 0x07, 0x6f, 0x09, 0x4b, 0x85, 0xce, 0x3a, 0x2e, 0x0b, 0x44, 0x58, 0xf7, +]; + +struct KeySigner(SigningKey); + +impl ReceiptSigner for KeySigner { + fn signer_fingerprint(&self) -> Digest { + hash(&self.0.verifying_key().to_bytes()) + } + fn sign_receipt_digest(&self, digest: &Digest) -> Result<[u8; 64], ArtifactError> { + Ok(self.0.sign(&signature_message(digest)).to_bytes()) + } +} + +struct OneKey([u8; 32]); + +impl ReceiptAnchorSet for OneKey { + fn find(&self, fingerprint: &Digest) -> Option<[u8; 32]> { + (hash(&self.0) == *fingerprint).then_some(self.0) + } +} + +fn pattern(seed: u8) -> Digest { + let mut d = [0u8; 32]; + for (i, b) in d.iter_mut().enumerate() { + *b = seed.wrapping_add(i as u8); + } + d +} + +fn admitted() -> Receipt { + let verifier_identity = pattern(0x80); + Receipt { + flags: 0, + decision: ReceiptDecision::Admitted, + tier: QualificationTier::Seed0bQemu, + sequence: 1, + nonce: receipt_nonce(&verifier_identity, 1), + observed_time_ns: 0, + execution_status: ExecutionStatusCode::Exited, + exit_status: 0, + result_flags: RESULT_READ_OK + | RESULT_WRITE_DENIED + | RESULT_RECLAIMED + | RESULT_CANARY_PASSED + | RESULT_FORGED_DENIED + | RESULT_MAPPED_BYTES_MATCH + | RESULT_EXECUTED_BYTES_MATCH + | RESULT_WX_SEALED, + rejection_stage: 0, + rejection_reason: 0, + syscalls: 8, + object_reads_ok: 2, + denials: 5, + frames_reserved: 10, + artifact_id: pattern(0x10), + payload_digest: pattern(0x20), + artifact_signer_fingerprint: pattern(0x30), + policy_digest: pattern(0x40), + requested_capability_digest: pattern(0x50), + granted_capability_digest: pattern(0x60), + resource_envelope_digest: pattern(0x70), + verifier_identity, + machine_id_digest: [0; 32], + generation: 0, + context_id: 0, + } +} + +fn rejected() -> Receipt { + let verifier_identity = pattern(0x80); + Receipt { + decision: ReceiptDecision::Rejected, + sequence: 2, + nonce: receipt_nonce(&verifier_identity, 2), + execution_status: ExecutionStatusCode::NotRun, + exit_status: 0, + result_flags: RESULT_RECLAIMED, + rejection_stage: 3, + rejection_reason: ArtifactError::BadSignature as u16, + syscalls: 0, + object_reads_ok: 0, + denials: 0, + frames_reserved: 0, + artifact_signer_fingerprint: [0; 32], + granted_capability_digest: [0; 32], + ..admitted() + } +} + +fn signed(r: &Receipt, seed: &[u8; 32]) -> [u8; RECEIPT_SIZE] { + let mut bytes = encode(r); + sign(&mut bytes, &KeySigner(SigningKey::from_bytes(seed))).unwrap(); + bytes +} + +fn hex(bytes: &[u8]) -> std::string::String { + use core::fmt::Write; + let mut s = std::string::String::new(); + for b in bytes { + let _ = write!(s, "{b:02x}"); + } + s +} + +fn le16(b: &[u8], at: usize) -> u16 { + u16::from_le_bytes([b[at], b[at + 1]]) +} +fn le32(b: &[u8], at: usize) -> u32 { + u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]) +} + +#[test] +fn layout_matches_adr_table_offsets() { + let r = admitted(); + let b = encode(&r); + assert_eq!(&b[0..8], b"AIENRCP\0"); + assert_eq!(le16(&b, 8), 0); + assert_eq!(le16(&b, 10), 96); + assert_eq!(le32(&b, 12), 512); + assert_eq!(le32(&b, 16), 0); + assert_eq!(le16(&b, 20), 1); + assert_eq!(le16(&b, 22), 1); + assert_eq!(&b[24..32], &1u64.to_le_bytes()); + assert_eq!(&b[32..48], &r.nonce); + assert!(b[48..64].iter().all(|x| *x == 0)); + assert_eq!(le32(&b, 64), 1); + assert_eq!(le32(&b, 68), 0); + assert_eq!(le32(&b, 72), 0xff); + assert_eq!((le16(&b, 76), le16(&b, 78)), (0, 0)); + assert_eq!( + (le32(&b, 80), le32(&b, 84), le32(&b, 88), le32(&b, 92)), + (8, 2, 5, 10) + ); + for (at, seed) in [ + (96, 0x10), + (128, 0x20), + (160, 0x30), + (192, 0x40), + (224, 0x50), + (256, 0x60), + (288, 0x70), + (320, 0x80), + ] { + assert_eq!(&b[at..at + 32], &pattern(seed), "digest at {at}"); + } + assert!( + b[352..].iter().all(|x| *x == 0), + "absent fields and signature block" + ); + let exit = Receipt { + execution_status: ExecutionStatusCode::Exited, + exit_status: -2, + result_flags: 0, + ..r + }; + assert_eq!(&encode(&exit)[68..72], &(-2i32).to_le_bytes()); +} + +#[test] +fn golden_bytes_are_stable() { + let a = encode(&admitted()); + let r = encode(&rejected()); + assert_eq!( + hex(&receipt_digest(&a)), + GOLDEN_ADMITTED_DIGEST, + "admitted record: {}", + hex(&a) + ); + assert_eq!(hex(&a), GOLDEN_ADMITTED_RECORD); + assert_eq!( + hex(&receipt_digest(&r)), + GOLDEN_REJECTED_DIGEST, + "rejected record: {}", + hex(&r) + ); +} + +#[test] +fn encoding_is_deterministic_and_round_trips() { + for r in [admitted(), rejected()] { + let first = encode(&r); + assert_eq!(first, encode(&r)); + assert_eq!(decode(&first), Ok(r)); + let s = signed(&r, &TEST2_SEED); + assert_eq!(decode(&s), Ok(r)); + assert_eq!(receipt_digest(&first), receipt_digest(&s)); + } +} + +#[test] +fn nonce_and_verifier_identity_vectors() { + let id = pattern(0x80); + assert_ne!(receipt_nonce(&id, 1), receipt_nonce(&id, 2)); + assert_ne!(receipt_nonce(&id, 1), receipt_nonce(&pattern(0x81), 1)); + let commit = b"71cb1703484cbc9d56eabe43402a6f9bf62b1028"; + let bytes = verifier_identity_bytes(commit, 1, 1, 1).unwrap(); + assert_eq!(&bytes[..40], commit); + assert_eq!(&bytes[40..], &[1, 0, 1, 0, 1]); + assert!( + verifier_identity_bytes(b"71CB1703484CBC9D56EABE43402A6F9BF62B1028", 1, 1, 1).is_none() + ); + assert!(verifier_identity_bytes(&commit[..39], 1, 1, 1).is_none()); + assert!( + verifier_identity_bytes(b"71cb1703484cbc9d56eabe43402a6f9bf62b102g", 1, 1, 1).is_none() + ); +} + +#[test] +fn rejects_length_magic_version_and_sizes() { + let b = encode(&admitted()); + assert_eq!(decode(&b[..511]), Err(ArtifactError::Truncated)); + assert_eq!(decode(&[]), Err(ArtifactError::Truncated)); + let mut long = b.to_vec(); + long.push(0); + assert_eq!(decode(&long), Err(ArtifactError::WrongLength)); + let set = |at: usize, v: u8| { + let mut m = b; + m[at] = v; + m + }; + assert_eq!(decode(&set(0, b'X')), Err(ArtifactError::BadMagic)); + assert_eq!(decode(&set(8, 1)), Err(ArtifactError::UnsupportedVersion)); + assert_eq!(decode(&set(10, 95)), Err(ArtifactError::UnsupportedVersion)); + assert_eq!(decode(&set(13, 0)), Err(ArtifactError::UnsupportedVersion)); +} + +#[test] +fn rejects_unknown_flags_and_nonzero_reserved_bytes() { + let b = encode(&admitted()); + for bit in 3..32 { + let mut m = b; + m[16..20].copy_from_slice(&(1u32 << bit).to_le_bytes()); + assert_eq!( + decode(&m), + Err(ArtifactError::UnsupportedFlags), + "flag bit {bit}" + ); + } + for bit in 8..32 { + let mut m = b; + m[72..76].copy_from_slice(&(0xffu32 | (1 << bit)).to_le_bytes()); + assert_eq!( + decode(&m), + Err(ArtifactError::UnsupportedFlags), + "result bit {bit}" + ); + } + for at in (56..64).chain(500..512) { + let mut m = b; + m[at] = 1; + assert_eq!( + decode(&m), + Err(ArtifactError::ReservedNonZero), + "reserved {at}" + ); + } + let mut s = signed(&admitted(), &TEST2_SEED); + s[402] = 1; + assert_eq!(decode(&s), Err(ArtifactError::ReservedNonZero)); + let mut s = signed(&admitted(), &TEST2_SEED); + s[400] = 2; + assert_eq!(decode(&s), Err(ArtifactError::BadSignatureFormat)); +} + +#[test] +fn rejects_unknown_enum_and_code_values() { + let b = encode(&admitted()); + let m16 = |at: usize, v: u16| { + let mut m = b; + m[at..at + 2].copy_from_slice(&v.to_le_bytes()); + m + }; + for v in [0u16, 5, 0xffff] { + assert_eq!( + decode(&m16(20, v)), + Err(ArtifactError::MalformedReceipt), + "decision {v}" + ); + } + for v in [0u16, 3, 0xffff] { + assert_eq!( + decode(&m16(22, v)), + Err(ArtifactError::MalformedReceipt), + "tier {v}" + ); + } + for v in [7u32, 0xffff_ffff] { + let mut m = b; + m[64..68].copy_from_slice(&v.to_le_bytes()); + assert_eq!( + decode(&m), + Err(ArtifactError::MalformedReceipt), + "status {v}" + ); + } + let base = rejected(); + for stage in [0u16, 10, 0xffff] { + let r = Receipt { + rejection_stage: stage, + ..base + }; + assert_eq!( + decode(&encode(&r)), + Err(ArtifactError::MalformedReceipt), + "stage {stage}" + ); + } + for reason in [0u16, 20, 0x100, 0x10b, 0xffff] { + let r = Receipt { + rejection_reason: reason, + ..base + }; + assert_eq!( + decode(&encode(&r)), + Err(ArtifactError::MalformedReceipt), + "reason {reason}" + ); + } + for reason in (1u16..=19).chain(0x101..=0x10a) { + let r = Receipt { + rejection_reason: reason, + ..base + }; + assert_eq!(decode(&encode(&r)), Ok(r), "valid reason {reason}"); + } +} + +#[test] +fn optional_fields_require_their_presence_flags() { + let base = admitted(); + let cases = [ + Receipt { + machine_id_digest: pattern(1), + ..base + }, + Receipt { + generation: 1, + ..base + }, + Receipt { + context_id: 1, + ..base + }, + Receipt { + observed_time_ns: 1, + ..base + }, + ]; + for r in cases { + assert_eq!(decode(&encode(&r)), Err(ArtifactError::MalformedReceipt)); + } + let present = Receipt { + flags: VALID_FLAGS, + machine_id_digest: pattern(1), + generation: 3, + context_id: 4, + observed_time_ns: 5, + ..base + }; + assert_eq!(decode(&encode(&present)), Ok(present)); +} + +#[test] +fn decision_consistency_rules_are_enforced() { + let a = admitted(); + let r = rejected(); + let bad = [ + Receipt { + rejection_stage: 3, + rejection_reason: 18, + ..a + }, + Receipt { + rejection_reason: 18, + ..a + }, + Receipt { + execution_status: ExecutionStatusCode::Exited, + ..r + }, + Receipt { + exit_status: 1, + ..r + }, + Receipt { syscalls: 1, ..r }, + Receipt { + object_reads_ok: 1, + ..r + }, + Receipt { denials: 1, ..r }, + Receipt { + result_flags: RESULT_RECLAIMED | RESULT_READ_OK, + ..r + }, + Receipt { + exit_status: 3, + ..a + }, + Receipt { + execution_status: ExecutionStatusCode::Fault, + ..a + }, + Receipt { sequence: 9, ..a }, + Receipt { + nonce: [0; 16], + ..a + }, + ]; + for (i, case) in bad.iter().enumerate() { + assert_eq!( + decode(&encode(case)), + Err(ArtifactError::MalformedReceipt), + "case {i}" + ); + } + let faulted = Receipt { + execution_status: ExecutionStatusCode::Fault, + result_flags: RESULT_RECLAIMED | RESULT_WX_SEALED, + ..a + }; + assert_eq!(decode(&encode(&faulted)), Ok(faulted)); +} + +#[test] +fn every_single_bit_change_in_the_signed_range_changes_meaning_or_is_rejected() { + let b = encode(&admitted()); + let digest = receipt_digest(&b); + let original = decode(&b).unwrap(); + for at in 0..RECEIPT_SIGNATURE_OFFSET { + for mask in [0x01u8, 0x80] { + let mut m = b; + m[at] ^= mask; + assert_ne!(receipt_digest(&m), digest, "digest ignores byte {at}"); + if let Ok(r) = decode(&m) { + assert_ne!(r, original, "byte {at} mask {mask:#x} decoded identically"); + } + } + } +} + +#[test] +fn signature_block_is_outside_the_digest_and_fully_authenticated() { + let anchors = OneKey( + SigningKey::from_bytes(&TEST2_SEED) + .verifying_key() + .to_bytes(), + ); + let s = signed(&admitted(), &TEST2_SEED); + assert_eq!(verify(&s, &anchors, &Ed25519Verifier), Ok(admitted())); + assert_eq!(receipt_digest(&s), receipt_digest(&encode(&admitted()))); + for at in RECEIPT_SIGNATURE_OFFSET..RECEIPT_SIZE { + let mut m = s; + m[at] ^= 0x01; + assert!(verify(&m, &anchors, &Ed25519Verifier).is_err(), "byte {at}"); + } + for at in 0..RECEIPT_SIGNATURE_OFFSET { + let mut m = s; + m[at] ^= 0x01; + assert!( + verify(&m, &anchors, &Ed25519Verifier).is_err(), + "signed byte {at}" + ); + } +} + +#[test] +fn unsigned_untrusted_and_production_verification_fail_closed() { + let anchors = OneKey( + SigningKey::from_bytes(&TEST2_SEED) + .verifying_key() + .to_bytes(), + ); + let unsigned = encode(&admitted()); + assert_eq!( + verify(&unsigned, &anchors, &Ed25519Verifier), + Err(ArtifactError::BadSignatureFormat) + ); + let other = signed(&admitted(), &TEST3_SEED); + assert_eq!( + verify(&other, &anchors, &Ed25519Verifier), + Err(ArtifactError::UntrustedSigner) + ); + let good = signed(&admitted(), &TEST2_SEED); + assert_eq!( + verify(&good, &EmptyReceiptAnchorSet, &Ed25519Verifier), + Err(ArtifactError::UntrustedSigner) + ); + let mut forged = good; + forged[436] ^= 0xff; + assert_eq!( + verify(&forged, &anchors, &Ed25519Verifier), + Err(ArtifactError::BadSignature) + ); + let mut resigned = good; + assert_eq!( + sign( + &mut resigned, + &KeySigner(SigningKey::from_bytes(&TEST2_SEED)) + ), + Err(ArtifactError::BadSignatureFormat) + ); + let mut invalid = encode(&Receipt { + denials: 1, + ..rejected() + }); + assert_eq!( + sign( + &mut invalid, + &KeySigner(SigningKey::from_bytes(&TEST2_SEED)) + ), + Err(ArtifactError::MalformedReceipt) + ); +} + +#[cfg(feature = "seed0b-test-anchor")] +#[test] +fn test_receipt_anchor_is_rfc8032_test2_and_distinct_from_artifact_key() { + use crate::receipt::seed0b_test_receipt_anchor::{Seed0bTestReceiptAnchorSet, PUBLIC_KEY}; + use crate::signature::seed0b_test_anchor::PUBLIC_KEY as ARTIFACT_KEY; + assert_eq!( + SigningKey::from_bytes(&TEST2_SEED) + .verifying_key() + .to_bytes(), + PUBLIC_KEY + ); + assert_ne!(PUBLIC_KEY, ARTIFACT_KEY); + let s = signed(&admitted(), &TEST2_SEED); + assert_eq!( + verify(&s, &Seed0bTestReceiptAnchorSet, &Ed25519Verifier), + Ok(admitted()) + ); + let other = signed(&admitted(), &TEST3_SEED); + assert_eq!( + verify(&other, &Seed0bTestReceiptAnchorSet, &Ed25519Verifier), + Err(ArtifactError::UntrustedSigner) + ); +} + +#[test] +fn arbitrary_records_never_panic_the_decoder() { + let base = encode(&admitted()); + let mut state = 0x9e37_79b9_7f4a_7c15u64; + let mut buffers: Vec<[u8; RECEIPT_SIZE]> = Vec::new(); + for _ in 0..512 { + let mut m = base; + for _ in 0..8 { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + m[(state as usize) % RECEIPT_SIZE] = (state >> 32) as u8; + } + buffers.push(m); + } + for m in &buffers { + let _ = decode(m); + } +} + +const GOLDEN_ADMITTED_DIGEST: &str = + "16bcbe523a62d9f4c907729fb2fb09d630ce36f80d7169e202730173a59bdfdc"; +const GOLDEN_ADMITTED_RECORD: &str = "4149454e52435000000060000002000000000000010001000100000000000000e28b2fcc80dd4e973fbc3d13dc62801b000000000000000000000000000000000100000000000000ff000000000000000800000002000000050000000a000000101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; +const GOLDEN_REJECTED_DIGEST: &str = + "f12ebace5ec0f2a8f06c415d58d936389dcc2fed64dbed4bc91efd01a734a6a3"; diff --git a/docs/adr/0014-binary-artifact-v0-and-native-admission.md b/docs/adr/0014-binary-artifact-v0-and-native-admission.md index 1789751f..e74bc617 100644 --- a/docs/adr/0014-binary-artifact-v0-and-native-admission.md +++ b/docs/adr/0014-binary-artifact-v0-and-native-admission.md @@ -292,16 +292,20 @@ presence flags, and nonzero absent optional fields are rejected. | 12 | 4 | record_size | `512` | | 16 | 4 | flags | bit 0 machine ID present; bit 1 context ID present; bit 2 timestamp present; all others zero | | 20 | 2 | decision | `1` admitted; `2` rejected; `3` canary failed; `4` destroyed | -| 22 | 2 | qualification_tier | `1` = SEED-0B test qualification | +| 22 | 2 | qualification_tier | `1` = SEED-0B QEMU test qualification; `2` = SEED-0B Machine 1 test qualification; `0` and all others rejected (no production tier in v0) | | 24 | 8 | sequence | monotonically increasing sequence within one verifier context | | 32 | 16 | nonce | unique within that verifier context | | 48 | 8 | observed_time_ns | UTC observation metadata, or zero when flag 2 is clear; never an admission input | | 56 | 8 | reserved | zero | | 64 | 4 | execution_status | `0` not run; `1` exited; `2` timeout; `3` fault; `4` bad syscall; `5` resource overrun; `6` canary failed | | 68 | 4 | exit_status | signed 32-bit little-endian task exit code; zero if not executed | -| 72 | 4 | result_flags | bit 0 read succeeded; bit 1 write denied; bit 2 candidate reclaimed; bit 3 canary passed; all others zero | -| 76 | 4 | reserved | zero | -| 80 | 16 | reserved | zero | +| 72 | 4 | result_flags | bit 0 authorized read succeeded; bit 1 write denied; bit 2 candidate reclaimed; bit 3 canary passed; bit 4 forged handle denied; bit 5 mapped bytes matched admitted digest; bit 6 executed bytes matched mapped bytes; bit 7 W^X seal audit passed; all others zero | +| 76 | 2 | rejection_stage | `0` when admitted; otherwise the §7.3 stage code at which the candidate was refused | +| 78 | 2 | rejection_reason | `0` when admitted; otherwise the §7.3 stable reason code | +| 80 | 4 | syscalls | EL0 syscalls taken; zero if not executed | +| 84 | 4 | object_reads_ok | authorized object reads that succeeded | +| 88 | 4 | denials | syscalls answered with a denial | +| 92 | 4 | frames_reserved | task frames reserved (content, window tables, shadow tables); zero if refused before reservation | | 96 | 32 | artifact_id | ArtifactId | | 128 | 32 | payload_digest | SHA-256 of exact serialized code/data payload | | 160 | 32 | artifact_signer_fingerprint | fingerprint from verified artifact signature block | @@ -346,6 +350,46 @@ The machine ID slot contains this digest of the opaque provisioned MachineId, not hardware make/model data. If M5 has not provisioned a MachineId, the field is all zero and the presence flag is clear. +Consistency rules (decoder-enforced): an admitted receipt has zero +`rejection_stage` and `rejection_reason`. A rejected receipt has both +nonzero, `execution_status` 0, `exit_status` 0, zero counters, and no +result flag other than bit 2. Canary passed (bit 3) requires +`execution_status` 1 and `exit_status` 0. Fields that the failing stage had +not yet computed are all zero (for example `granted_capability_digest` +before Authorized; every identity field when parsing failed). + +### 7.3 Stage, reason and outcome codes + +Stage codes: `1` received, `2` staged, `3` verified, `4` authorized, +`5` reserved, `6` mapped, `7` hashed, `8` sealed, `9` capabilities +installed. + +Reason codes `1..=19` are the `ArtifactError` values of §4 in declaration +order (`BadMagic` = 1 … `RightsEscalation` = 19); `MalformedReceipt` (20) +is a receipt-decoding error and never a candidate reason. Loader reasons: +`0x101` no frames, `0x102` staging too large, `0x103` mapping, `0x104` +mapped digest mismatch, `0x105` W^X audit, `0x106` capability install, +`0x107` scheduler full, `0x108` executed digest mismatch, `0x109` reclaim, +`0x10a` firmware read. Any other value is rejected. + +`execution_status` maps the task runtime outcome: not run `0`, exited `1`, +timeout `2`, fault `3`, bad syscall `4`, resource overrun `5`. `exit_status` +is the low 32 bits of the EL0 exit code read as a two's-complement `i32`. + +Sequence and nonce in a qualification boot: `sequence` counts candidates +from 1 within one boot (the verifier context; there is no persistent +counter before M4) and `flags` bit 1 stays clear. +`nonce = SHA256("AIENOS-ADMISSION-RECEIPT-NONCE-V1\0" || verifier_identity || sequence_u64_le)[0..16]`, +which is unique within the context and reproducible from the receipt. + +Signing custody in SEED-0B: the kernel never holds a receipt private key. +It emits the canonical record with the signature block (bytes 400..512) +all zero plus the ReceiptDigest. The host qualification harness re-derives +the digest from the emitted bytes, checks every bound field against the +artifact it supplied, and signs the record with the TEST-ONLY SEED-0B +receipt key (RFC 8032 TEST 2, distinct from the artifact test key), then +verifies the signed record. Production receipt keys wait for M5. + ### 7.2 Receipt digest and signature The receipt signature block is excluded from its own digest. The digest diff --git a/scripts/verify_all.sh b/scripts/verify_all.sh index e0e73b86..caf9b1d3 100755 --- a/scripts/verify_all.sh +++ b/scripts/verify_all.sh @@ -72,6 +72,19 @@ for features in firmware handoff seed0b-qualification usb-keyboard; do done echo "PASS clippy: aarch64-unknown-none kernel and aarch64-unknown-uefi images, zero warnings" +# Step 3c: TEST-ONLY SEED-0B qualification code paths are feature-gated and +# so absent from the default runs above; test and lint them explicitly. +echo "" +echo "--- [SEED-0B qualification features: tests and clippy] ---" +cargo test -p aienos-artifact --features seed0b-test-anchor +cargo test -p aienos-artifact-tool --features seed0b-test-signing +cargo clippy -p aienos-artifact-tool --all-targets --features seed0b-test-signing -- -D warnings +if cargo build --release -p aienos-artifact-tool --features seed0b-test-signing >/dev/null 2>&1; then + echo "FAIL release build accepted the TEST-ONLY SEED-0B signing identity" >&2 + exit 1 +fi +echo "PASS SEED-0B qualification features tested and linted; release build refuses the test signing identity" + # Step 4: Bare-metal library compilation check (not a boot test) echo "" echo "--- [Bare-Metal Target Compilation Check] ---"