microvms_protocol/identity.rs
1// SPDX-License-Identifier: Apache-2.0
2//! The tunnel's identity proof: the seed's wire contract, the Noise pattern, and the pin.
3//!
4//! Here rather than on either side for ARCH-2's reason, and the stakes are higher than for
5//! the close codes: the host derives a public key from a seed and the daemon derives what
6//! must be the *same* public key from the *same* seed. A derivation spelled twice is a
7//! derivation that can disagree, and a disagreement surfaces as a handshake that fails with
8//! no way to tell a wrong pin from a wrong derivation.
9//!
10//! Following this crate's own rule (see the crate docs), the base64 *encoding* is not here:
11//! the seed travels as a `String` field and each side encodes with the shared `base64` crate,
12//! exactly as the exec payloads do. What is here is the part that must agree — the key names,
13//! the length, the pattern, and which seeds are refused.
14//!
15//! # What this proves, and what platform-layer mTLS cannot
16//!
17//! TLS terminates at the AWS-managed endpoint proxy and the service model has no
18//! client-certificate parameter anywhere: `CreateMicrovmAuthToken` takes
19//! `microvmIdentifier`, `allowedPorts`, and `expirationInMinutes`, and nothing else. So there
20//! is no way to present a certificate to the *VM* through the platform, and endpoint auth is
21//! the JWE alone.
22//!
23//! The JWE is scoped to one `microvmId` and the proxy enforces that scope, so an
24//! authenticated connection already binds to VM identity **as attested by AWS**. A caller who
25//! trusts the proxy needs nothing here. This module is for the caller who wants that binding
26//! without trusting the proxy, and it works because we control both endpoints: the proof
27//! terminates in the daemon rather than at the proxy.
28//!
29//! # Noise KK rather than TLS, on a measured constraint
30//!
31//! Issue #70's layer 3 called for rustls with a per-VM certificate pinned by SPKI. That is
32//! not available to the daemon, and the reason is the shipping target rather than a
33//! preference. `agentd` ships as a static `aarch64-unknown-linux-musl` binary, and **both**
34//! rustls crypto providers compile C: `aws-lc-sys` and `ring` each drive `cc-rs`, which looks
35//! for `aarch64-linux-musl-gcc`. Measured 2026-08-29 on the devbox, and `.github/workflows/ci.yml`
36//! installs `gcc-aarch64-linux-gnu` — a *gnu* cross compiler, not the musl one `cc-rs` asks
37//! for. Both providers fail the daemon's release build with `error occurred in cc-rs: failed
38//! to find tool "aarch64-linux-musl-gcc"`, so putting rustls in the daemon would trade a
39//! working shipping artifact for an identity feature.
40//!
41//! Noise KK gives the same three properties with no PKI and no C:
42//!
43//! * **Mutual authentication.** `KK` means both statics are known to both sides before the
44//! handshake, which is exactly the situation here — the host generated the seed, so it
45//! knows the daemon's key, and the daemon is told the host's key in the same payload. Each
46//! side proves possession of its own static, so the daemon learns the peer is the launching
47//! host rather than another token holder.
48//! * **Pinning by construction.** There is no name, no CA, and no chain to get wrong: the
49//! remote static key *is* the pin. A wrong pin cannot be "accepted anyway" by a verifier
50//! that forgot a check, because the key is mixed into the handshake hash and a mismatch
51//! fails decryption. That is a stronger position than a custom certificate verifier, which
52//! is code that can be written wrong.
53//! * **Confidentiality past the proxy.** ChaCha20-Poly1305 over the whole stream, so the
54//! bytes the relay carries are opaque to the endpoint that carries them.
55//!
56//! `snow` is the crate, at 26M downloads the most-used Noise implementation in the ecosystem,
57//! and it cross-compiles to the shipping target with **no C compiler** — measured, with
58//! `default-features = false`, which is load-bearing: snow's `std` feature reads `ring/std`
59//! rather than `ring?/std`, so enabling it force-enables the very C dependency the daemon
60//! cannot build.
61//!
62//! # The end of stream (#342)
63//!
64//! Every relayed chunk rides one Noise transport message, and so does the end of a stream: a
65//! side that has sent its last byte sends one more message with an empty plaintext. A relayed
66//! chunk is never empty, so the empty message is unambiguous, and it authenticates under the
67//! session's keys like any other. It also counts: each transport message decrypts only at its
68//! own position (snow's nonce is a counter), so the end of stream proves every message before
69//! it arrived, in order, with none added. That's why it carries no byte counts.
70//!
71//! The WebSocket close frame that follows it stays plaintext, since it has to reach a caller
72//! whose handshake failed. After the handshake it's a diagnosis and never the verdict: anything
73//! on the path can send a close frame or drop the connection, and only the end of stream says a
74//! stream finished rather than being cut short.
75//!
76//! Each side offers the end of stream in its handshake message's payload
77//! ([`HANDSHAKE_PAYLOAD`]), and a side holds its peer to it only when the peer offered it. The
78//! payloads are inside the handshake's encryption and its hash, so an on-path party can't strip
79//! the offer the way it could strip a query flag. An older peer sends an empty payload and no
80//! end of stream, and it reads the newer peer's end of stream as a message with nothing in it,
81//! so a release that predates the end of stream and one that sends it still work together in
82//! either order. `docs/PROTOCOL.md` has what each side does without one.
83//!
84//! # The honest limit, restated here because this is where a reader will look
85//!
86//! This proves the far end is **`agentd` in the VM the caller launched**. It does not prove
87//! the VM is uncompromised: the workload runs as uid 0 and can in principle `ptrace` the
88//! daemon and read the derived key out of its memory. Same class as the other entries on
89//! `docs/TRUST.md`'s unenforced list. It is documented rather than overclaimed.
90
91/// The Noise handshake pattern, spelled once for both sides.
92///
93/// `KK` because both static keys are known in advance, which is the whole shape of this
94/// problem: the host *generated* the daemon's key, so pre-knowledge is not an assumption to
95/// arrange but the starting condition. The alternatives are worse fits — `XX` transmits the
96/// statics during the handshake, which is what you want when the peers have never met, and it
97/// would let a responder present *any* key and be believed until a later check caught it.
98/// Under `KK` a wrong key fails the handshake itself.
99///
100/// `25519_ChaChaPoly_BLAKE2s`: all three have pure-Rust implementations in snow's default
101/// resolver, which is what keeps the daemon's build free of a C compiler. AES-GCM would pull
102/// that constraint back in on some targets for no security gain here.
103pub const NOISE_PATTERN: &str = "Noise_KK_25519_ChaChaPoly_BLAKE2s";
104
105/// The length of a seed, a static secret, and a public key. All 32 bytes, on x25519.
106///
107/// One constant rather than three, because they are the same number for the same reason: an
108/// x25519 static secret *is* 32 bytes of seed, so the derivation is a type change rather than
109/// a KDF. That is why this design needs no HKDF step and no rejection loop — the thing the
110/// platform can carry is already the thing the handshake needs.
111pub const SEED_BYTES: usize = 32;
112
113/// The payload key carrying the VM's own seed.
114///
115/// Named beside the pattern so a reader finds the whole wire contract in one file, and
116/// spelled as a constant because it appears in the host's composition and the daemon's parse
117/// — a literal in each place is a typo that fails as "the VM has no identity" rather than as
118/// a compile error.
119pub const SEED_KEY: &str = "identity_seed";
120
121/// The payload key carrying the host's public key, which the daemon pins in return.
122///
123/// The other half of mutual authentication. Without it the daemon would accept a handshake
124/// from anyone holding the agent token, and the token is a bearer credential the proxy
125/// transports on every request — so "knows the token" is a weaker claim than "holds the
126/// launching host's private key".
127pub const HOST_PUBLIC_KEY_KEY: &str = "identity_host_public_key";
128
129/// How many bytes the identity material adds to the run-hook payload.
130///
131/// Two 32-byte values, each base64'd to 44 characters, plus the JSON keys, quotes, colons,
132/// and commas. Stated as a constant because the payload shares one measured 4096-byte ceiling
133/// with the agent token and the launch environment, and a caller near that ceiling needs the
134/// number rather than a warning. `microvms-core` asserts the real composition against it.
135pub const IDENTITY_PAYLOAD_BYTES: usize = 137;
136
137/// The handshake payload's flag for the end of stream: the sender sends one, and checks the
138/// peer's when the peer offered it too.
139pub const END_OF_STREAM: u8 = 0b0000_0001;
140
141/// The payload each side writes into its handshake message: the flags it offers.
142///
143/// One byte of flags, so a later release can offer something more in another bit. The
144/// initiator's first message and the responder's reply both carry it, and both are encrypted
145/// under keys only the two pinned statics can derive, so the offer can't be forged or stripped.
146pub const HANDSHAKE_PAYLOAD: [u8; 1] = [END_OF_STREAM];
147
148/// Whether a peer's handshake payload offers the end of stream.
149///
150/// An empty payload is a peer that predates it. A flag or a byte this release doesn't know is
151/// ignored rather than refused, so a later release's payload still reads here.
152pub fn offers_end_of_stream(payload: &[u8]) -> bool {
153 payload
154 .first()
155 .is_some_and(|flags| flags & END_OF_STREAM != 0)
156}
157
158/// Whether a transport message's plaintext is the end of stream.
159///
160/// The one message with nothing in it: neither side relays an empty read, so an empty
161/// plaintext can't be a chunk of the stream.
162pub fn is_end_of_stream(plaintext: &[u8]) -> bool {
163 plaintext.is_empty()
164}
165
166/// Why some bytes are not a usable identity seed.
167///
168/// Named variants rather than a string for the same reason [`super::hook::RunHookError`] has
169/// them: this material is secret, and a message that quoted what it rejected would put key
170/// material into a log line and a response body.
171#[derive(Debug, Eq, PartialEq)]
172pub enum SeedError {
173 /// Not exactly [`SEED_BYTES`] bytes. Carries what was found, because a truncated payload
174 /// and a padded one are different bugs on the composition side.
175 WrongLength(usize),
176 /// Every byte is zero. A caller that produced it has a broken random source, and
177 /// accepting it would install an identity every other broken caller shares.
178 AllZero,
179}
180
181impl std::fmt::Display for SeedError {
182 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183 match self {
184 SeedError::WrongLength(found) => write!(
185 f,
186 "the identity seed is {found} bytes, and an x25519 static secret is exactly \
187 {SEED_BYTES}. A seed of another length is a different derivation, not a \
188 shorter one. It travels as standard base64 beside the agent token in the \
189 run-hook payload."
190 ),
191 SeedError::AllZero => f.write_str(
192 "the identity seed is all zero bytes, which every caller with a broken random \
193 source would produce identically. Refused rather than installed: a shared \
194 identity proves nothing about which VM answered.",
195 ),
196 }
197 }
198}
199
200impl std::error::Error for SeedError {}
201
202/// Checks decoded bytes into a seed, refusing the two shapes that are not one.
203///
204/// Takes bytes rather than a base64 string on purpose: this crate carries no encoder (crate
205/// docs), so each side decodes with the shared `base64` crate and hands the result here. That
206/// keeps one *validation* for both sides, which is the half that has to agree — a host that
207/// accepted a seed the daemon refuses would report a launch as identity-capable and then fail
208/// every handshake against it.
209pub fn seed_from_bytes(bytes: &[u8]) -> Result<[u8; SEED_BYTES], SeedError> {
210 if bytes.len() != SEED_BYTES {
211 return Err(SeedError::WrongLength(bytes.len()));
212 }
213 // A zero seed is a working x25519 secret and a useless identity, so it is refused here
214 // rather than at the handshake, where the failure would read as a wrong pin.
215 if bytes.iter().all(|byte| *byte == 0) {
216 return Err(SeedError::AllZero);
217 }
218 let mut seed = [0_u8; SEED_BYTES];
219 seed.copy_from_slice(bytes);
220 Ok(seed)
221}
222
223#[cfg(test)]
224mod tests {
225 use super::*;
226
227 /// The pattern is `KK` and nothing else, because the choice *is* the security property.
228 ///
229 /// `XX` would transmit the statics during the handshake, which is the pattern for peers
230 /// that have never met — and it would let a responder present any key and be believed
231 /// until a later check caught it. An edit to this string is a change of threat model, so
232 /// it is pinned rather than merely used.
233 #[test]
234 fn the_pattern_is_mutually_authenticated_and_pure_rust() {
235 assert_eq!(NOISE_PATTERN, "Noise_KK_25519_ChaChaPoly_BLAKE2s");
236 assert!(
237 NOISE_PATTERN.starts_with("Noise_KK_"),
238 "only KK pre-knows both statics, which is what makes the pin unforgeable"
239 );
240 // ChaChaPoly and BLAKE2s both have pure-Rust implementations in snow's default
241 // resolver. That is what keeps the daemon's aarch64-musl build free of a C compiler,
242 // which is the constraint that ruled rustls out in the first place.
243 assert!(NOISE_PATTERN.contains("ChaChaPoly"), "{NOISE_PATTERN}");
244 assert!(NOISE_PATTERN.contains("BLAKE2s"), "{NOISE_PATTERN}");
245 }
246
247 #[test]
248 fn a_seed_of_the_right_length_is_accepted_byte_for_byte() {
249 let mut ascending = [0_u8; SEED_BYTES];
250 for (index, byte) in ascending.iter_mut().enumerate() {
251 *byte = index as u8;
252 }
253 assert_eq!(seed_from_bytes(&ascending).expect("accepted"), ascending);
254 }
255
256 /// A seed one byte short and one byte long are both refused, and the message says which.
257 ///
258 /// The pair matters because a truncated payload and a padded one are different bugs on the
259 /// composition side, and a single "bad seed" message would send a reader to the wrong one.
260 #[test]
261 fn a_seed_of_the_wrong_length_reports_the_length_it_found() {
262 assert_eq!(
263 seed_from_bytes(&[7_u8; 31]),
264 Err(SeedError::WrongLength(31))
265 );
266 assert_eq!(
267 seed_from_bytes(&[7_u8; 33]),
268 Err(SeedError::WrongLength(33))
269 );
270 assert_eq!(seed_from_bytes(&[]), Err(SeedError::WrongLength(0)));
271 assert!(
272 SeedError::WrongLength(31).to_string().contains("31"),
273 "the found length is the diagnosis"
274 );
275 }
276
277 /// A zero seed decodes fine and is refused anyway, because it is a shared identity.
278 #[test]
279 fn an_all_zero_seed_is_refused() {
280 assert_eq!(
281 seed_from_bytes(&[0_u8; SEED_BYTES]),
282 Err(SeedError::AllZero)
283 );
284 // One non-zero byte is enough to be a real seed: the refusal is about a broken RNG
285 // producing an all-zero buffer, not about weak-looking keys in general.
286 let mut nearly = [0_u8; SEED_BYTES];
287 nearly[SEED_BYTES - 1] = 1;
288 assert!(seed_from_bytes(&nearly).is_ok());
289 }
290
291 /// No refusal may carry the material it rejected.
292 ///
293 /// The payload this validates sits beside the agent token, and `docs/TRUST.md` promises
294 /// no secret reaches a log line or a response body.
295 #[test]
296 fn a_refusal_never_quotes_the_bytes_it_rejected() {
297 let secret = [0xAB_u8; 31];
298 let message = seed_from_bytes(&secret).expect_err("refused").to_string();
299 assert!(!message.contains("171"), "{message}");
300 assert!(!message.contains("ab"), "{message}");
301 assert!(!message.contains("AB"), "{message}");
302 }
303
304 /// The two payload keys are distinct, and neither collides with the payload's other keys.
305 ///
306 /// A collision would make one value overwrite the other in the payload object, and the
307 /// symptom would be a failed handshake rather than anything naming a key.
308 #[test]
309 fn the_payload_keys_are_distinct_from_each_other_and_from_the_token() {
310 assert_ne!(SEED_KEY, HOST_PUBLIC_KEY_KEY);
311 for key in [SEED_KEY, HOST_PUBLIC_KEY_KEY] {
312 assert_ne!(key, "agent_token");
313 assert_ne!(key, "env");
314 }
315 }
316
317 /// The offer reads from the flags byte alone, and an older peer's empty payload offers
318 /// nothing.
319 ///
320 /// The empty payload is the skew case: every release before #342 wrote one, and reading it
321 /// as an offer would hold that peer to an end of stream it never sends, failing every
322 /// tunnel to an older image. A later release's extra flag or byte must not turn the offer
323 /// off either.
324 #[test]
325 fn the_end_of_stream_is_offered_by_its_flag_and_not_by_an_empty_payload() {
326 assert!(offers_end_of_stream(&HANDSHAKE_PAYLOAD));
327 assert!(!offers_end_of_stream(&[]));
328 assert!(!offers_end_of_stream(&[0b0000_0010]));
329 assert!(offers_end_of_stream(&[END_OF_STREAM | 0b1000_0000, 0xff]));
330 assert!(is_end_of_stream(&[]));
331 assert!(!is_end_of_stream(&[0]));
332 }
333
334 /// The identity payload budget is what a caller near the ceiling needs, so it is asserted
335 /// against the real composition rather than trusted as a comment.
336 ///
337 /// The number is checked here against its two 44-character base64 values and JSON framing;
338 /// `microvms-core` asserts the same constant against the payload it actually builds. Two
339 /// independent checks of one number, because the ceiling it is spent against is measured
340 /// and hard — 4096 bytes, where 4097 fails.
341 #[test]
342 fn the_identity_payload_budget_matches_its_parts() {
343 // Two keys, two quoted 44-char base64 values, two colons, two commas, four quote pairs.
344 let value_chars = 44 * 2;
345 let key_chars = SEED_KEY.len() + HOST_PUBLIC_KEY_KEY.len();
346 // Per pair: quotes around the key (2), a colon (1), quotes around the value (2), and a
347 // leading comma (1) — six characters of framing each.
348 let framing = 6 * 2;
349 assert_eq!(
350 IDENTITY_PAYLOAD_BYTES,
351 value_chars + key_chars + framing,
352 "the stated budget must equal the bytes the two halves really cost"
353 );
354 }
355}