blob: c8c15215c2777526e9a830e2b021beafc415b05e [file] [log] [blame]
Shikha Panwareb223ba2023-10-19 14:54:06 +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
David Drysdale8898d2e2023-11-07 15:20:15 +000017//! Non-secure implementation of the Secretkeeper HAL.
Shikha Panwar2759df02023-11-27 22:00:42 +000018mod store;
David Drysdale8898d2e2023-11-07 15:20:15 +000019
David Drysdale8898d2e2023-11-07 15:20:15 +000020use authgraph_boringssl as boring;
Shikha Panwar2759df02023-11-27 22:00:42 +000021use authgraph_core::keyexchange::{AuthGraphParticipant, MAX_OPENED_SESSIONS};
22use authgraph_core::ta::{AuthGraphTa, Role};
23use authgraph_hal::channel::SerializedChannel;
24use log::{error, info, Level};
Shikha Panwar3f136b22023-12-07 18:44:00 +000025use secretkeeper_core::ta::SecretkeeperTa;
David Drysdale8898d2e2023-11-07 15:20:15 +000026use secretkeeper_hal::SecretkeeperService;
Shikha Panwar2759df02023-11-27 22:00:42 +000027use std::sync::Arc;
28use std::sync::Mutex;
29use store::InMemoryStore;
30
Shikha Panwareb223ba2023-10-19 14:54:06 +000031use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::{
Shikha Panwar2759df02023-11-27 22:00:42 +000032 BpSecretkeeper, ISecretkeeper,
Shikha Panwareb223ba2023-10-19 14:54:06 +000033};
David Drysdale8898d2e2023-11-07 15:20:15 +000034use std::cell::RefCell;
35use std::rc::Rc;
36use std::sync::mpsc;
Shikha Panwareb223ba2023-10-19 14:54:06 +000037
David Drysdale8898d2e2023-11-07 15:20:15 +000038/// Implementation of the Secrekeeper TA that runs locally in-process (and which is therefore
39/// insecure).
40pub struct LocalTa {
41 in_tx: mpsc::Sender<Vec<u8>>,
42 out_rx: mpsc::Receiver<Vec<u8>>,
43}
Shikha Panwareb223ba2023-10-19 14:54:06 +000044
David Drysdale8898d2e2023-11-07 15:20:15 +000045/// Prefix byte for messages intended for the AuthGraph TA.
46const AG_MESSAGE_PREFIX: u8 = 0x00;
47/// Prefix byte for messages intended for the Secretkeeper TA.
48const SK_MESSAGE_PREFIX: u8 = 0x01;
Shikha Panwareb223ba2023-10-19 14:54:06 +000049
David Drysdale8898d2e2023-11-07 15:20:15 +000050impl LocalTa {
51 /// Create a new instance.
52 pub fn new() -> Self {
53 // Create a pair of channels to communicate with the TA thread.
54 let (in_tx, in_rx) = mpsc::channel();
55 let (out_tx, out_rx) = mpsc::channel();
Shikha Panwareb223ba2023-10-19 14:54:06 +000056
David Drysdale8898d2e2023-11-07 15:20:15 +000057 // The TA code expects to run single threaded, so spawn a thread to run it in.
58 std::thread::spawn(move || {
59 let mut crypto_impls = boring::crypto_trait_impls();
Shikha Panwar2759df02023-11-27 22:00:42 +000060 let storage_impl = Box::new(InMemoryStore::default());
David Drysdale8898d2e2023-11-07 15:20:15 +000061 let sk_ta = Rc::new(RefCell::new(
Shikha Panwar2759df02023-11-27 22:00:42 +000062 SecretkeeperTa::new(&mut crypto_impls, storage_impl)
David Drysdale8898d2e2023-11-07 15:20:15 +000063 .expect("Failed to create local Secretkeeper TA"),
64 ));
65 let mut ag_ta = AuthGraphTa::new(
66 AuthGraphParticipant::new(crypto_impls, sk_ta.clone(), MAX_OPENED_SESSIONS)
67 .expect("Failed to create local AuthGraph TA"),
68 Role::Sink,
69 );
70
71 // Loop forever processing request messages.
72 loop {
73 let req_data: Vec<u8> = in_rx.recv().expect("failed to receive next req");
74 let rsp_data = match req_data[0] {
75 AG_MESSAGE_PREFIX => ag_ta.process(&req_data[1..]),
76 SK_MESSAGE_PREFIX => {
77 // It's safe to `borrow_mut()` because this code is not a callback
78 // from AuthGraph (the only other holder of an `Rc`), and so there
79 // can be no live `borrow()`s in this (single) thread.
80 sk_ta.borrow_mut().process(&req_data[1..])
81 }
82 prefix => panic!("unexpected messageprefix {prefix}!"),
83 };
84 out_tx.send(rsp_data).expect("failed to send out rsp");
85 }
86 });
87 Self { in_tx, out_rx }
88 }
89
90 fn execute_for(&mut self, prefix: u8, req_data: &[u8]) -> Vec<u8> {
91 let mut prefixed_req = Vec::with_capacity(req_data.len() + 1);
92 prefixed_req.push(prefix);
93 prefixed_req.extend_from_slice(req_data);
94 self.in_tx
95 .send(prefixed_req)
96 .expect("failed to send in request");
97 self.out_rx.recv().expect("failed to receive response")
Shikha Panwareb223ba2023-10-19 14:54:06 +000098 }
99}
100
David Drysdale8898d2e2023-11-07 15:20:15 +0000101pub struct AuthGraphChannel(Arc<Mutex<LocalTa>>);
102impl SerializedChannel for AuthGraphChannel {
103 const MAX_SIZE: usize = usize::MAX;
104 fn execute(&self, req_data: &[u8]) -> binder::Result<Vec<u8>> {
105 Ok(self
106 .0
107 .lock()
108 .unwrap()
109 .execute_for(AG_MESSAGE_PREFIX, req_data))
Shikha Panwareb223ba2023-10-19 14:54:06 +0000110 }
David Drysdale8898d2e2023-11-07 15:20:15 +0000111}
Shikha Panwareb223ba2023-10-19 14:54:06 +0000112
David Drysdale8898d2e2023-11-07 15:20:15 +0000113pub struct SecretkeeperChannel(Arc<Mutex<LocalTa>>);
114impl SerializedChannel for SecretkeeperChannel {
115 const MAX_SIZE: usize = usize::MAX;
116 fn execute(&self, req_data: &[u8]) -> binder::Result<Vec<u8>> {
117 Ok(self
118 .0
119 .lock()
120 .unwrap()
121 .execute_for(SK_MESSAGE_PREFIX, req_data))
Shikha Panwareb223ba2023-10-19 14:54:06 +0000122 }
123}
124
125fn main() {
126 // Initialize Android logging.
127 android_logger::init_once(
128 android_logger::Config::default()
129 .with_tag("NonSecureSecretkeeper")
130 .with_min_level(Level::Info)
131 .with_log_id(android_logger::LogId::System),
132 );
133 // Redirect panic messages to logcat.
134 std::panic::set_hook(Box::new(|panic_info| {
135 error!("{}", panic_info);
136 }));
137
David Drysdale8898d2e2023-11-07 15:20:15 +0000138 let ta = Arc::new(Mutex::new(LocalTa::new()));
139 let ag_channel = AuthGraphChannel(ta.clone());
140 let sk_channel = SecretkeeperChannel(ta.clone());
141
142 let service = SecretkeeperService::new_as_binder(sk_channel, ag_channel);
Shikha Panwareb223ba2023-10-19 14:54:06 +0000143 let service_name = format!(
144 "{}/nonsecure",
145 <BpSecretkeeper as ISecretkeeper>::get_descriptor()
146 );
David Drysdale8898d2e2023-11-07 15:20:15 +0000147 binder::add_service(&service_name, service.as_binder()).unwrap_or_else(|e| {
148 panic!("Failed to register service {service_name} because of {e:?}.",);
Shikha Panwareb223ba2023-10-19 14:54:06 +0000149 });
150 info!("Registered Binder service, joining threadpool.");
151 binder::ProcessState::join_thread_pool();
152}