blob: a2910179a94c861ac570273f241de553dccf80b3 [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.
18
Shikha Panwareb223ba2023-10-19 14:54:06 +000019use log::{error, info, Level};
David Drysdale8898d2e2023-11-07 15:20:15 +000020use std::sync::{Arc, Mutex};
21use authgraph_boringssl as boring;
22use authgraph_core::ta::{Role, AuthGraphTa};
23use authgraph_core::keyexchange::{MAX_OPENED_SESSIONS, AuthGraphParticipant};
Shikha Panwar3f136b22023-12-07 18:44:00 +000024use secretkeeper_core::ta::SecretkeeperTa;
David Drysdale8898d2e2023-11-07 15:20:15 +000025use secretkeeper_hal::SecretkeeperService;
26use authgraph_hal::channel::SerializedChannel;
Shikha Panwareb223ba2023-10-19 14:54:06 +000027use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::{
David Drysdale8898d2e2023-11-07 15:20:15 +000028 ISecretkeeper, BpSecretkeeper,
Shikha Panwareb223ba2023-10-19 14:54:06 +000029};
David Drysdale8898d2e2023-11-07 15:20:15 +000030use std::cell::RefCell;
31use std::rc::Rc;
32use std::sync::mpsc;
Shikha Panwareb223ba2023-10-19 14:54:06 +000033
David Drysdale8898d2e2023-11-07 15:20:15 +000034/// Implementation of the Secrekeeper TA that runs locally in-process (and which is therefore
35/// insecure).
36pub struct LocalTa {
37 in_tx: mpsc::Sender<Vec<u8>>,
38 out_rx: mpsc::Receiver<Vec<u8>>,
39}
Shikha Panwareb223ba2023-10-19 14:54:06 +000040
David Drysdale8898d2e2023-11-07 15:20:15 +000041/// Prefix byte for messages intended for the AuthGraph TA.
42const AG_MESSAGE_PREFIX: u8 = 0x00;
43/// Prefix byte for messages intended for the Secretkeeper TA.
44const SK_MESSAGE_PREFIX: u8 = 0x01;
Shikha Panwareb223ba2023-10-19 14:54:06 +000045
David Drysdale8898d2e2023-11-07 15:20:15 +000046impl LocalTa {
47 /// Create a new instance.
48 pub fn new() -> Self {
49 // Create a pair of channels to communicate with the TA thread.
50 let (in_tx, in_rx) = mpsc::channel();
51 let (out_tx, out_rx) = mpsc::channel();
Shikha Panwareb223ba2023-10-19 14:54:06 +000052
David Drysdale8898d2e2023-11-07 15:20:15 +000053 // The TA code expects to run single threaded, so spawn a thread to run it in.
54 std::thread::spawn(move || {
55 let mut crypto_impls = boring::crypto_trait_impls();
56 let sk_ta = Rc::new(RefCell::new(
57 SecretkeeperTa::new(&mut crypto_impls)
58 .expect("Failed to create local Secretkeeper TA"),
59 ));
60 let mut ag_ta = AuthGraphTa::new(
61 AuthGraphParticipant::new(crypto_impls, sk_ta.clone(), MAX_OPENED_SESSIONS)
62 .expect("Failed to create local AuthGraph TA"),
63 Role::Sink,
64 );
65
66 // Loop forever processing request messages.
67 loop {
68 let req_data: Vec<u8> = in_rx.recv().expect("failed to receive next req");
69 let rsp_data = match req_data[0] {
70 AG_MESSAGE_PREFIX => ag_ta.process(&req_data[1..]),
71 SK_MESSAGE_PREFIX => {
72 // It's safe to `borrow_mut()` because this code is not a callback
73 // from AuthGraph (the only other holder of an `Rc`), and so there
74 // can be no live `borrow()`s in this (single) thread.
75 sk_ta.borrow_mut().process(&req_data[1..])
76 }
77 prefix => panic!("unexpected messageprefix {prefix}!"),
78 };
79 out_tx.send(rsp_data).expect("failed to send out rsp");
80 }
81 });
82 Self { in_tx, out_rx }
83 }
84
85 fn execute_for(&mut self, prefix: u8, req_data: &[u8]) -> Vec<u8> {
86 let mut prefixed_req = Vec::with_capacity(req_data.len() + 1);
87 prefixed_req.push(prefix);
88 prefixed_req.extend_from_slice(req_data);
89 self.in_tx
90 .send(prefixed_req)
91 .expect("failed to send in request");
92 self.out_rx.recv().expect("failed to receive response")
Shikha Panwareb223ba2023-10-19 14:54:06 +000093 }
94}
95
David Drysdale8898d2e2023-11-07 15:20:15 +000096pub struct AuthGraphChannel(Arc<Mutex<LocalTa>>);
97impl SerializedChannel for AuthGraphChannel {
98 const MAX_SIZE: usize = usize::MAX;
99 fn execute(&self, req_data: &[u8]) -> binder::Result<Vec<u8>> {
100 Ok(self
101 .0
102 .lock()
103 .unwrap()
104 .execute_for(AG_MESSAGE_PREFIX, req_data))
Shikha Panwareb223ba2023-10-19 14:54:06 +0000105 }
David Drysdale8898d2e2023-11-07 15:20:15 +0000106}
Shikha Panwareb223ba2023-10-19 14:54:06 +0000107
David Drysdale8898d2e2023-11-07 15:20:15 +0000108pub struct SecretkeeperChannel(Arc<Mutex<LocalTa>>);
109impl SerializedChannel for SecretkeeperChannel {
110 const MAX_SIZE: usize = usize::MAX;
111 fn execute(&self, req_data: &[u8]) -> binder::Result<Vec<u8>> {
112 Ok(self
113 .0
114 .lock()
115 .unwrap()
116 .execute_for(SK_MESSAGE_PREFIX, req_data))
Shikha Panwareb223ba2023-10-19 14:54:06 +0000117 }
118}
119
120fn main() {
121 // Initialize Android logging.
122 android_logger::init_once(
123 android_logger::Config::default()
124 .with_tag("NonSecureSecretkeeper")
125 .with_min_level(Level::Info)
126 .with_log_id(android_logger::LogId::System),
127 );
128 // Redirect panic messages to logcat.
129 std::panic::set_hook(Box::new(|panic_info| {
130 error!("{}", panic_info);
131 }));
132
David Drysdale8898d2e2023-11-07 15:20:15 +0000133 let ta = Arc::new(Mutex::new(LocalTa::new()));
134 let ag_channel = AuthGraphChannel(ta.clone());
135 let sk_channel = SecretkeeperChannel(ta.clone());
136
137 let service = SecretkeeperService::new_as_binder(sk_channel, ag_channel);
Shikha Panwareb223ba2023-10-19 14:54:06 +0000138 let service_name = format!(
139 "{}/nonsecure",
140 <BpSecretkeeper as ISecretkeeper>::get_descriptor()
141 );
David Drysdale8898d2e2023-11-07 15:20:15 +0000142 binder::add_service(&service_name, service.as_binder()).unwrap_or_else(|e| {
143 panic!("Failed to register service {service_name} because of {e:?}.",);
Shikha Panwareb223ba2023-10-19 14:54:06 +0000144 });
145 info!("Registered Binder service, joining threadpool.");
146 binder::ProcessState::join_thread_pool();
147}