1 /*
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
20 //! 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.
25
26 use kmr_hal::SerializedChannel;
27 use kmr_hal_nonsecure::{attestation_id_info, get_boot_info};
28 use log::{debug, error, info, warn};
29 use std::ops::DerefMut;
30 use std::sync::{mpsc, Arc, Mutex};
31
32 /// Name of KeyMint binder device instance.
33 static SERVICE_INSTANCE: &str = "default";
34
35 static KM_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice";
36 static RPC_SERVICE_NAME: &str = "android.hardware.security.keymint.IRemotelyProvisionedComponent";
37 static CLOCK_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock";
38 static SECRET_SERVICE_NAME: &str = "android.hardware.security.sharedsecret.ISharedSecret";
39
40 /// Local error type for failures in the HAL service.
41 #[derive(Debug, Clone)]
42 struct HalServiceError(String);
43
44 impl From<String> for HalServiceError {
from(s: String) -> Self45 fn from(s: String) -> Self {
46 Self(s)
47 }
48 }
49
main()50 fn main() {
51 if let Err(HalServiceError(e)) = inner_main() {
52 panic!("HAL service failed: {:?}", e);
53 }
54 }
55
inner_main() -> Result<(), HalServiceError>56 fn 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
69 warn!("Insecure KeyMint HAL service is starting.");
70
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 the TA know information about the boot environment. In a real device this
78 // is communicated directly from the bootloader to the TA, but here we retrieve
79 // the information from system properties and send from the HAL service.
80 let boot_req = get_boot_info();
81 debug!("boot/HAL->TA: boot info is {:?}", boot_req);
82 kmr_hal::send_boot_info(channel.lock().unwrap().deref_mut(), boot_req)
83 .map_err(|e| HalServiceError(format!("Failed to send boot info: {:?}", e)))?;
84
85 // Let the TA know information about the userspace environment.
86 if let Err(e) = kmr_hal::send_hal_info(channel.lock().unwrap().deref_mut()) {
87 error!("Failed to send HAL info: {:?}", e);
88 }
89
90 // Let the TA know about attestation IDs. (In a real device these would be pre-provisioned into
91 // the TA.)
92 let attest_ids = attestation_id_info();
93 if let Err(e) = kmr_hal::send_attest_ids(channel.lock().unwrap().deref_mut(), attest_ids) {
94 error!("Failed to send attestation ID info: {:?}", e);
95 }
96
97 let secret_service = kmr_hal::sharedsecret::Device::new_as_binder(channel.clone());
98 let service_name = format!("{}/{}", SECRET_SERVICE_NAME, SERVICE_INSTANCE);
99 binder::add_service(&service_name, secret_service.as_binder()).map_err(|e| {
100 HalServiceError(format!(
101 "Failed to register service {} because of {:?}.",
102 service_name, e
103 ))
104 })?;
105
106 let km_service = kmr_hal::keymint::Device::new_as_binder(channel.clone());
107 let service_name = format!("{}/{}", KM_SERVICE_NAME, SERVICE_INSTANCE);
108 binder::add_service(&service_name, km_service.as_binder()).map_err(|e| {
109 HalServiceError(format!(
110 "Failed to register service {} because of {:?}.",
111 service_name, e
112 ))
113 })?;
114
115 let rpc_service = kmr_hal::rpc::Device::new_as_binder(channel.clone());
116 let service_name = format!("{}/{}", RPC_SERVICE_NAME, SERVICE_INSTANCE);
117 binder::add_service(&service_name, rpc_service.as_binder()).map_err(|e| {
118 HalServiceError(format!(
119 "Failed to register service {} because of {:?}.",
120 service_name, e
121 ))
122 })?;
123
124 let clock_service = kmr_hal::secureclock::Device::new_as_binder(channel.clone());
125 let service_name = format!("{}/{}", CLOCK_SERVICE_NAME, SERVICE_INSTANCE);
126 binder::add_service(&service_name, clock_service.as_binder()).map_err(|e| {
127 HalServiceError(format!(
128 "Failed to register service {} because of {:?}.",
129 service_name, e
130 ))
131 })?;
132
133 info!("Successfully registered KeyMint HAL services.");
134 binder::ProcessState::join_thread_pool();
135 info!("KeyMint HAL service is terminating."); // should not reach here
136 Ok(())
137 }
138
139 /// Implementation of the KeyMint TA that runs locally in-process (and which is therefore
140 /// insecure).
141 #[derive(Debug)]
142 pub struct LocalTa {
143 in_tx: mpsc::Sender<Vec<u8>>,
144 out_rx: mpsc::Receiver<Vec<u8>>,
145 }
146
147 impl LocalTa {
148 /// Create a new instance.
new() -> Self149 pub fn new() -> Self {
150 // Create a pair of channels to communicate with the TA thread.
151 let (in_tx, in_rx) = mpsc::channel();
152 let (out_tx, out_rx) = mpsc::channel();
153
154 // The TA code expects to run single threaded, so spawn a thread to run it in.
155 std::thread::spawn(move || {
156 let mut ta = kmr_ta_nonsecure::build_ta();
157 loop {
158 let req_data: Vec<u8> = in_rx.recv().expect("failed to receive next req");
159 let rsp_data = ta.process(&req_data);
160 out_tx.send(rsp_data).expect("failed to send out rsp");
161 }
162 });
163 Self { in_tx, out_rx }
164 }
165 }
166
167 impl SerializedChannel for LocalTa {
168 const MAX_SIZE: usize = usize::MAX;
169
execute(&mut self, req_data: &[u8]) -> binder::Result<Vec<u8>>170 fn execute(&mut self, req_data: &[u8]) -> binder::Result<Vec<u8>> {
171 self.in_tx
172 .send(req_data.to_vec())
173 .expect("failed to send in request");
174 Ok(self.out_rx.recv().expect("failed to receive response"))
175 }
176 }
177