device_virtio_tpm/
swtpm_backend.rs

1// Copyright 2026 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::io::Read;
6use std::io::Write;
7use std::os::unix::net::UnixStream;
8use std::path::Path;
9use std::time::Duration;
10
11use anyhow::Context;
12use anyhow::Result;
13use base::error;
14use base::AsRawDescriptor;
15use base::RawDescriptor;
16
17use crate::TpmBackend;
18use crate::TPM_BUFSIZE;
19use crate::TPM_RC_FAILURE_RESPONSE;
20
21// Bound every socket operation so a stalled swtpm cannot hang the device worker, and
22// with it Tpm::reset() and VM shutdown.  Matches the timeout VtpmProxy uses for D-Bus.
23const SWTPM_IO_TIMEOUT: Duration = Duration::from_secs(300);
24
25/// Backend that communicates with swtpm via Unix socket
26pub struct SwtpmBackend {
27    socket: UnixStream,
28    response_buffer: Vec<u8>,
29    broken: bool,
30}
31
32impl SwtpmBackend {
33    pub fn new<P: AsRef<Path>>(socket_path: P) -> Result<Self> {
34        let socket = UnixStream::connect(socket_path.as_ref()).with_context(|| {
35            format!(
36                "failed to connect to swtpm socket at {}",
37                socket_path.as_ref().display()
38            )
39        })?;
40
41        socket
42            .set_read_timeout(Some(SWTPM_IO_TIMEOUT))
43            .context("failed to set swtpm socket read timeout")?;
44        socket
45            .set_write_timeout(Some(SWTPM_IO_TIMEOUT))
46            .context("failed to set swtpm socket write timeout")?;
47
48        Ok(Self {
49            socket,
50            response_buffer: vec![0u8; TPM_BUFSIZE],
51            broken: false,
52        })
53    }
54}
55
56impl TpmBackend for SwtpmBackend {
57    fn execute_command<'a>(&'a mut self, command: &[u8]) -> &'a [u8] {
58        // A failed socket operation can leave a partial command or response in the
59        // stream, so its framing is no longer trustworthy: refuse the socket from then
60        // on rather than read one response as another.
61        if self.broken {
62            return TPM_RC_FAILURE_RESPONSE;
63        }
64
65        // swtpm takes its commands off a stream socket, so a command whose header
66        // disagrees with the buffer it arrived in desynchronises that stream: swtpm waits
67        // for bytes that never arrive, or the surplus is read as the next command.
68        if command.len() < 10 {
69            error!("swtpm command too short: {} bytes", command.len());
70            return TPM_RC_FAILURE_RESPONSE;
71        }
72        let command_size =
73            u32::from_be_bytes([command[2], command[3], command[4], command[5]]) as usize;
74        if command_size != command.len() {
75            error!(
76                "swtpm command length mismatch: header says {}, buffer is {}",
77                command_size,
78                command.len()
79            );
80            return TPM_RC_FAILURE_RESPONSE;
81        }
82
83        if let Err(e) = self.socket.write_all(command) {
84            error!("swtpm write error: {}", e);
85            self.broken = true;
86            return TPM_RC_FAILURE_RESPONSE;
87        }
88
89        let mut header = [0u8; 10];
90        if let Err(e) = self.socket.read_exact(&mut header) {
91            error!("swtpm read header error: {}", e);
92            self.broken = true;
93            return TPM_RC_FAILURE_RESPONSE;
94        }
95
96        // The length comes off the socket and is not trusted: a corrupt value would either
97        // ask for far more than the device can ever return, or claim to be shorter than
98        // the header just read.
99        let response_size =
100            u32::from_be_bytes([header[2], header[3], header[4], header[5]]) as usize;
101        if !(10..=TPM_BUFSIZE).contains(&response_size) {
102            error!("swtpm invalid response size: {}", response_size);
103            self.broken = true;
104            return TPM_RC_FAILURE_RESPONSE;
105        }
106
107        self.response_buffer[..10].copy_from_slice(&header);
108
109        if response_size > 10 {
110            if let Err(e) = self
111                .socket
112                .read_exact(&mut self.response_buffer[10..response_size])
113            {
114                error!("swtpm read body error: {}", e);
115                self.broken = true;
116                return TPM_RC_FAILURE_RESPONSE;
117            }
118        }
119
120        &self.response_buffer[..response_size]
121    }
122
123    fn keep_rds(&self) -> Vec<RawDescriptor> {
124        vec![self.socket.as_raw_descriptor()]
125    }
126}