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