David Drysdale | 30196cf | 2023-12-02 19:24:15 +0000 | [diff] [blame] | 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 be implemented in a secure environment**. |
| 21 | |
| 22 | use kmr_hal::SerializedChannel; |
| 23 | use kmr_hal_nonsecure::{attestation_id_info, get_boot_info}; |
| 24 | use log::{debug, error, info}; |
| 25 | use std::ops::DerefMut; |
| 26 | use std::sync::{mpsc, Arc, Mutex}; |
| 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 | impl From<String> for HalServiceError { |
| 41 | fn from(s: String) -> Self { |
| 42 | Self(s) |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | fn main() { |
Charisee | 5fc736d | 2024-04-03 20:04:29 +0000 | [diff] [blame^] | 47 | if let Err(HalServiceError(e)) = inner_main() { |
David Drysdale | 30196cf | 2023-12-02 19:24:15 +0000 | [diff] [blame] | 48 | panic!("HAL service failed: {:?}", e); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | fn inner_main() -> Result<(), HalServiceError> { |
| 53 | // Initialize Android logging. |
| 54 | android_logger::init_once( |
| 55 | android_logger::Config::default() |
| 56 | .with_tag("keymint-hal-nonsecure") |
| 57 | .with_max_level(log::LevelFilter::Info) |
| 58 | .with_log_buffer(android_logger::LogId::System), |
| 59 | ); |
| 60 | // Redirect panic messages to logcat. |
| 61 | std::panic::set_hook(Box::new(|panic_info| { |
| 62 | error!("{}", panic_info); |
| 63 | })); |
| 64 | |
| 65 | info!("Insecure KeyMint HAL service is starting."); |
| 66 | |
| 67 | info!("Starting thread pool now."); |
| 68 | binder::ProcessState::start_thread_pool(); |
| 69 | |
| 70 | // Create a TA in-process, which acts as a local channel for communication. |
| 71 | let channel = Arc::new(Mutex::new(LocalTa::new())); |
| 72 | |
| 73 | let km_service = kmr_hal::keymint::Device::new_as_binder(channel.clone()); |
| 74 | let service_name = format!("{}/{}", KM_SERVICE_NAME, SERVICE_INSTANCE); |
| 75 | binder::add_service(&service_name, km_service.as_binder()).map_err(|e| { |
| 76 | HalServiceError(format!( |
| 77 | "Failed to register service {} because of {:?}.", |
| 78 | service_name, e |
| 79 | )) |
| 80 | })?; |
| 81 | |
| 82 | let rpc_service = kmr_hal::rpc::Device::new_as_binder(channel.clone()); |
| 83 | let service_name = format!("{}/{}", RPC_SERVICE_NAME, SERVICE_INSTANCE); |
| 84 | binder::add_service(&service_name, rpc_service.as_binder()).map_err(|e| { |
| 85 | HalServiceError(format!( |
| 86 | "Failed to register service {} because of {:?}.", |
| 87 | service_name, e |
| 88 | )) |
| 89 | })?; |
| 90 | |
| 91 | let clock_service = kmr_hal::secureclock::Device::new_as_binder(channel.clone()); |
| 92 | let service_name = format!("{}/{}", CLOCK_SERVICE_NAME, SERVICE_INSTANCE); |
| 93 | binder::add_service(&service_name, clock_service.as_binder()).map_err(|e| { |
| 94 | HalServiceError(format!( |
| 95 | "Failed to register service {} because of {:?}.", |
| 96 | service_name, e |
| 97 | )) |
| 98 | })?; |
| 99 | |
| 100 | let secret_service = kmr_hal::sharedsecret::Device::new_as_binder(channel.clone()); |
| 101 | let service_name = format!("{}/{}", SECRET_SERVICE_NAME, SERVICE_INSTANCE); |
| 102 | binder::add_service(&service_name, secret_service.as_binder()).map_err(|e| { |
| 103 | HalServiceError(format!( |
| 104 | "Failed to register service {} because of {:?}.", |
| 105 | service_name, e |
| 106 | )) |
| 107 | })?; |
| 108 | |
| 109 | info!("Successfully registered KeyMint HAL services."); |
| 110 | |
| 111 | // Let the TA know information about the boot environment. In a real device this |
| 112 | // is communicated directly from the bootloader to the TA, but here we retrieve |
| 113 | // the information from system properties and send from the HAL service. |
| 114 | let boot_req = get_boot_info(); |
| 115 | debug!("boot/HAL->TA: boot info is {:?}", boot_req); |
| 116 | kmr_hal::send_boot_info(channel.lock().unwrap().deref_mut(), boot_req) |
| 117 | .map_err(|e| HalServiceError(format!("Failed to send boot info: {:?}", e)))?; |
| 118 | |
| 119 | // Let the TA know information about the userspace environment. |
| 120 | if let Err(e) = kmr_hal::send_hal_info(channel.lock().unwrap().deref_mut()) { |
| 121 | error!("Failed to send HAL info: {:?}", e); |
| 122 | } |
| 123 | |
| 124 | // Let the TA know about attestation IDs. (In a real device these would be pre-provisioned into |
| 125 | // the TA.) |
| 126 | let attest_ids = attestation_id_info(); |
| 127 | if let Err(e) = kmr_hal::send_attest_ids(channel.lock().unwrap().deref_mut(), attest_ids) { |
| 128 | error!("Failed to send attestation ID info: {:?}", e); |
| 129 | } |
| 130 | |
| 131 | info!("Successfully registered KeyMint HAL services."); |
| 132 | binder::ProcessState::join_thread_pool(); |
| 133 | info!("KeyMint HAL service is terminating."); // should not reach here |
| 134 | Ok(()) |
| 135 | } |
| 136 | |
| 137 | /// Implementation of the KeyMint TA that runs locally in-process (and which is therefore |
| 138 | /// insecure). |
| 139 | #[derive(Debug)] |
| 140 | pub struct LocalTa { |
| 141 | in_tx: mpsc::Sender<Vec<u8>>, |
| 142 | out_rx: mpsc::Receiver<Vec<u8>>, |
| 143 | } |
| 144 | |
| 145 | impl LocalTa { |
| 146 | /// Create a new instance. |
| 147 | pub fn new() -> Self { |
| 148 | // Create a pair of channels to communicate with the TA thread. |
| 149 | let (in_tx, in_rx) = mpsc::channel(); |
| 150 | let (out_tx, out_rx) = mpsc::channel(); |
| 151 | |
| 152 | // The TA code expects to run single threaded, so spawn a thread to run it in. |
| 153 | std::thread::spawn(move || { |
| 154 | let mut ta = kmr_ta_nonsecure::build_ta(); |
| 155 | loop { |
| 156 | let req_data: Vec<u8> = in_rx.recv().expect("failed to receive next req"); |
| 157 | let rsp_data = ta.process(&req_data); |
| 158 | out_tx.send(rsp_data).expect("failed to send out rsp"); |
| 159 | } |
| 160 | }); |
| 161 | Self { in_tx, out_rx } |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | impl SerializedChannel for LocalTa { |
| 166 | const MAX_SIZE: usize = usize::MAX; |
| 167 | |
| 168 | fn execute(&mut self, req_data: &[u8]) -> binder::Result<Vec<u8>> { |
| 169 | self.in_tx |
| 170 | .send(req_data.to_vec()) |
| 171 | .expect("failed to send in request"); |
| 172 | Ok(self.out_rx.recv().expect("failed to receive response")) |
| 173 | } |
| 174 | } |