device_virtio_tpm/
vtpm_proxy.rs1use 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
19const VTPM_DBUS_TIMEOUT: Duration = Duration::from_secs(300);
21
22const TPM_RC_INSUFFICIENT_RESPONSE: &[u8] = &[
24 0x80, 0x01, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x9A, ];
28
29use crate::TPM_RC_FAILURE_RESPONSE;
30
31pub struct VtpmProxy {
33 dbus_connection: Option<dbus::blocking::Connection>,
34 buf: Vec<u8>,
35}
36
37impl VtpmProxy {
38 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}