blob: 936fe3d6bfe454436ff580fe20042530b11e2ca1 [file] [log] [blame]
Tri Voe8f04442022-12-21 08:53:56 -08001// Copyright 2022, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Helper wrapper around RKPD interface.
16
Tri Voe8f04442022-12-21 08:53:56 -080017use android_security_rkp_aidl::aidl::android::security::rkp::{
Seth Moore484010a2023-01-31 11:22:26 -080018 IGetKeyCallback::BnGetKeyCallback, IGetKeyCallback::ErrorCode::ErrorCode as GetKeyErrorCode,
19 IGetKeyCallback::IGetKeyCallback, IGetRegistrationCallback::BnGetRegistrationCallback,
Tri Voe8f04442022-12-21 08:53:56 -080020 IGetRegistrationCallback::IGetRegistrationCallback, IRegistration::IRegistration,
Seth Moorea55428e2023-01-10 13:07:31 -080021 IRemoteProvisioning::IRemoteProvisioning,
22 IStoreUpgradedKeyCallback::BnStoreUpgradedKeyCallback,
23 IStoreUpgradedKeyCallback::IStoreUpgradedKeyCallback,
24 RemotelyProvisionedKey::RemotelyProvisionedKey,
Tri Voe8f04442022-12-21 08:53:56 -080025};
Tri Voe8f04442022-12-21 08:53:56 -080026use anyhow::{Context, Result};
Alice Wang849cfe42023-11-10 12:43:36 +000027use binder::{BinderFeatures, Interface, StatusCode, Strong};
Alice Wange66c3312023-11-07 12:41:42 +000028use message_macro::source_location_msg;
Tri Voe8f04442022-12-21 08:53:56 -080029use std::sync::Mutex;
Tri Vo437d0142023-01-18 16:43:49 -080030use std::time::Duration;
31use tokio::sync::oneshot;
32use tokio::time::timeout;
33
34// Normally, we block indefinitely when making calls outside of keystore and rely on watchdog to
35// report deadlocks. However, RKPD is mainline updatable. Also, calls to RKPD may wait on network
36// for certificates. So, we err on the side of caution and timeout instead.
37static RKPD_TIMEOUT: Duration = Duration::from_secs(10);
38
39fn tokio_rt() -> tokio::runtime::Runtime {
40 tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap()
41}
Tri Voe8f04442022-12-21 08:53:56 -080042
Alice Wang849cfe42023-11-10 12:43:36 +000043/// Errors occurred during the interaction with RKPD.
44#[derive(Debug, Clone, Copy, thiserror::Error, PartialEq, Eq)]
45pub enum Error {
46 /// An RKPD request gets cancelled.
47 #[error("An RKPD request gets cancelled")]
48 RequestCancelled,
49
50 /// Failed to get registration.
51 #[error("Failed to get registration")]
52 GetRegistrationFailed,
53
54 /// Failed to get key.
55 #[error("Failed to get key: {0:?}")]
56 GetKeyFailed(GetKeyErrorCode),
57
58 /// Failed to store upgraded key.
59 #[error("Failed to store upgraded key")]
60 StoreUpgradedKeyFailed,
61
62 /// Retryable timeout when waiting for a callback.
63 #[error("Retryable timeout when waiting for a callback")]
64 RetryableTimeout,
65
66 /// Timeout when waiting for a callback.
67 #[error("Timeout when waiting for a callback")]
68 Timeout,
69
70 /// Wraps a Binder status code.
71 #[error("Binder transaction error {0:?}")]
72 BinderTransaction(StatusCode),
73}
74
75impl From<StatusCode> for Error {
76 fn from(s: StatusCode) -> Self {
77 Self::BinderTransaction(s)
78 }
79}
80
Seth Moorea882c962023-01-09 16:55:10 -080081/// Thread-safe channel for sending a value once and only once. If a value has
82/// already been send, subsequent calls to send will noop.
83struct SafeSender<T> {
84 inner: Mutex<Option<oneshot::Sender<T>>>,
85}
86
87impl<T> SafeSender<T> {
88 fn new(sender: oneshot::Sender<T>) -> Self {
89 Self { inner: Mutex::new(Some(sender)) }
90 }
91
92 fn send(&self, value: T) {
93 if let Some(inner) = self.inner.lock().unwrap().take() {
Tri Vo0e5fe2c2023-02-15 17:02:06 -080094 // It's possible for the corresponding receiver to time out and be dropped. In this
95 // case send() will fail. This error is not actionable though, so only log the error.
96 if inner.send(value).is_err() {
97 log::error!("SafeSender::send() failed");
98 }
Seth Moorea882c962023-01-09 16:55:10 -080099 }
100 }
101}
Tri Voe8f04442022-12-21 08:53:56 -0800102
103struct GetRegistrationCallback {
Seth Moorea882c962023-01-09 16:55:10 -0800104 registration_tx: SafeSender<Result<binder::Strong<dyn IRegistration>>>,
Tri Voe8f04442022-12-21 08:53:56 -0800105}
106
107impl GetRegistrationCallback {
108 pub fn new_native_binder(
Seth Moorea882c962023-01-09 16:55:10 -0800109 registration_tx: oneshot::Sender<Result<binder::Strong<dyn IRegistration>>>,
Seth Moore613a1fd2023-01-11 10:42:26 -0800110 ) -> Strong<dyn IGetRegistrationCallback> {
Tri Voe8f04442022-12-21 08:53:56 -0800111 let result: Self =
Seth Moorea882c962023-01-09 16:55:10 -0800112 GetRegistrationCallback { registration_tx: SafeSender::new(registration_tx) };
Seth Moore613a1fd2023-01-11 10:42:26 -0800113 BnGetRegistrationCallback::new_binder(result, BinderFeatures::default())
Tri Voe8f04442022-12-21 08:53:56 -0800114 }
115}
116
117impl Interface for GetRegistrationCallback {}
118
119impl IGetRegistrationCallback for GetRegistrationCallback {
120 fn onSuccess(&self, registration: &Strong<dyn IRegistration>) -> binder::Result<()> {
Seth Moore613a1fd2023-01-11 10:42:26 -0800121 self.registration_tx.send(Ok(registration.clone()));
122 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800123 }
124 fn onCancel(&self) -> binder::Result<()> {
Seth Moore613a1fd2023-01-11 10:42:26 -0800125 log::warn!("IGetRegistrationCallback cancelled");
126 self.registration_tx.send(
Alice Wang849cfe42023-11-10 12:43:36 +0000127 Err(Error::RequestCancelled)
Alice Wange66c3312023-11-07 12:41:42 +0000128 .context(source_location_msg!("GetRegistrationCallback cancelled.")),
Seth Moore613a1fd2023-01-11 10:42:26 -0800129 );
130 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800131 }
Seth Moore484010a2023-01-31 11:22:26 -0800132 fn onError(&self, description: &str) -> binder::Result<()> {
Seth Moore484010a2023-01-31 11:22:26 -0800133 log::error!("IGetRegistrationCallback failed: '{description}'");
Alice Wang849cfe42023-11-10 12:43:36 +0000134 self.registration_tx.send(
135 Err(Error::GetRegistrationFailed)
136 .context(source_location_msg!("GetRegistrationCallback failed: {:?}", description)),
137 );
Seth Moore613a1fd2023-01-11 10:42:26 -0800138 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800139 }
140}
141
142/// Make a new connection to a IRegistration service.
Alice Wangbf6a6932023-11-07 11:47:12 +0000143async fn get_rkpd_registration(rpc_name: &str) -> Result<binder::Strong<dyn IRegistration>> {
Tri Voe8f04442022-12-21 08:53:56 -0800144 let remote_provisioning: Strong<dyn IRemoteProvisioning> =
Alice Wang849cfe42023-11-10 12:43:36 +0000145 binder::get_interface("remote_provisioning")
146 .map_err(Error::from)
Alice Wange66c3312023-11-07 12:41:42 +0000147 .context(source_location_msg!("Trying to connect to IRemoteProvisioning service."))?;
Tri Voe8f04442022-12-21 08:53:56 -0800148
Tri Voe8f04442022-12-21 08:53:56 -0800149 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800150 let cb = GetRegistrationCallback::new_native_binder(tx);
Tri Voe8f04442022-12-21 08:53:56 -0800151
152 remote_provisioning
Alice Wangbf6a6932023-11-07 11:47:12 +0000153 .getRegistration(rpc_name, &cb)
Alice Wange66c3312023-11-07 12:41:42 +0000154 .context(source_location_msg!("Trying to get registration."))?;
Tri Voe8f04442022-12-21 08:53:56 -0800155
Tri Vo437d0142023-01-18 16:43:49 -0800156 match timeout(RKPD_TIMEOUT, rx).await {
Alice Wang849cfe42023-11-10 12:43:36 +0000157 Err(e) => Err(Error::Timeout).context(source_location_msg!("Waiting for RKPD: {:?}", e)),
Tri Vo437d0142023-01-18 16:43:49 -0800158 Ok(v) => v.unwrap(),
159 }
Tri Voe8f04442022-12-21 08:53:56 -0800160}
161
Tri Voe8f04442022-12-21 08:53:56 -0800162struct GetKeyCallback {
Seth Moorea882c962023-01-09 16:55:10 -0800163 key_tx: SafeSender<Result<RemotelyProvisionedKey>>,
Tri Voe8f04442022-12-21 08:53:56 -0800164}
165
166impl GetKeyCallback {
Seth Moorea882c962023-01-09 16:55:10 -0800167 pub fn new_native_binder(
168 key_tx: oneshot::Sender<Result<RemotelyProvisionedKey>>,
Seth Moore613a1fd2023-01-11 10:42:26 -0800169 ) -> Strong<dyn IGetKeyCallback> {
Seth Moorea882c962023-01-09 16:55:10 -0800170 let result: Self = GetKeyCallback { key_tx: SafeSender::new(key_tx) };
Seth Moore613a1fd2023-01-11 10:42:26 -0800171 BnGetKeyCallback::new_binder(result, BinderFeatures::default())
Tri Voe8f04442022-12-21 08:53:56 -0800172 }
173}
174
175impl Interface for GetKeyCallback {}
176
177impl IGetKeyCallback for GetKeyCallback {
178 fn onSuccess(&self, key: &RemotelyProvisionedKey) -> binder::Result<()> {
Seth Moore613a1fd2023-01-11 10:42:26 -0800179 self.key_tx.send(Ok(RemotelyProvisionedKey {
180 keyBlob: key.keyBlob.clone(),
181 encodedCertChain: key.encodedCertChain.clone(),
182 }));
183 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800184 }
185 fn onCancel(&self) -> binder::Result<()> {
Seth Moore613a1fd2023-01-11 10:42:26 -0800186 log::warn!("IGetKeyCallback cancelled");
187 self.key_tx.send(
Alice Wang849cfe42023-11-10 12:43:36 +0000188 Err(Error::RequestCancelled).context(source_location_msg!("GetKeyCallback cancelled.")),
Seth Moore613a1fd2023-01-11 10:42:26 -0800189 );
190 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800191 }
Seth Moore484010a2023-01-31 11:22:26 -0800192 fn onError(&self, error: GetKeyErrorCode, description: &str) -> binder::Result<()> {
Seth Moore484010a2023-01-31 11:22:26 -0800193 log::error!("IGetKeyCallback failed: {description}");
Alice Wang849cfe42023-11-10 12:43:36 +0000194 self.key_tx.send(Err(Error::GetKeyFailed(error)).context(source_location_msg!(
Seth Moore484010a2023-01-31 11:22:26 -0800195 "GetKeyCallback failed: {:?} {:?}",
196 error,
197 description
198 )));
Seth Moore613a1fd2023-01-11 10:42:26 -0800199 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800200 }
201}
202
Tri Vo437d0142023-01-18 16:43:49 -0800203async fn get_rkpd_attestation_key_from_registration_async(
204 registration: &Strong<dyn IRegistration>,
205 caller_uid: u32,
206) -> Result<RemotelyProvisionedKey> {
207 let (tx, rx) = oneshot::channel();
208 let cb = GetKeyCallback::new_native_binder(tx);
209
210 registration
211 .getKey(caller_uid.try_into().unwrap(), &cb)
Alice Wange66c3312023-11-07 12:41:42 +0000212 .context(source_location_msg!("Trying to get key."))?;
Tri Vo437d0142023-01-18 16:43:49 -0800213
214 match timeout(RKPD_TIMEOUT, rx).await {
Tri Vo0e5fe2c2023-02-15 17:02:06 -0800215 Err(e) => {
216 // Make a best effort attempt to cancel the timed out request.
217 if let Err(e) = registration.cancelGetKey(&cb) {
218 log::error!("IRegistration::cancelGetKey failed: {:?}", e);
219 }
Alice Wang849cfe42023-11-10 12:43:36 +0000220 Err(Error::RetryableTimeout)
Alice Wange66c3312023-11-07 12:41:42 +0000221 .context(source_location_msg!("Waiting for RKPD key timed out: {:?}", e))
Tri Vo0e5fe2c2023-02-15 17:02:06 -0800222 }
Tri Vo437d0142023-01-18 16:43:49 -0800223 Ok(v) => v.unwrap(),
224 }
225}
226
Tri Voe8f04442022-12-21 08:53:56 -0800227async fn get_rkpd_attestation_key_async(
Alice Wangbf6a6932023-11-07 11:47:12 +0000228 rpc_name: &str,
Tri Voe8f04442022-12-21 08:53:56 -0800229 caller_uid: u32,
230) -> Result<RemotelyProvisionedKey> {
Alice Wangbf6a6932023-11-07 11:47:12 +0000231 let registration = get_rkpd_registration(rpc_name)
Tri Voe8f04442022-12-21 08:53:56 -0800232 .await
Alice Wange66c3312023-11-07 12:41:42 +0000233 .context(source_location_msg!("Trying to get to IRegistration service."))?;
Tri Vo437d0142023-01-18 16:43:49 -0800234 get_rkpd_attestation_key_from_registration_async(&registration, caller_uid).await
Tri Voe8f04442022-12-21 08:53:56 -0800235}
236
Seth Moorea55428e2023-01-10 13:07:31 -0800237struct StoreUpgradedKeyCallback {
238 completer: SafeSender<Result<()>>,
239}
240
241impl StoreUpgradedKeyCallback {
242 pub fn new_native_binder(
243 completer: oneshot::Sender<Result<()>>,
Seth Moore613a1fd2023-01-11 10:42:26 -0800244 ) -> Strong<dyn IStoreUpgradedKeyCallback> {
Seth Moorea55428e2023-01-10 13:07:31 -0800245 let result: Self = StoreUpgradedKeyCallback { completer: SafeSender::new(completer) };
Seth Moore613a1fd2023-01-11 10:42:26 -0800246 BnStoreUpgradedKeyCallback::new_binder(result, BinderFeatures::default())
Seth Moorea55428e2023-01-10 13:07:31 -0800247 }
248}
249
250impl Interface for StoreUpgradedKeyCallback {}
251
252impl IStoreUpgradedKeyCallback for StoreUpgradedKeyCallback {
253 fn onSuccess(&self) -> binder::Result<()> {
Seth Moore613a1fd2023-01-11 10:42:26 -0800254 self.completer.send(Ok(()));
255 Ok(())
Seth Moorea55428e2023-01-10 13:07:31 -0800256 }
257
258 fn onError(&self, error: &str) -> binder::Result<()> {
Alice Wang849cfe42023-11-10 12:43:36 +0000259 log::error!("IStoreUpgradedKeyCallback failed: {error}");
Seth Moore613a1fd2023-01-11 10:42:26 -0800260 self.completer.send(
Alice Wang849cfe42023-11-10 12:43:36 +0000261 Err(Error::StoreUpgradedKeyFailed)
Alice Wange66c3312023-11-07 12:41:42 +0000262 .context(source_location_msg!("Failed to store upgraded key: {:?}", error)),
Seth Moore613a1fd2023-01-11 10:42:26 -0800263 );
264 Ok(())
Seth Moorea55428e2023-01-10 13:07:31 -0800265 }
266}
267
Tri Vo437d0142023-01-18 16:43:49 -0800268async fn store_rkpd_attestation_key_with_registration_async(
269 registration: &Strong<dyn IRegistration>,
270 key_blob: &[u8],
271 upgraded_blob: &[u8],
272) -> Result<()> {
273 let (tx, rx) = oneshot::channel();
274 let cb = StoreUpgradedKeyCallback::new_native_binder(tx);
275
276 registration
277 .storeUpgradedKeyAsync(key_blob, upgraded_blob, &cb)
Alice Wange66c3312023-11-07 12:41:42 +0000278 .context(source_location_msg!("Failed to store upgraded blob with RKPD."))?;
Tri Vo437d0142023-01-18 16:43:49 -0800279
280 match timeout(RKPD_TIMEOUT, rx).await {
Alice Wang849cfe42023-11-10 12:43:36 +0000281 Err(e) => Err(Error::Timeout)
Alice Wange66c3312023-11-07 12:41:42 +0000282 .context(source_location_msg!("Waiting for RKPD to complete storing key: {:?}", e)),
Tri Vo437d0142023-01-18 16:43:49 -0800283 Ok(v) => v.unwrap(),
284 }
285}
286
Tri Voe8f04442022-12-21 08:53:56 -0800287async fn store_rkpd_attestation_key_async(
Alice Wangbf6a6932023-11-07 11:47:12 +0000288 rpc_name: &str,
Tri Voe8f04442022-12-21 08:53:56 -0800289 key_blob: &[u8],
290 upgraded_blob: &[u8],
291) -> Result<()> {
Alice Wangbf6a6932023-11-07 11:47:12 +0000292 let registration = get_rkpd_registration(rpc_name)
Tri Voe8f04442022-12-21 08:53:56 -0800293 .await
Alice Wange66c3312023-11-07 12:41:42 +0000294 .context(source_location_msg!("Trying to get to IRegistration service."))?;
Tri Vo437d0142023-01-18 16:43:49 -0800295 store_rkpd_attestation_key_with_registration_async(&registration, key_blob, upgraded_blob).await
Tri Voe8f04442022-12-21 08:53:56 -0800296}
297
298/// Get attestation key from RKPD.
Alice Wangbf6a6932023-11-07 11:47:12 +0000299pub fn get_rkpd_attestation_key(rpc_name: &str, caller_uid: u32) -> Result<RemotelyProvisionedKey> {
Alice Wangbf6a6932023-11-07 11:47:12 +0000300 tokio_rt().block_on(get_rkpd_attestation_key_async(rpc_name, caller_uid))
Tri Voe8f04442022-12-21 08:53:56 -0800301}
302
303/// Store attestation key in RKPD.
304pub fn store_rkpd_attestation_key(
Alice Wangbf6a6932023-11-07 11:47:12 +0000305 rpc_name: &str,
Tri Voe8f04442022-12-21 08:53:56 -0800306 key_blob: &[u8],
307 upgraded_blob: &[u8],
308) -> Result<()> {
Alice Wangbf6a6932023-11-07 11:47:12 +0000309 tokio_rt().block_on(store_rkpd_attestation_key_async(rpc_name, key_blob, upgraded_blob))
Tri Voe8f04442022-12-21 08:53:56 -0800310}
311
312#[cfg(test)]
David Drysdale2566fb32024-07-09 14:46:37 +0100313mod tests;