1#![cfg(any(target_os = "android", target_os = "linux"))]
6
7use std::collections::BTreeMap;
8use std::io;
9use std::io::Read;
10use std::io::Write;
11use std::ops::BitOrAssign;
12use std::path::Path;
13use std::path::PathBuf;
14
15use anyhow::anyhow;
16use anyhow::Context;
17use base::error;
18use base::Event;
19use base::EventToken;
20use base::RawDescriptor;
21use base::WaitContext;
22use base::WorkerThread;
23use devices::virtio;
24use devices::virtio::DescriptorChain;
25use devices::virtio::DeviceType;
26use devices::virtio::Interrupt;
27use devices::virtio::Queue;
28use devices::virtio::VirtioDevice;
29use devices::VirtioDeviceArgs;
30use devices::VirtioDeviceModule;
31use jail::JailConfig;
32#[cfg(any(target_os = "android", target_os = "linux"))]
33use minijail::Minijail;
34use remain::sorted;
35use thiserror::Error;
36use vm_memory::GuestMemory;
37
38mod swtpm_backend;
39mod vtpm_proxy;
40pub use self::swtpm_backend::SwtpmBackend;
41pub use self::vtpm_proxy::VtpmProxy;
42
43const QUEUE_SIZE: u16 = 2;
47const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE];
48
49const TPM_BUFSIZE: usize = 4096;
53
54pub(crate) const TPM_RC_FAILURE_RESPONSE: &[u8] = &[
57 0x80, 0x01, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x01, 0x01, ];
61
62struct Worker {
63 queue: Queue,
64 backend: Box<dyn TpmBackend>,
65}
66
67pub trait TpmBackend: Send {
68 fn execute_command<'a>(&'a mut self, command: &[u8]) -> &'a [u8];
69
70 fn keep_rds(&self) -> Vec<RawDescriptor> {
72 Vec::new()
73 }
74}
75
76impl Worker {
77 fn perform_work(&mut self, desc: &mut DescriptorChain) -> Result<u32> {
78 let available_bytes = desc.reader.available_bytes();
79 if available_bytes > TPM_BUFSIZE {
80 return Err(Error::CommandTooLong {
81 size: available_bytes,
82 });
83 }
84
85 let mut command = vec![0u8; available_bytes];
86 desc.reader.read_exact(&mut command).map_err(Error::Read)?;
87
88 let response = self.backend.execute_command(&command);
89
90 if response.len() > TPM_BUFSIZE {
91 return Err(Error::ResponseTooLong {
92 size: response.len(),
93 });
94 }
95
96 let writer_len = desc.writer.available_bytes();
97 if response.len() > writer_len {
98 return Err(Error::BufferTooSmall {
99 size: writer_len,
100 required: response.len(),
101 });
102 }
103
104 desc.writer.write_all(response).map_err(Error::Write)?;
105
106 Ok(desc.writer.bytes_written() as u32)
107 }
108
109 fn process_queue(&mut self) -> NeedsInterrupt {
110 let mut needs_interrupt = NeedsInterrupt::No;
111 while let Some(mut avail_desc) = self.queue.pop() {
112 let len = match self.perform_work(&mut avail_desc) {
113 Ok(len) => len,
114 Err(err) => {
115 error!("{}", err);
116 0
117 }
118 };
119
120 self.queue.add_used_with_bytes_written(avail_desc, len);
121 needs_interrupt = NeedsInterrupt::Yes;
122 }
123
124 needs_interrupt
125 }
126
127 fn run(&mut self, kill_evt: Event) -> anyhow::Result<()> {
128 #[derive(EventToken, Debug)]
129 enum Token {
130 QueueAvailable,
132 Kill,
134 }
135
136 let wait_ctx = WaitContext::build_with(&[
137 (self.queue.event(), Token::QueueAvailable),
138 (&kill_evt, Token::Kill),
139 ])
140 .context("WaitContext::build_with")?;
141
142 loop {
143 let events = wait_ctx.wait().context("WaitContext::wait")?;
144 let mut needs_interrupt = NeedsInterrupt::No;
145 for event in events.iter().filter(|e| e.is_readable) {
146 match event.token {
147 Token::QueueAvailable => {
148 self.queue.event().wait().context("Event::wait")?;
149 needs_interrupt |= self.process_queue();
150 }
151 Token::Kill => return Ok(()),
152 }
153 }
154 if needs_interrupt == NeedsInterrupt::Yes {
155 self.queue.trigger_interrupt();
156 }
157 }
158 }
159}
160
161pub struct Tpm {
163 backend: Option<Box<dyn TpmBackend>>,
164 worker_thread: Option<WorkerThread<Box<dyn TpmBackend>>>,
165 features: u64,
166}
167
168impl Tpm {
169 pub fn new(backend: Box<dyn TpmBackend>, base_features: u64) -> Tpm {
170 Tpm {
171 backend: Some(backend),
172 worker_thread: None,
173 features: base_features,
174 }
175 }
176}
177
178impl VirtioDevice for Tpm {
179 fn keep_rds(&self) -> Vec<RawDescriptor> {
180 self.backend
181 .as_ref()
182 .map(|b| b.keep_rds())
183 .unwrap_or_default()
184 }
185
186 fn device_type(&self) -> DeviceType {
187 DeviceType::Tpm
188 }
189
190 fn queue_max_sizes(&self) -> &[u16] {
191 QUEUE_SIZES
192 }
193
194 fn features(&self) -> u64 {
195 self.features
196 }
197
198 fn reset(&mut self) -> anyhow::Result<()> {
199 if let Some(worker_thread) = self.worker_thread.take() {
200 self.backend = Some(worker_thread.stop());
201 }
202 Ok(())
203 }
204
205 fn activate(
206 &mut self,
207 _mem: GuestMemory,
208 _interrupt: Interrupt,
209 mut queues: BTreeMap<usize, Queue>,
210 ) -> anyhow::Result<()> {
211 if queues.len() != 1 {
212 return Err(anyhow!("expected 1 queue, got {}", queues.len()));
213 }
214 let queue = queues.pop_first().unwrap().1;
215
216 let backend = self.backend.take().context("no backend in vtpm")?;
217
218 let mut worker = Worker { queue, backend };
219
220 self.worker_thread = Some(WorkerThread::start("v_tpm", |kill_evt| {
221 if let Err(e) = worker.run(kill_evt) {
222 error!("virtio-tpm worker failed: {:#}", e);
223 }
224 worker.backend
225 }));
226
227 Ok(())
228 }
229}
230
231#[derive(PartialEq, Eq)]
232enum NeedsInterrupt {
233 Yes,
234 No,
235}
236
237impl BitOrAssign for NeedsInterrupt {
238 fn bitor_assign(&mut self, rhs: NeedsInterrupt) {
239 if rhs == NeedsInterrupt::Yes {
240 *self = NeedsInterrupt::Yes;
241 }
242 }
243}
244
245type Result<T> = std::result::Result<T, Error>;
246
247#[sorted]
248#[derive(Error, Debug)]
249enum Error {
250 #[error("vtpm response buffer is too small: {size} < {required} bytes")]
251 BufferTooSmall { size: usize, required: usize },
252 #[error("vtpm command is too long: {size} > {} bytes", TPM_BUFSIZE)]
253 CommandTooLong { size: usize },
254 #[error("vtpm failed to read from guest memory: {0}")]
255 Read(io::Error),
256 #[error(
257 "vtpm simulator generated a response that is unexpectedly long: {size} > {} bytes",
258 TPM_BUFSIZE
259 )]
260 ResponseTooLong { size: usize },
261 #[error("vtpm failed to write to guest memory: {0}")]
262 Write(io::Error),
263}
264
265#[derive(serde::Serialize, serde::Deserialize, Default)]
267pub enum TpmBackendConfig {
268 #[default]
270 VtpmProxy,
271 SwtpmSocket(PathBuf),
273}
274
275#[derive(serde::Serialize, serde::Deserialize, Default)]
277pub struct VirtioTpmModule {
278 backend: TpmBackendConfig,
279}
280
281impl VirtioTpmModule {
282 pub fn new() -> Self {
284 Self::default()
285 }
286
287 pub fn with_swtpm_socket(socket_path: PathBuf) -> Self {
289 Self {
290 backend: TpmBackendConfig::SwtpmSocket(socket_path),
291 }
292 }
293}
294
295impl VirtioDeviceModule for VirtioTpmModule {
296 fn sort_name(&self) -> &'static str {
297 "vtpm"
298 }
299
300 fn create(&self, args: &mut VirtioDeviceArgs<'_>) -> anyhow::Result<Box<dyn VirtioDevice>> {
301 let backend: Box<dyn TpmBackend> = match &self.backend {
302 TpmBackendConfig::VtpmProxy => Box::new(VtpmProxy::new()),
303 TpmBackendConfig::SwtpmSocket(path) => Box::new(SwtpmBackend::new(path)?),
304 };
305 let dev = Tpm::new(backend, virtio::base_features(args.protection_type));
306 Ok(Box::new(dev))
307 }
308
309 #[cfg(any(target_os = "android", target_os = "linux"))]
310 fn create_jail(&self, jail_config: Option<&JailConfig>) -> anyhow::Result<Option<Minijail>> {
311 let Some(jail_config) = jail_config else {
312 return Ok(None);
313 };
314 let mut config = jail::SandboxConfig::new(jail_config, "vtpm_proxy_device");
315 config.bind_mounts = true;
316 let mut jail = jail::create_sandbox_minijail(
317 &jail_config.pivot_root,
318 jail::MAX_OPEN_FILES_DEFAULT,
319 &config,
320 )?;
321 match &self.backend {
322 TpmBackendConfig::VtpmProxy => {
323 let system_bus_socket_path = Path::new("/run/dbus/system_bus_socket");
324 jail.mount_bind(system_bus_socket_path, system_bus_socket_path, true)?;
325 }
326 TpmBackendConfig::SwtpmSocket(_) => {}
331 }
332 Ok(Some(jail))
333 }
334}