device_virtio_tpm/
vtpm_proxy.rs

1// Copyright 2022 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
5//! vTPM Proxy backend using the vtpmd on ChromeOS to virtualize TPM commands.
6
7use std::time::Duration;
8
9use base::error;
10use protobuf::Message;
11use remain::sorted;
12use system_api::client::OrgChromiumVtpm;
13use system_api::vtpm_interface::SendCommandRequest;
14use system_api::vtpm_interface::SendCommandResponse;
15use thiserror::Error;
16
17use crate::TpmBackend;
18
19// 5 minutes is the default timeout for tpm commands.
20const VTPM_DBUS_TIMEOUT: Duration = Duration::from_secs(300);
21
22// The response of TPM_RC_INSUFFICIENT
23const TPM_RC_INSUFFICIENT_RESPONSE: &[u8] = &[
24    0x80, 0x01, // TPM_ST_NO_SESSIONS
25    0x00, 0x00, 0x00, 0x0A, // Header Size = 10
26    0x00, 0x00, 0x00, 0x9A, // TPM_RC_INSUFFICIENT
27];
28
29use crate::TPM_RC_FAILURE_RESPONSE;
30
31/// A proxy object that connects to the vtpmd on ChromeOS.
32pub struct VtpmProxy {
33    dbus_connection: Option<dbus::blocking::Connection>,
34    buf: Vec<u8>,
35}
36
37impl VtpmProxy {
38    /// Returns a proxy that can be connected to the vtpmd.
39    pub fn new() -> Self {
40        VtpmProxy {
41            dbus_connection: None,
42            buf: Vec::new(),
43        }
44    }
45
46    fn get_or_create_dbus_connection(
47        &mut self,
48    ) -> anyhow::Result<&dbus::blocking::Connection, dbus::Error> {
49        match self.dbus_connection {
50            Some(ref dbus_connection) => Ok(dbus_connection),
51            None => {
52                let dbus_connection = dbus::blocking::Connection::new_system()?;
53                self.dbus_connection = Some(dbus_connection);
54                self.get_or_create_dbus_connection()
55            }
56        }
57    }
58
59    fn try_execute_command(&mut self, command: &[u8]) -> anyhow::Result<(), Error> {
60        let dbus_connection = self
61            .get_or_create_dbus_connection()
62            .map_err(Error::DBusError)?;
63
64        let proxy = dbus_connection.with_proxy(
65            "org.chromium.Vtpm",
66            "/org/chromium/Vtpm",
67            VTPM_DBUS_TIMEOUT,
68        );
69
70        let mut proto = SendCommandRequest::new();
71        proto.set_command(command.to_vec());
72
73        let bytes = proto.write_to_bytes().map_err(Error::ProtobufError)?;
74
75        let resp_bytes = proxy.send_command(bytes).map_err(Error::DBusError)?;
76
77        let response =
78            SendCommandResponse::parse_from_bytes(&resp_bytes).map_err(Error::ProtobufError)?;
79
80        self.buf = response.response().to_vec();
81
82        Ok(())
83    }
84}
85
86impl Default for VtpmProxy {
87    fn default() -> Self {
88        Self::new()
89    }
90}
91
92impl TpmBackend for VtpmProxy {
93    fn execute_command<'a>(&'a mut self, command: &[u8]) -> &'a [u8] {
94        match self.try_execute_command(command) {
95            Ok(()) => &self.buf,
96            Err(e) => {
97                error!("{:#}", e);
98                match e {
99                    Error::ProtobufError(_) => TPM_RC_INSUFFICIENT_RESPONSE,
100                    Error::DBusError(_) => TPM_RC_FAILURE_RESPONSE,
101                }
102            }
103        }
104    }
105}
106
107#[sorted]
108#[derive(Error, Debug)]
109enum Error {
110    #[error("D-Bus failure: {0:#}")]
111    DBusError(dbus::Error),
112    #[error("protocol buffers failure: {0:#}")]
113    ProtobufError(protobuf::Error),
114}