1 // Copyright 2021, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 //! This crate implements the KeyMint HAL service in Rust, communicating with a Rust
16 //! trusted application (TA) running on the Cuttlefish host.
17 
18 use kmr_hal_nonsecure::{attestation_id_info, get_boot_info};
19 use log::{debug, error, info};
20 use std::ops::DerefMut;
21 use std::os::unix::io::FromRawFd;
22 use std::panic;
23 use std::sync::{Arc, Mutex};
24 
25 /// Device file used to communicate with the KeyMint TA.
26 static DEVICE_FILE_NAME: &str = "/dev/hvc11";
27 
28 /// Name of KeyMint binder device instance.
29 static SERVICE_INSTANCE: &str = "default";
30 
31 static KM_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice";
32 static RPC_SERVICE_NAME: &str = "android.hardware.security.keymint.IRemotelyProvisionedComponent";
33 static CLOCK_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock";
34 static SECRET_SERVICE_NAME: &str = "android.hardware.security.sharedsecret.ISharedSecret";
35 
36 /// Local error type for failures in the HAL service.
37 #[derive(Debug, Clone)]
38 struct HalServiceError(String);
39 
40 /// Read-write file used for communication with host TA.
41 #[derive(Debug)]
42 struct FileChannel(std::fs::File);
43 
44 impl kmr_hal::SerializedChannel for FileChannel {
45     const MAX_SIZE: usize = kmr_wire::DEFAULT_MAX_SIZE;
46 
execute(&mut self, serialized_req: &[u8]) -> binder::Result<Vec<u8>>47     fn execute(&mut self, serialized_req: &[u8]) -> binder::Result<Vec<u8>> {
48         kmr_hal::write_msg(&mut self.0, serialized_req)?;
49         kmr_hal::read_msg(&mut self.0)
50     }
51 }
52 
53 /// Set 'raw' mode for the given file descriptor.
set_terminal_raw(fd: libc::c_int) -> Result<(), HalServiceError>54 fn set_terminal_raw(fd: libc::c_int) -> Result<(), HalServiceError> {
55     // SAFETY: All fields of termios are valid for zero bytes.
56     let mut settings: libc::termios = unsafe { std::mem::zeroed() };
57     // SAFETY: The pointer is valid because it comes from a reference, and tcgetattr doesn't store
58     // it.
59     let result = unsafe { libc::tcgetattr(fd, &mut settings) };
60     if result < 0 {
61         return Err(HalServiceError(format!(
62             "Failed to get terminal attributes for {}: {:?}",
63             fd,
64             std::io::Error::last_os_error()
65         )));
66     }
67 
68     // SAFETY: The pointers are valid because they come from references, and they are not stored
69     // beyond the function calls.
70     let result = unsafe {
71         libc::cfmakeraw(&mut settings);
72         libc::tcsetattr(fd, libc::TCSANOW, &settings)
73     };
74     if result < 0 {
75         return Err(HalServiceError(format!(
76             "Failed to set terminal attributes for {}: {:?}",
77             fd,
78             std::io::Error::last_os_error()
79         )));
80     }
81     Ok(())
82 }
83 
main()84 fn main() {
85     if let Err(HalServiceError(e)) = inner_main() {
86         panic!("HAL service failed: {:?}", e);
87     }
88 }
89 
inner_main() -> Result<(), HalServiceError>90 fn inner_main() -> Result<(), HalServiceError> {
91     // Initialize android logging.
92     android_logger::init_once(
93         android_logger::Config::default()
94             .with_tag("keymint-hal")
95             .with_max_level(log::LevelFilter::Info)
96             .with_log_buffer(android_logger::LogId::System),
97     );
98     // Redirect panic messages to logcat.
99     panic::set_hook(Box::new(|panic_info| {
100         error!("{}", panic_info);
101     }));
102 
103     info!("KeyMint HAL service is starting.");
104 
105     info!("Starting thread pool now.");
106     binder::ProcessState::start_thread_pool();
107 
108     // Create a connection to the TA.
109     let path = std::ffi::CString::new(DEVICE_FILE_NAME).unwrap();
110     // SAFETY: The path is a valid C string.
111     let fd = unsafe { libc::open(path.as_ptr(), libc::O_RDWR) };
112     if fd < 0 {
113         return Err(HalServiceError(format!(
114             "Failed to open device file '{}': {:?}",
115             DEVICE_FILE_NAME,
116             std::io::Error::last_os_error()
117         )));
118     }
119     set_terminal_raw(fd)?;
120     // SAFETY: The file descriptor is valid because `open` either returns a valid FD or -1, and we
121     // checked that it is not negative.
122     let channel = Arc::new(Mutex::new(FileChannel(unsafe { std::fs::File::from_raw_fd(fd) })));
123 
124     let km_service = kmr_hal::keymint::Device::new_as_binder(channel.clone());
125     let service_name = format!("{}/{}", KM_SERVICE_NAME, SERVICE_INSTANCE);
126     binder::add_service(&service_name, km_service.as_binder()).map_err(|e| {
127         HalServiceError(format!("Failed to register service {} because of {:?}.", service_name, e))
128     })?;
129 
130     let rpc_service = kmr_hal::rpc::Device::new_as_binder(channel.clone());
131     let service_name = format!("{}/{}", RPC_SERVICE_NAME, SERVICE_INSTANCE);
132     binder::add_service(&service_name, rpc_service.as_binder()).map_err(|e| {
133         HalServiceError(format!("Failed to register service {} because of {:?}.", service_name, e))
134     })?;
135 
136     let clock_service = kmr_hal::secureclock::Device::new_as_binder(channel.clone());
137     let service_name = format!("{}/{}", CLOCK_SERVICE_NAME, SERVICE_INSTANCE);
138     binder::add_service(&service_name, clock_service.as_binder()).map_err(|e| {
139         HalServiceError(format!("Failed to register service {} because of {:?}.", service_name, e))
140     })?;
141 
142     let secret_service = kmr_hal::sharedsecret::Device::new_as_binder(channel.clone());
143     let service_name = format!("{}/{}", SECRET_SERVICE_NAME, SERVICE_INSTANCE);
144     binder::add_service(&service_name, secret_service.as_binder()).map_err(|e| {
145         HalServiceError(format!("Failed to register service {} because of {:?}.", service_name, e))
146     })?;
147 
148     info!("Successfully registered KeyMint HAL services.");
149 
150     // Let the TA know information about the boot environment. In a real device this
151     // is communicated directly from the bootloader to the TA, but here we retrieve
152     // the information from system properties and send from the HAL service.
153     // TODO: investigate Cuttlefish bootloader info propagation
154     // https://android.googlesource.com/platform/external/u-boot/+/2114f87e56d262220c4dc5e00c3321e99e12204b/boot/android_bootloader_keymint.c
155     let boot_req = get_boot_info();
156     debug!("boot/HAL->TA: boot info is {:?}", boot_req);
157     kmr_hal::send_boot_info(channel.lock().unwrap().deref_mut(), boot_req)
158         .map_err(|e| HalServiceError(format!("Failed to send boot info: {:?}", e)))?;
159 
160     // Let the TA know information about the userspace environment.
161     if let Err(e) = kmr_hal::send_hal_info(channel.lock().unwrap().deref_mut()) {
162         error!("Failed to send HAL info: {:?}", e);
163     }
164 
165     // Let the TA know about attestation IDs. (In a real device these would be pre-provisioned into
166     // the TA.)
167     let attest_ids = attestation_id_info();
168     if let Err(e) = kmr_hal::send_attest_ids(channel.lock().unwrap().deref_mut(), attest_ids) {
169         error!("Failed to send attestation ID info: {:?}", e);
170     }
171 
172     info!("Joining thread pool now.");
173     binder::ProcessState::join_thread_pool();
174     info!("KeyMint HAL service is terminating.");
175     Ok(())
176 }
177