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-artifact-tool / src / receipt_cmd.rs

342 lines · 13491 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//! `receipt` subcommands: inspect, cross-check against the artifact the
17//! host supplied, TEST-ONLY signing, and verification (ADR 0014 ยง7).
18
19use std::error::Error;
20use std::fs;
21
22use aienos_artifact::canonical::{requested_capability_digest, resource_envelope_digest};
23use aienos_artifact::receipt::{
24 decode, is_unsigned, receipt_digest, verify, Receipt, ReceiptDecision, RECEIPT_SIZE,
25};
26use aienos_artifact::signature::Ed25519Verifier;
27use aienos_artifact::verify::parse_and_identify;
28
29use crate::hex;
30
31pub 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";
32
33pub fn run(args: &[String]) -> Result<(), Box<dyn Error>> {
34 match (args.first().map(String::as_str), args.len()) {
35 (Some("inspect"), 2) => inspect(&read(&args[1])?),
36 (Some("check"), 3) => check(&read(&args[1])?, &fs::read(&args[2])?),
37 (Some("from-hex"), 3) => from_hex(&args[1], &args[2]),
38 (Some("sign-test"), 3) => sign_test(&read(&args[1])?, &args[2]),
39 (Some("verify"), 2) => verify_file(&read(&args[1])?),
40 _ => Err(USAGE.into()),
41 }
42}
43
44fn read(path: &str) -> Result<[u8; RECEIPT_SIZE], Box<dyn Error>> {
45 let bytes = fs::read(path)?;
46 let record: [u8; RECEIPT_SIZE] = bytes.as_slice().try_into().map_err(|_| {
47 format!(
48 "receipt must be exactly {RECEIPT_SIZE} bytes, got {}",
49 bytes.len()
50 )
51 })?;
52 Ok(record)
53}
54
55fn decoded(record: &[u8; RECEIPT_SIZE]) -> Result<Receipt, Box<dyn Error>> {
56 decode(record).map_err(|e| format!("receipt rejected: {e:?}").into())
57}
58
59fn inspect(record: &[u8; RECEIPT_SIZE]) -> Result<(), Box<dyn Error>> {
60 let r = decoded(record)?;
61 println!("RECEIPT_DIGEST: {}", hex(&receipt_digest(record)));
62 println!("SIGNED: {}", if is_unsigned(record) { "no" } else { "yes" });
63 println!("DECISION: {:?}", r.decision);
64 println!("TIER: {}", r.tier.label());
65 println!("SEQUENCE: {}", r.sequence);
66 println!(
67 "REJECTION: stage={} reason={:#x}",
68 r.rejection_stage, r.rejection_reason
69 );
70 println!(
71 "EXECUTION: status={:?} exit={} syscalls={} reads_ok={} denials={}",
72 r.execution_status, r.exit_status, r.syscalls, r.object_reads_ok, r.denials
73 );
74 println!("RESULT_FLAGS: {:#04x}", r.result_flags);
75 println!("FRAMES_RESERVED: {}", r.frames_reserved);
76 for (name, digest) in [
77 ("ARTIFACT_ID", &r.artifact_id),
78 ("PAYLOAD_SHA256", &r.payload_digest),
79 ("ARTIFACT_SIGNER", &r.artifact_signer_fingerprint),
80 ("POLICY_DIGEST", &r.policy_digest),
81 ("REQUESTED_CAPS_DIGEST", &r.requested_capability_digest),
82 ("GRANTED_CAPS_DIGEST", &r.granted_capability_digest),
83 ("RESOURCE_ENVELOPE_DIGEST", &r.resource_envelope_digest),
84 ("VERIFIER_IDENTITY", &r.verifier_identity),
85 ] {
86 println!("{name}: {}", hex(digest));
87 }
88 Ok(())
89}
90
91/// A kernel-emitted record must be unsigned and must bind exactly the
92/// artifact the host supplied. Fields the failing stage had not computed may
93/// be zero; any nonzero identity field must match.
94fn check(record: &[u8; RECEIPT_SIZE], artifact: &[u8]) -> Result<(), Box<dyn Error>> {
95 if !is_unsigned(record) {
96 return Err("kernel-emitted receipts must be unsigned".into());
97 }
98 let r = decoded(record)?;
99 let admitted = r.decision == ReceiptDecision::Admitted;
100 let expected = match parse_and_identify(artifact) {
101 Ok(identified) => Some((
102 *identified.artifact_id.as_bytes(),
103 identified.payload_digest,
104 *identified.artifact.signer_fingerprint,
105 requested_capability_digest(identified.artifact.capability_request_bytes),
106 resource_envelope_digest(identified.artifact.resource_envelope_bytes),
107 )),
108 Err(_) => None,
109 };
110 let fields = [
111 ("artifact_id", r.artifact_id),
112 ("payload_digest", r.payload_digest),
113 ("artifact_signer_fingerprint", r.artifact_signer_fingerprint),
114 ("requested_capability_digest", r.requested_capability_digest),
115 ("resource_envelope_digest", r.resource_envelope_digest),
116 ];
117 match expected {
118 None => {
119 if admitted {
120 return Err("admitted receipt for an artifact the host cannot parse".into());
121 }
122 for (name, value) in fields {
123 if value != [0; 32] {
124 return Err(format!("{name} must be zero for an unparseable artifact").into());
125 }
126 }
127 }
128 Some((id, payload, signer, requested, resources)) => {
129 for ((name, value), want) in fields
130 .into_iter()
131 .zip([id, payload, signer, requested, resources])
132 {
133 let zero_allowed = !admitted;
134 if value != want && !(zero_allowed && value == [0; 32]) {
135 return Err(format!("{name} does not bind the supplied artifact").into());
136 }
137 }
138 if admitted && r.granted_capability_digest == [0; 32] {
139 return Err("admitted receipt without a granted-capability digest".into());
140 }
141 }
142 }
143 println!(
144 "RECEIPT_CHECK: PASS digest={} decision={:?} tier={} stage={} reason={:#x} status={:?} exit={} syscalls={} reads_ok={} denials={} flags={:#04x}",
145 hex(&receipt_digest(record)),
146 r.decision,
147 r.tier.label(),
148 r.rejection_stage,
149 r.rejection_reason,
150 r.execution_status,
151 r.exit_status,
152 r.syscalls,
153 r.object_reads_ok,
154 r.denials,
155 r.result_flags
156 );
157 Ok(())
158}
159
160fn from_hex(text: &str, out: &str) -> Result<(), Box<dyn Error>> {
161 let text = text.trim();
162 if text.len() != RECEIPT_SIZE * 2
163 || !text.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f'))
164 {
165 return Err(format!("expected {} lowercase hex characters", RECEIPT_SIZE * 2).into());
166 }
167 let bytes: Vec<u8> = (0..RECEIPT_SIZE)
168 .map(|i| u8::from_str_radix(&text[2 * i..2 * i + 2], 16))
169 .collect::<Result<_, _>>()?;
170 fs::write(out, bytes)?;
171 println!("FROM_HEX: PASS");
172 Ok(())
173}
174
175fn sign_test(record: &[u8; RECEIPT_SIZE], out: &str) -> Result<(), Box<dyn Error>> {
176 #[cfg(feature = "seed0b-test-signing")]
177 {
178 use aienos_artifact::receipt::{sign, signature_message};
179 use aienos_artifact::signature::ReceiptSigner;
180 use aienos_crypto::sha256::{hash, Digest};
181 use ed25519_dalek::{Signer, SigningKey};
182
183 struct TestReceiptKey(SigningKey);
184 impl ReceiptSigner for TestReceiptKey {
185 fn signer_fingerprint(&self) -> Digest {
186 hash(&self.0.verifying_key().to_bytes())
187 }
188 fn sign_receipt_digest(
189 &self,
190 digest: &Digest,
191 ) -> Result<[u8; 64], aienos_artifact::ArtifactError> {
192 Ok(self.0.sign(&signature_message(digest)).to_bytes())
193 }
194 }
195
196 let key = TestReceiptKey(SigningKey::from_bytes(&test_only_receipt_seed()));
197 let mut signed = *record;
198 sign(&mut signed, &key).map_err(|e| format!("cannot sign receipt: {e:?}"))?;
199 fs::write(out, signed)?;
200 println!("RECEIPT_SIGN: TEST ONLY SEED-0B QUALIFICATION RECEIPT KEY");
201 println!(
202 "RECEIPT_SIGNER_FINGERPRINT: {}",
203 hex(&key.signer_fingerprint())
204 );
205 Ok(())
206 }
207 #[cfg(not(feature = "seed0b-test-signing"))]
208 {
209 let _ = (record, out);
210 Err("receipt signing requires explicit feature seed0b-test-signing; production receipt keys are not available".into())
211 }
212}
213
214fn verify_file(record: &[u8; RECEIPT_SIZE]) -> Result<(), Box<dyn Error>> {
215 #[cfg(feature = "seed0b-test-signing")]
216 {
217 use aienos_artifact::receipt::seed0b_test_receipt_anchor::Seed0bTestReceiptAnchorSet;
218 let r = verify(record, &Seed0bTestReceiptAnchorSet, &Ed25519Verifier)
219 .map_err(|e| format!("receipt verification failed: {e:?}"))?;
220 println!(
221 "RECEIPT_VERIFY: PASS digest={} decision={:?} tier={} trust=SEED-0B-TEST-ONLY",
222 hex(&receipt_digest(record)),
223 r.decision,
224 r.tier.label()
225 );
226 Ok(())
227 }
228 #[cfg(not(feature = "seed0b-test-signing"))]
229 {
230 verify(
231 record,
232 &aienos_artifact::receipt::EmptyReceiptAnchorSet,
233 &Ed25519Verifier,
234 )
235 .map_err(|e| {
236 format!("receipt verification failed: {e:?} (no production receipt anchors before M5)")
237 })?;
238 Ok(())
239 }
240}
241
242#[cfg(feature = "seed0b-test-signing")]
243fn test_only_receipt_seed() -> [u8; 32] {
244 // RFC 8032 TEST 2 seed. TEST-ONLY SEED-0B receipt key; never a secret.
245 [
246 0x4c, 0xcd, 0x08, 0x9b, 0x28, 0xff, 0x96, 0xda, 0x9d, 0xb6, 0xc3, 0x46, 0xec, 0x11, 0x4e,
247 0x0f, 0x5b, 0x8a, 0x31, 0x9f, 0x35, 0xab, 0xa6, 0x24, 0xda, 0x8c, 0xf6, 0xed, 0x4f, 0xb8,
248 0xa6, 0xfb,
249 ]
250}
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255 use aienos_artifact::receipt::{
256 encode, receipt_nonce, ExecutionStatusCode, QualificationTier, RESULT_RECLAIMED,
257 };
258
259 fn artifact() -> Vec<u8> {
260 let manifest: crate::Manifest = serde_json::from_str(
261 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}}"#,
262 )
263 .unwrap();
264 crate::pack_bytes(&manifest, &[0xc0, 0x03, 0x5f, 0xd6], b"DATA").unwrap()
265 }
266
267 fn binding(bytes: &[u8], decision: ReceiptDecision) -> Receipt {
268 let identified = parse_and_identify(bytes).unwrap();
269 let verifier_identity = [7u8; 32];
270 let admitted = decision == ReceiptDecision::Admitted;
271 Receipt {
272 flags: 0,
273 decision,
274 tier: QualificationTier::Seed0bQemu,
275 sequence: 1,
276 nonce: receipt_nonce(&verifier_identity, 1),
277 observed_time_ns: 0,
278 execution_status: if admitted {
279 ExecutionStatusCode::Exited
280 } else {
281 ExecutionStatusCode::NotRun
282 },
283 exit_status: 0,
284 result_flags: RESULT_RECLAIMED,
285 rejection_stage: if admitted { 0 } else { 3 },
286 rejection_reason: if admitted { 0 } else { 17 },
287 syscalls: 0,
288 object_reads_ok: 0,
289 denials: 0,
290 frames_reserved: 0,
291 artifact_id: *identified.artifact_id.as_bytes(),
292 payload_digest: identified.payload_digest,
293 artifact_signer_fingerprint: *identified.artifact.signer_fingerprint,
294 policy_digest: [1; 32],
295 requested_capability_digest: requested_capability_digest(
296 identified.artifact.capability_request_bytes,
297 ),
298 granted_capability_digest: if admitted { [2; 32] } else { [0; 32] },
299 resource_envelope_digest: resource_envelope_digest(
300 identified.artifact.resource_envelope_bytes,
301 ),
302 verifier_identity,
303 machine_id_digest: [0; 32],
304 generation: 0,
305 context_id: 0,
306 }
307 }
308
309 #[test]
310 fn check_accepts_only_receipts_that_bind_the_supplied_artifact() {
311 let bytes = artifact();
312 let admitted = binding(&bytes, ReceiptDecision::Admitted);
313 assert!(check(&encode(&admitted), &bytes).is_ok());
314 let rejected = Receipt {
315 artifact_signer_fingerprint: [0; 32],
316 ..binding(&bytes, ReceiptDecision::Rejected)
317 };
318 assert!(check(&encode(&rejected), &bytes).is_ok());
319 let wrong_id = Receipt {
320 artifact_id: [9; 32],
321 ..admitted
322 };
323 assert!(check(&encode(&wrong_id), &bytes).is_err());
324 let zero_in_admitted = Receipt {
325 payload_digest: [0; 32],
326 ..admitted
327 };
328 assert!(check(&encode(&zero_in_admitted), &bytes).is_err());
329 let no_grants = Receipt {
330 granted_capability_digest: [0; 32],
331 ..admitted
332 };
333 assert!(check(&encode(&no_grants), &bytes).is_err());
334 let mut signed_bytes = encode(&admitted);
335 signed_bytes[400] = 1;
336 assert!(check(&signed_bytes, &bytes).is_err());
337 let mut other = bytes.clone();
338 let last = other.len() - 101;
339 other[last] ^= 1;
340 assert!(check(&encode(&admitted), &other).is_err());
341 }
342}