blob: 47143f49fa20f2255ae6673303b44571672e59af [file] [log] [blame]
David Drysdale30196cf2023-12-02 19:24:15 +00001/*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//! Default implementation of the KeyMint HAL and related HALs.
18//!
19//! This implementation of the HAL is only intended to allow testing and policy compliance. A real
David Drysdale33a132f2024-03-06 15:40:45 +000020//! implementation **must implement the TA in a secure environment**, as per CDD 9.11 [C-1-1]:
21//! "MUST back up the keystore implementation with an isolated execution environment."
22//!
23//! The additional device-specific components that are required for a real implementation of KeyMint
24//! that is based on the Rust reference implementation are described in system/keymint/README.md.
David Drysdale30196cf2023-12-02 19:24:15 +000025
26use kmr_hal::SerializedChannel;
27use kmr_hal_nonsecure::{attestation_id_info, get_boot_info};
David Drysdale33a132f2024-03-06 15:40:45 +000028use log::{debug, error, info, warn};
David Drysdale30196cf2023-12-02 19:24:15 +000029use std::ops::DerefMut;
30use std::sync::{mpsc, Arc, Mutex};
31
32/// Name of KeyMint binder device instance.
33static SERVICE_INSTANCE: &str = "default";
34
35static KM_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice";
36static RPC_SERVICE_NAME: &str = "android.hardware.security.keymint.IRemotelyProvisionedComponent";
37static CLOCK_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock";
38static SECRET_SERVICE_NAME: &str = "android.hardware.security.sharedsecret.ISharedSecret";
39
40/// Local error type for failures in the HAL service.
41#[derive(Debug, Clone)]
42struct HalServiceError(String);
43
44impl From<String> for HalServiceError {
45 fn from(s: String) -> Self {
46 Self(s)
47 }
48}
49
50fn main() {
Charisee5fc736d2024-04-03 20:04:29 +000051 if let Err(HalServiceError(e)) = inner_main() {
David Drysdale30196cf2023-12-02 19:24:15 +000052 panic!("HAL service failed: {:?}", e);
53 }
54}
55
56fn inner_main() -> Result<(), HalServiceError> {
57 // Initialize Android logging.
58 android_logger::init_once(
59 android_logger::Config::default()
60 .with_tag("keymint-hal-nonsecure")
61 .with_max_level(log::LevelFilter::Info)
62 .with_log_buffer(android_logger::LogId::System),
63 );
64 // Redirect panic messages to logcat.
65 std::panic::set_hook(Box::new(|panic_info| {
66 error!("{}", panic_info);
67 }));
68
David Drysdale33a132f2024-03-06 15:40:45 +000069 warn!("Insecure KeyMint HAL service is starting.");
David Drysdale30196cf2023-12-02 19:24:15 +000070
71 info!("Starting thread pool now.");
72 binder::ProcessState::start_thread_pool();
73
74 // Create a TA in-process, which acts as a local channel for communication.
75 let channel = Arc::new(Mutex::new(LocalTa::new()));
76
77 let km_service = kmr_hal::keymint::Device::new_as_binder(channel.clone());
78 let service_name = format!("{}/{}", KM_SERVICE_NAME, SERVICE_INSTANCE);
79 binder::add_service(&service_name, km_service.as_binder()).map_err(|e| {
80 HalServiceError(format!(
81 "Failed to register service {} because of {:?}.",
82 service_name, e
83 ))
84 })?;
85
86 let rpc_service = kmr_hal::rpc::Device::new_as_binder(channel.clone());
87 let service_name = format!("{}/{}", RPC_SERVICE_NAME, SERVICE_INSTANCE);
88 binder::add_service(&service_name, rpc_service.as_binder()).map_err(|e| {
89 HalServiceError(format!(
90 "Failed to register service {} because of {:?}.",
91 service_name, e
92 ))
93 })?;
94
95 let clock_service = kmr_hal::secureclock::Device::new_as_binder(channel.clone());
96 let service_name = format!("{}/{}", CLOCK_SERVICE_NAME, SERVICE_INSTANCE);
97 binder::add_service(&service_name, clock_service.as_binder()).map_err(|e| {
98 HalServiceError(format!(
99 "Failed to register service {} because of {:?}.",
100 service_name, e
101 ))
102 })?;
103
104 let secret_service = kmr_hal::sharedsecret::Device::new_as_binder(channel.clone());
105 let service_name = format!("{}/{}", SECRET_SERVICE_NAME, SERVICE_INSTANCE);
106 binder::add_service(&service_name, secret_service.as_binder()).map_err(|e| {
107 HalServiceError(format!(
108 "Failed to register service {} because of {:?}.",
109 service_name, e
110 ))
111 })?;
112
113 info!("Successfully registered KeyMint HAL services.");
114
115 // Let the TA know information about the boot environment. In a real device this
116 // is communicated directly from the bootloader to the TA, but here we retrieve
117 // the information from system properties and send from the HAL service.
118 let boot_req = get_boot_info();
119 debug!("boot/HAL->TA: boot info is {:?}", boot_req);
120 kmr_hal::send_boot_info(channel.lock().unwrap().deref_mut(), boot_req)
121 .map_err(|e| HalServiceError(format!("Failed to send boot info: {:?}", e)))?;
122
123 // Let the TA know information about the userspace environment.
124 if let Err(e) = kmr_hal::send_hal_info(channel.lock().unwrap().deref_mut()) {
125 error!("Failed to send HAL info: {:?}", e);
126 }
127
128 // Let the TA know about attestation IDs. (In a real device these would be pre-provisioned into
129 // the TA.)
130 let attest_ids = attestation_id_info();
131 if let Err(e) = kmr_hal::send_attest_ids(channel.lock().unwrap().deref_mut(), attest_ids) {
132 error!("Failed to send attestation ID info: {:?}", e);
133 }
134
135 info!("Successfully registered KeyMint HAL services.");
136 binder::ProcessState::join_thread_pool();
137 info!("KeyMint HAL service is terminating."); // should not reach here
138 Ok(())
139}
140
141/// Implementation of the KeyMint TA that runs locally in-process (and which is therefore
142/// insecure).
143#[derive(Debug)]
144pub struct LocalTa {
145 in_tx: mpsc::Sender<Vec<u8>>,
146 out_rx: mpsc::Receiver<Vec<u8>>,
147}
148
149impl LocalTa {
150 /// Create a new instance.
151 pub fn new() -> Self {
152 // Create a pair of channels to communicate with the TA thread.
153 let (in_tx, in_rx) = mpsc::channel();
154 let (out_tx, out_rx) = mpsc::channel();
155
156 // The TA code expects to run single threaded, so spawn a thread to run it in.
157 std::thread::spawn(move || {
158 let mut ta = kmr_ta_nonsecure::build_ta();
159 loop {
160 let req_data: Vec<u8> = in_rx.recv().expect("failed to receive next req");
161 let rsp_data = ta.process(&req_data);
162 out_tx.send(rsp_data).expect("failed to send out rsp");
163 }
164 });
165 Self { in_tx, out_rx }
166 }
167}
168
169impl SerializedChannel for LocalTa {
170 const MAX_SIZE: usize = usize::MAX;
171
172 fn execute(&mut self, req_data: &[u8]) -> binder::Result<Vec<u8>> {
173 self.in_tx
174 .send(req_data.to_vec())
175 .expect("failed to send in request");
176 Ok(self.out_rx.recv().expect("failed to receive response"))
177 }
178}