Skip to main content

sev_snp/
lib.rs

1//! Safe Rust bindings for the Linux AMD SEV-SNP guest API.
2//!
3//! Inside an SEV-SNP virtual machine, the AMD secure processor will sign
4//! statements about the VM and derive keys that never leave the chip. This
5//! crate exposes everything the Linux guest interface offers, over both kernel
6//! transports, with no `unsafe` required of the caller.
7//!
8//! # Getting started
9//!
10//! ```no_run
11//! use sev_snp::Firmware;
12//!
13//! let fw = Firmware::open()?;
14//! let report = fw.report(&[0u8; 64])?;
15//!
16//! println!("measurement: {:x?}", report.measurement());
17//! println!("running on {}", report.product().unwrap());
18//! # Ok::<_, sev_snp::Error>(())
19//! ```
20//!
21//! # What the guest can ask for
22//!
23//! - **[Attestation reports](AttestationReport)** — a signed statement covering
24//!   the launch measurement, the guest policy, the platform's firmware versions
25//!   and 64 bytes of caller-supplied data. Fetch one with [`Firmware::report`].
26//! - **[Endorsement certificates](CertTable)** — the chain that verifies the
27//!   report's signature, when the host provisioned one. See
28//!   [`Firmware::extended_report`].
29#![cfg_attr(
30    feature = "sev-guest",
31    doc = "- **[Derived keys](DerivedKey)** — reproducible key material bound to any"
32)]
33#![cfg_attr(
34    feature = "sev-guest",
35    doc = "  combination of the chip, the firmware version, and the guest image. See"
36)]
37#![cfg_attr(
38    feature = "sev-guest",
39    doc = "  [`Firmware::derive_key`] and the [`key`] module."
40)]
41//! - **[Capability detection](detect)** — what the processor supports, and
42//!   whether this process is in fact running inside an SNP guest.
43//!
44//! # Portability across Zen 3, Zen 4 and Zen 5
45//!
46//! The guest request protocol is identical on every SEV-SNP part, so the calls
47//! in this crate need no per-generation branching. Two things do vary, and both
48//! are handled without asking the caller which machine they are on:
49//!
50//! - **Report version.** Reports are always [`AttestationReport::SIZE`] bytes;
51//!   newer revisions only claim space older ones reserved. Fields introduced
52//!   later — [`cpuid_fms`](AttestationReport::cpuid_fms) in version 3,
53//!   [`launch_mit_vector`](AttestationReport::launch_mit_vector) in version 5 —
54//!   return `Option`. Report version tracks *firmware* level, not silicon, so a
55//!   Zen 3 machine on current firmware emits version 5 reports.
56//! - **TCB version layout.** [`TcbVersion`] means different things on different
57//!   processors: Zen 5 inserts an FMC security version number that Zen 3 and
58//!   Zen 4 do not have. The raw value is always preserved, and
59//!   [`TcbVersion::decode`] splits it correctly for a given [`Product`] —
60//!   which reports from version 3 onwards carry themselves.
61//!
62//! Bitfields such as [`GuestPolicy`] and [`PlatformInfo`] name the bits this
63//! crate knows and expose the rest through `unknown_bits`, so a report from
64//! firmware newer than this crate parses rather than fails.
65//!
66//! # Transports and features
67//!
68//! Linux exposes guest requests through both `/dev/sev-guest` (5.19 and later)
69//! and configfs-TSM (6.7 and later). [`Firmware::open`] uses whichever are
70//! present, preferring configfs for reports because it can detect a concurrent
71//! writer, and requiring `/dev/sev-guest` for key derivation because configfs
72//! does not implement it. See the [`backend`] module for the full comparison.
73//!
74//! Each transport is a cargo feature, both on by default. Turning one off
75//! compiles it out entirely, along with anything only it needed:
76//!
77//! - `configfs` — the configfs-TSM transport. Reports only.
78//! - `sev-guest` — the `/dev/sev-guest` transport. Adds key derivation and
79//!   firmware status codes, and pulls in `libc`.
80//!
81//! Selecting neither is a compile error. Selecting only `configfs` leaves a
82//! crate with no dependencies at all, compiled under `forbid(unsafe_code)` —
83//! useful for a verifier or a report-only agent that wants no `unsafe`
84//! anywhere in what it builds.
85//!
86//! Anything a build cannot do is absent rather than failing at run time:
87//! without `sev-guest` there is no `Firmware::derive_key`, no `key` module and
88//! no `Transport::Ioctl`, so code that needs them fails to compile instead of
89//! reaching production and returning an error. Write against both feature sets
90//! the way `examples/attest.rs` does, with a `#[cfg]` around the parts that
91//! need a particular transport.
92//!
93//! # Trust boundary
94//!
95//! A report is only evidence once its signature has been checked against AMD's
96//! certificate chain, and the freshness of
97//! [`report_data`](AttestationReport::report_data) confirmed. This crate
98//! obtains and parses reports; it deliberately performs no cryptographic
99//! verification and fetches nothing from the network, so that the verifying
100//! party can be a different machine running code of its own choosing. Treat
101//! everything a report says as unverified until you have done that.
102//!
103//! What this crate does check, because a guest can do it without any
104//! cryptography and a caller who skips it has no way to notice:
105//!
106//! - The response answers *this* request. `REPORT_DATA` and the privilege
107//!   level are echoed by the firmware, so both are compared against what was
108//!   asked for and a mismatch is [`Error::Mismatch`], never a returned report.
109//! - The interface is really SEV-SNP. configfs-TSM is shared with TDX and
110//!   others, so the provider name is checked once at open; anything else is
111//!   [`Error::WrongProvider`] rather than a foreign quote parsed as a report.
112//! - The response is shaped like a report. The version is bounded above as
113//!   well as below, and a host-supplied certificate blob is bounded in size
114//!   and entry count before any of it is decoded.
115
116#![cfg_attr(docsrs, feature(doc_cfg))]
117#![cfg_attr(not(feature = "sev-guest"), forbid(unsafe_code))]
118
119#[cfg(not(any(feature = "configfs", feature = "sev-guest")))]
120compile_error!(
121    "sev-snp needs at least one backend: enable the `configfs` feature, the \
122     `sev-guest` feature, or both (both are on by default)."
123);
124
125#[cfg(all(doctest, feature = "sev-guest"))]
126#[doc = include_str!("../README.md")]
127struct ReadmeDoctests;
128
129pub mod backend;
130pub mod certs;
131pub mod detect;
132pub mod error;
133#[cfg(feature = "sev-guest")]
134pub mod key;
135pub mod policy;
136pub mod report;
137pub mod tcb;
138
139#[doc(inline)]
140pub use backend::{GuestBackend, ReportRequest, Transport};
141#[doc(inline)]
142pub use certs::{CertKind, CertTable, Certificate, ExtendedReport};
143#[doc(inline)]
144pub use error::{Error, FirmwareError, ParseError, Result, VmmError};
145#[cfg(feature = "sev-guest")]
146#[doc(inline)]
147pub use key::{DerivedKey, KeyFields, KeyRequest, RootKey};
148#[doc(inline)]
149pub use policy::{GuestPolicy, PlatformInfo, SignatureAlgo, SignerInfo, SigningKey};
150#[doc(inline)]
151pub use report::{AttestationReport, EcdsaP384Signature, FirmwareVersion};
152#[doc(inline)]
153pub use tcb::{Fms, Product, TcbLayout, TcbParts, TcbVersion};
154
155#[cfg(feature = "configfs")]
156use backend::configfs::ConfigFs;
157#[cfg(feature = "sev-guest")]
158use backend::ioctl::SevGuest;
159
160/// Backoff before each retry of a transient failure.
161///
162/// One entry per retry, so a request is attempted `len() + 1` times in all.
163/// The sum is the entire wall-clock cost of exhausting a request, and it is
164/// deliberately a fraction of a second: a call that can be made to block for
165/// seconds is a call that can be used to pin a caller's threads, and on the
166/// ioctl transport every attempt also consumes a VMPCK sequence number that
167/// the guest can never get back.
168const RETRY_BACKOFF: [std::time::Duration; 2] = [
169    std::time::Duration::from_millis(20),
170    std::time::Duration::from_millis(80),
171];
172
173/// Whether an error is one the kernel expects the guest to try again on.
174///
175/// [`Error::Raced`] is transient by definition, and the hypervisor raises
176/// [`VmmError::Busy`] — surfacing as `EBUSY` or `EAGAIN` through configfs —
177/// while it services another guest's request. Nothing else is retried: a
178/// [`Error::Mismatch`] in particular is a signal that something is wrong, not
179/// an invitation to ask again.
180fn is_transient(error: &Error) -> bool {
181    use std::io::ErrorKind::{Interrupted, ResourceBusy, WouldBlock};
182    match error {
183        Error::Raced | Error::Vmm(VmmError::Busy) => true,
184        Error::Io(e) => matches!(e.kind(), ResourceBusy | WouldBlock | Interrupted),
185        _ => false,
186    }
187}
188
189/// Runs `attempt`, retrying transient failures on a fixed, bounded schedule.
190fn retrying<T>(mut attempt: impl FnMut() -> Result<T>) -> Result<T> {
191    let mut backoff = RETRY_BACKOFF.iter();
192    loop {
193        match attempt() {
194            Err(error) if is_transient(&error) => match backoff.next() {
195                Some(delay) => std::thread::sleep(*delay),
196                None => return Err(error),
197            },
198            settled => return settled,
199        }
200    }
201}
202
203/// A handle to the SEV-SNP guest firmware.
204///
205/// Opens whichever kernel transports are compiled in and available, and routes
206/// each request to one that implements it. Cheap to keep around and safe to
207/// share between threads; the kernel serialises guest requests internally.
208#[derive(Debug)]
209pub struct Firmware {
210    /// Which backend serves reports. Fixed at open time, and always backed by
211    /// a live handle, so no request has to guess.
212    transport: Transport,
213    #[cfg(feature = "configfs")]
214    configfs: Option<ConfigFs>,
215    #[cfg(feature = "sev-guest")]
216    ioctl: Option<SevGuest>,
217}
218
219impl Firmware {
220    /// Opens every guest transport that is compiled in and available.
221    ///
222    /// Opening `/dev/sev-guest` requires root; if that fails but configfs
223    /// works, this still succeeds and only key derivation is unavailable.
224    ///
225    /// # Errors
226    ///
227    /// Returns [`Error::NoBackend`] if no transport could be opened, which
228    /// normally means this is not an SEV-SNP guest.
229    pub fn open() -> Result<Self> {
230        #[cfg(feature = "configfs")]
231        let configfs = ConfigFs::open().ok();
232        #[cfg(feature = "sev-guest")]
233        let ioctl = SevGuest::open().ok();
234
235        // configfs is preferred for reports: it is the only transport that can
236        // tell us whether another process overwrote our request before we read
237        // the answer.
238        #[cfg(feature = "configfs")]
239        let transport = if configfs.is_some() {
240            Some(Transport::ConfigFs)
241        } else {
242            None
243        };
244        #[cfg(not(feature = "configfs"))]
245        let transport = None;
246
247        #[cfg(feature = "sev-guest")]
248        let transport = transport.or_else(|| ioctl.as_ref().map(|_| Transport::Ioctl));
249
250        Ok(Self {
251            transport: transport.ok_or(Error::NoBackend)?,
252            #[cfg(feature = "configfs")]
253            configfs,
254            #[cfg(feature = "sev-guest")]
255            ioctl,
256        })
257    }
258
259    /// Opens exactly one transport, failing if it is unavailable.
260    ///
261    /// Use this when a specific interface is required — for instance to insist
262    /// on [`Transport::Ioctl`] so that firmware status codes survive, rather
263    /// than being collapsed into an `errno` by configfs.
264    ///
265    /// A transport whose feature is off has no [`Transport`] variant, so
266    /// asking for one this build cannot speak does not compile.
267    ///
268    /// # Errors
269    ///
270    /// Returns [`Error::NoBackend`] or [`Error::Io`] if the transport is absent
271    /// from this system or cannot be opened.
272    ///
273    #[cfg_attr(
274        not(feature = "sev-guest"),
275        doc = "[`Transport::Ioctl`]: crate#transports-and-features"
276    )]
277    pub fn open_with(transport: Transport) -> Result<Self> {
278        match transport {
279            #[cfg(feature = "configfs")]
280            Transport::ConfigFs => Ok(Self {
281                transport,
282                configfs: Some(ConfigFs::open()?),
283                #[cfg(feature = "sev-guest")]
284                ioctl: None,
285            }),
286            #[cfg(feature = "sev-guest")]
287            Transport::Ioctl => Ok(Self {
288                transport,
289                #[cfg(feature = "configfs")]
290                configfs: None,
291                ioctl: Some(SevGuest::open()?),
292            }),
293        }
294    }
295
296    /// Fetches reports through one configfs-TSM entry handed over by a more
297    /// privileged process, for a caller that may not create its own.
298    ///
299    /// See [`ConfigFs::open_entry`]. The handle never derives keys, whatever
300    /// this process could open.
301    ///
302    /// ```no_run
303    /// let fw = sev_snp::Firmware::open_entry("/sys/kernel/config/tsm/report/app")?;
304    /// let report = fw.report(&[0u8; 64])?;
305    /// # Ok::<_, sev_snp::Error>(())
306    /// ```
307    ///
308    /// # Errors
309    ///
310    /// Returns [`Error::NoBackend`] if `entry` is not a directory,
311    /// [`Error::WrongProvider`] if it belongs to another architecture, or
312    /// [`Error::Io`] if its provider cannot be read.
313    #[cfg(feature = "configfs")]
314    pub fn open_entry(entry: impl Into<std::path::PathBuf>) -> Result<Self> {
315        Ok(Self {
316            transport: Transport::ConfigFs,
317            configfs: Some(ConfigFs::open_entry(entry)?),
318            #[cfg(feature = "sev-guest")]
319            ioctl: None,
320        })
321    }
322
323    /// Which transport reports will be fetched from.
324    #[must_use]
325    pub const fn transport(&self) -> Transport {
326        self.transport
327    }
328
329    /// Whether key derivation is available on this handle.
330    ///
331    /// False when the device could not be opened, which usually means the
332    /// process lacks the privileges for `/dev/sev-guest`.
333    #[cfg(feature = "sev-guest")]
334    #[must_use]
335    pub const fn can_derive_keys(&self) -> bool {
336        self.ioctl.is_some()
337    }
338
339    /// Requests a signed attestation report over the given 64 bytes.
340    ///
341    /// The bytes land in [`AttestationReport::report_data`] and are what binds
342    /// the report to a challenge: put a verifier-supplied nonce there, or a
343    /// hash of a public key you want the report to endorse. All-zero data
344    /// produces a valid but replayable report.
345    ///
346    /// The returned report is guaranteed to carry exactly these bytes: a
347    /// response whose `REPORT_DATA` differs is rejected as
348    /// [`Error::Mismatch`] rather than returned.
349    ///
350    /// # Errors
351    ///
352    /// See [`GuestBackend::report`].
353    pub fn report(&self, report_data: &[u8; 64]) -> Result<AttestationReport> {
354        self.report_with(&ReportRequest::from(report_data))
355    }
356
357    /// Requests a report with full control over the request.
358    ///
359    /// Transient failures — a busy hypervisor, a detected race — are retried
360    /// twice, with a total backoff well under a second, before the error is
361    /// returned. Call [`GuestBackend::report`] on a backend directly to issue
362    /// exactly one request with no retry.
363    ///
364    /// # Errors
365    ///
366    /// See [`GuestBackend::report`].
367    pub fn report_with(&self, request: &ReportRequest) -> Result<AttestationReport> {
368        retrying(|| self.report_backend()?.report(request))
369    }
370
371    /// Requests a report together with the host-provisioned certificate chain.
372    ///
373    /// The chain is frequently empty: hosts are not required to provision one,
374    /// in which case it must be fetched from AMD's Key Distribution Service
375    /// instead. [`CertTable::is_empty`] tells you which case you are in.
376    ///
377    /// # Errors
378    ///
379    /// See [`GuestBackend::extended_report`].
380    pub fn extended_report(&self, report_data: &[u8; 64]) -> Result<ExtendedReport> {
381        self.extended_report_with(&ReportRequest::from(report_data))
382    }
383
384    /// Requests an extended report with full control over the request.
385    ///
386    /// Retried on transient failures exactly as [`report_with`](Self::report_with).
387    ///
388    /// # Errors
389    ///
390    /// See [`GuestBackend::extended_report`].
391    pub fn extended_report_with(&self, request: &ReportRequest) -> Result<ExtendedReport> {
392        retrying(|| self.report_backend()?.extended_report(request))
393    }
394
395    /// Derives a key from a secret held inside the processor.
396    ///
397    /// Requires the `/dev/sev-guest` transport; see
398    /// [`can_derive_keys`](Self::can_derive_keys). The [`key`] module explains
399    /// what the request can bind the key to.
400    ///
401    /// # Errors
402    ///
403    /// See [`GuestBackend::derive_key`].
404    #[cfg(feature = "sev-guest")]
405    pub fn derive_key(&self, request: &KeyRequest) -> Result<DerivedKey> {
406        let ioctl = self.ioctl.as_ref().ok_or(Error::Unsupported(
407            "key derivation needs /dev/sev-guest, which is not open",
408        ))?;
409        ioctl.derive_key(request)
410    }
411
412    /// The live backend serving reports, selected once at open time.
413    fn report_backend(&self) -> Result<&dyn GuestBackend> {
414        match self.transport {
415            #[cfg(feature = "configfs")]
416            Transport::ConfigFs => self
417                .configfs
418                .as_ref()
419                .map(|backend| -> &dyn GuestBackend { backend })
420                .ok_or(Error::NoBackend),
421            #[cfg(feature = "sev-guest")]
422            Transport::Ioctl => self
423                .ioctl
424                .as_ref()
425                .map(|backend| -> &dyn GuestBackend { backend })
426                .ok_or(Error::NoBackend),
427        }
428    }
429}
430
431// Small total helpers for reading fixed-width fields out of firmware buffers.
432// They live at the crate root, private, so every module can reach them without
433// a visibility qualifier: nothing here is part of the public API. All are free
434// of panicking operations — no indexing, no unchecked arithmetic, no `unwrap`.
435
436/// Narrows a value that the caller has already masked to eight bits or fewer.
437///
438/// `u8::try_from` is not callable from a `const fn`, and taking the low byte of
439/// an already-masked value is exact.
440const fn low_byte(masked: u32) -> u8 {
441    let [byte, _, _, _] = masked.to_le_bytes();
442    byte
443}
444
445/// Widens a byte to `u32` without an `as` cast, callable from a `const fn`.
446const fn widen(byte: u8) -> u32 {
447    u32::from_le_bytes([byte, 0, 0, 0])
448}
449
450/// Copies `N` bytes starting at `offset`, or `None` if the buffer is too short.
451fn bytes_at<const N: usize>(buf: &[u8], offset: usize) -> Option<[u8; N]> {
452    buf.get(offset..)?.first_chunk::<N>().copied()
453}
454
455/// Reads a little-endian `u32` at `offset`.
456fn u32_at(buf: &[u8], offset: usize) -> Option<u32> {
457    bytes_at::<4>(buf, offset).map(u32::from_le_bytes)
458}