blob: bfc7847c22c64a2528c10a11c051d2e0a6f126b5 [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.
Tri Vo437d0142023-01-18 16:43:49 -080016// TODO(b/264891956): Return RKP specific errors.
Tri Voe8f04442022-12-21 08:53:56 -080017
Tri Vo437d0142023-01-18 16:43:49 -080018use crate::error::{map_binder_status_code, Error};
Tri Voe8f04442022-12-21 08:53:56 -080019use crate::globals::get_remotely_provisioned_component_name;
20use crate::ks_err;
21use crate::utils::watchdog as wd;
22use android_hardware_security_keymint::aidl::android::hardware::security::keymint::SecurityLevel::SecurityLevel;
23use android_security_rkp_aidl::aidl::android::security::rkp::{
24 IGetKeyCallback::BnGetKeyCallback, IGetKeyCallback::IGetKeyCallback,
25 IGetRegistrationCallback::BnGetRegistrationCallback,
26 IGetRegistrationCallback::IGetRegistrationCallback, IRegistration::IRegistration,
Seth Moorea55428e2023-01-10 13:07:31 -080027 IRemoteProvisioning::IRemoteProvisioning,
28 IStoreUpgradedKeyCallback::BnStoreUpgradedKeyCallback,
29 IStoreUpgradedKeyCallback::IStoreUpgradedKeyCallback,
30 RemotelyProvisionedKey::RemotelyProvisionedKey,
Tri Voe8f04442022-12-21 08:53:56 -080031};
32use android_security_rkp_aidl::binder::{BinderFeatures, Interface, Strong};
Tri Vo437d0142023-01-18 16:43:49 -080033use android_system_keystore2::aidl::android::system::keystore2::ResponseCode::ResponseCode;
Tri Voe8f04442022-12-21 08:53:56 -080034use anyhow::{Context, Result};
Tri Voe8f04442022-12-21 08:53:56 -080035use std::sync::Mutex;
Tri Vo437d0142023-01-18 16:43:49 -080036use std::time::Duration;
37use tokio::sync::oneshot;
38use tokio::time::timeout;
39
40// Normally, we block indefinitely when making calls outside of keystore and rely on watchdog to
41// report deadlocks. However, RKPD is mainline updatable. Also, calls to RKPD may wait on network
42// for certificates. So, we err on the side of caution and timeout instead.
43static RKPD_TIMEOUT: Duration = Duration::from_secs(10);
44
45fn tokio_rt() -> tokio::runtime::Runtime {
46 tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap()
47}
Tri Voe8f04442022-12-21 08:53:56 -080048
Seth Moorea882c962023-01-09 16:55:10 -080049/// Thread-safe channel for sending a value once and only once. If a value has
50/// already been send, subsequent calls to send will noop.
51struct SafeSender<T> {
52 inner: Mutex<Option<oneshot::Sender<T>>>,
53}
54
55impl<T> SafeSender<T> {
56 fn new(sender: oneshot::Sender<T>) -> Self {
57 Self { inner: Mutex::new(Some(sender)) }
58 }
59
60 fn send(&self, value: T) {
61 if let Some(inner) = self.inner.lock().unwrap().take() {
62 // assert instead of unwrap, because on failure send returns Err(value)
63 assert!(inner.send(value).is_ok(), "thread state is terminally broken");
64 }
65 }
66}
Tri Voe8f04442022-12-21 08:53:56 -080067
68struct GetRegistrationCallback {
Seth Moorea882c962023-01-09 16:55:10 -080069 registration_tx: SafeSender<Result<binder::Strong<dyn IRegistration>>>,
Tri Voe8f04442022-12-21 08:53:56 -080070}
71
72impl GetRegistrationCallback {
73 pub fn new_native_binder(
Seth Moorea882c962023-01-09 16:55:10 -080074 registration_tx: oneshot::Sender<Result<binder::Strong<dyn IRegistration>>>,
Seth Moore613a1fd2023-01-11 10:42:26 -080075 ) -> Strong<dyn IGetRegistrationCallback> {
Tri Voe8f04442022-12-21 08:53:56 -080076 let result: Self =
Seth Moorea882c962023-01-09 16:55:10 -080077 GetRegistrationCallback { registration_tx: SafeSender::new(registration_tx) };
Seth Moore613a1fd2023-01-11 10:42:26 -080078 BnGetRegistrationCallback::new_binder(result, BinderFeatures::default())
Tri Voe8f04442022-12-21 08:53:56 -080079 }
80}
81
82impl Interface for GetRegistrationCallback {}
83
84impl IGetRegistrationCallback for GetRegistrationCallback {
85 fn onSuccess(&self, registration: &Strong<dyn IRegistration>) -> binder::Result<()> {
86 let _wp = wd::watch_millis("IGetRegistrationCallback::onSuccess", 500);
Seth Moore613a1fd2023-01-11 10:42:26 -080087 self.registration_tx.send(Ok(registration.clone()));
88 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -080089 }
90 fn onCancel(&self) -> binder::Result<()> {
91 let _wp = wd::watch_millis("IGetRegistrationCallback::onCancel", 500);
Seth Moore613a1fd2023-01-11 10:42:26 -080092 log::warn!("IGetRegistrationCallback cancelled");
93 self.registration_tx.send(
Tri Vo437d0142023-01-18 16:43:49 -080094 Err(Error::Rc(ResponseCode::OUT_OF_KEYS))
Seth Moore613a1fd2023-01-11 10:42:26 -080095 .context(ks_err!("GetRegistrationCallback cancelled.")),
96 );
97 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -080098 }
99 fn onError(&self, error: &str) -> binder::Result<()> {
100 let _wp = wd::watch_millis("IGetRegistrationCallback::onError", 500);
Seth Moore613a1fd2023-01-11 10:42:26 -0800101 log::error!("IGetRegistrationCallback failed: '{error}'");
102 self.registration_tx.send(
Tri Vo437d0142023-01-18 16:43:49 -0800103 Err(Error::Rc(ResponseCode::OUT_OF_KEYS))
Seth Moore613a1fd2023-01-11 10:42:26 -0800104 .context(ks_err!("GetRegistrationCallback failed: {:?}", error)),
105 );
106 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800107 }
108}
109
110/// Make a new connection to a IRegistration service.
111async fn get_rkpd_registration(
112 security_level: &SecurityLevel,
113) -> Result<binder::Strong<dyn IRegistration>> {
114 let remote_provisioning: Strong<dyn IRemoteProvisioning> =
115 map_binder_status_code(binder::get_interface("remote_provisioning"))
116 .context(ks_err!("Trying to connect to IRemoteProvisioning service."))?;
117
118 let rpc_name = get_remotely_provisioned_component_name(security_level)
119 .context(ks_err!("Trying to get IRPC name."))?;
120
121 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800122 let cb = GetRegistrationCallback::new_native_binder(tx);
Tri Voe8f04442022-12-21 08:53:56 -0800123
124 remote_provisioning
125 .getRegistration(&rpc_name, &cb)
126 .context(ks_err!("Trying to get registration."))?;
127
Tri Vo437d0142023-01-18 16:43:49 -0800128 match timeout(RKPD_TIMEOUT, rx).await {
129 Err(e) => {
130 Err(Error::Rc(ResponseCode::SYSTEM_ERROR)).context(ks_err!("Waiting for RKPD: {:?}", e))
131 }
132 Ok(v) => v.unwrap(),
133 }
Tri Voe8f04442022-12-21 08:53:56 -0800134}
135
Tri Voe8f04442022-12-21 08:53:56 -0800136struct GetKeyCallback {
Seth Moorea882c962023-01-09 16:55:10 -0800137 key_tx: SafeSender<Result<RemotelyProvisionedKey>>,
Tri Voe8f04442022-12-21 08:53:56 -0800138}
139
140impl GetKeyCallback {
Seth Moorea882c962023-01-09 16:55:10 -0800141 pub fn new_native_binder(
142 key_tx: oneshot::Sender<Result<RemotelyProvisionedKey>>,
Seth Moore613a1fd2023-01-11 10:42:26 -0800143 ) -> Strong<dyn IGetKeyCallback> {
Seth Moorea882c962023-01-09 16:55:10 -0800144 let result: Self = GetKeyCallback { key_tx: SafeSender::new(key_tx) };
Seth Moore613a1fd2023-01-11 10:42:26 -0800145 BnGetKeyCallback::new_binder(result, BinderFeatures::default())
Tri Voe8f04442022-12-21 08:53:56 -0800146 }
147}
148
149impl Interface for GetKeyCallback {}
150
151impl IGetKeyCallback for GetKeyCallback {
152 fn onSuccess(&self, key: &RemotelyProvisionedKey) -> binder::Result<()> {
153 let _wp = wd::watch_millis("IGetKeyCallback::onSuccess", 500);
Seth Moore613a1fd2023-01-11 10:42:26 -0800154 self.key_tx.send(Ok(RemotelyProvisionedKey {
155 keyBlob: key.keyBlob.clone(),
156 encodedCertChain: key.encodedCertChain.clone(),
157 }));
158 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800159 }
160 fn onCancel(&self) -> binder::Result<()> {
161 let _wp = wd::watch_millis("IGetKeyCallback::onCancel", 500);
Seth Moore613a1fd2023-01-11 10:42:26 -0800162 log::warn!("IGetKeyCallback cancelled");
163 self.key_tx.send(
Tri Vo437d0142023-01-18 16:43:49 -0800164 Err(Error::Rc(ResponseCode::OUT_OF_KEYS)).context(ks_err!("GetKeyCallback cancelled.")),
Seth Moore613a1fd2023-01-11 10:42:26 -0800165 );
166 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800167 }
168 fn onError(&self, error: &str) -> binder::Result<()> {
169 let _wp = wd::watch_millis("IGetKeyCallback::onError", 500);
Seth Moore613a1fd2023-01-11 10:42:26 -0800170 log::error!("IGetKeyCallback failed: {error}");
171 self.key_tx.send(
Tri Vo437d0142023-01-18 16:43:49 -0800172 Err(Error::Rc(ResponseCode::OUT_OF_KEYS))
Seth Moore613a1fd2023-01-11 10:42:26 -0800173 .context(ks_err!("GetKeyCallback failed: {:?}", error)),
174 );
175 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800176 }
177}
178
Tri Vo437d0142023-01-18 16:43:49 -0800179async fn get_rkpd_attestation_key_from_registration_async(
180 registration: &Strong<dyn IRegistration>,
181 caller_uid: u32,
182) -> Result<RemotelyProvisionedKey> {
183 let (tx, rx) = oneshot::channel();
184 let cb = GetKeyCallback::new_native_binder(tx);
185
186 registration
187 .getKey(caller_uid.try_into().unwrap(), &cb)
188 .context(ks_err!("Trying to get key."))?;
189
190 match timeout(RKPD_TIMEOUT, rx).await {
191 Err(e) => Err(Error::Rc(ResponseCode::OUT_OF_KEYS))
192 .context(ks_err!("Waiting for RKPD key timed out: {:?}", e)),
193 Ok(v) => v.unwrap(),
194 }
195}
196
Tri Voe8f04442022-12-21 08:53:56 -0800197async fn get_rkpd_attestation_key_async(
198 security_level: &SecurityLevel,
199 caller_uid: u32,
200) -> Result<RemotelyProvisionedKey> {
201 let registration = get_rkpd_registration(security_level)
202 .await
203 .context(ks_err!("Trying to get to IRegistration service."))?;
Tri Vo437d0142023-01-18 16:43:49 -0800204 get_rkpd_attestation_key_from_registration_async(&registration, caller_uid).await
Tri Voe8f04442022-12-21 08:53:56 -0800205}
206
Seth Moorea55428e2023-01-10 13:07:31 -0800207struct StoreUpgradedKeyCallback {
208 completer: SafeSender<Result<()>>,
209}
210
211impl StoreUpgradedKeyCallback {
212 pub fn new_native_binder(
213 completer: oneshot::Sender<Result<()>>,
Seth Moore613a1fd2023-01-11 10:42:26 -0800214 ) -> Strong<dyn IStoreUpgradedKeyCallback> {
Seth Moorea55428e2023-01-10 13:07:31 -0800215 let result: Self = StoreUpgradedKeyCallback { completer: SafeSender::new(completer) };
Seth Moore613a1fd2023-01-11 10:42:26 -0800216 BnStoreUpgradedKeyCallback::new_binder(result, BinderFeatures::default())
Seth Moorea55428e2023-01-10 13:07:31 -0800217 }
218}
219
220impl Interface for StoreUpgradedKeyCallback {}
221
222impl IStoreUpgradedKeyCallback for StoreUpgradedKeyCallback {
223 fn onSuccess(&self) -> binder::Result<()> {
224 let _wp = wd::watch_millis("IGetRegistrationCallback::onSuccess", 500);
Seth Moore613a1fd2023-01-11 10:42:26 -0800225 self.completer.send(Ok(()));
226 Ok(())
Seth Moorea55428e2023-01-10 13:07:31 -0800227 }
228
229 fn onError(&self, error: &str) -> binder::Result<()> {
230 let _wp = wd::watch_millis("IGetRegistrationCallback::onError", 500);
Seth Moore613a1fd2023-01-11 10:42:26 -0800231 log::error!("IGetRegistrationCallback failed: {error}");
232 self.completer.send(
Tri Vo437d0142023-01-18 16:43:49 -0800233 Err(Error::Rc(ResponseCode::SYSTEM_ERROR))
Seth Moore613a1fd2023-01-11 10:42:26 -0800234 .context(ks_err!("Failed to store upgraded key: {:?}", error)),
235 );
236 Ok(())
Seth Moorea55428e2023-01-10 13:07:31 -0800237 }
238}
239
Tri Vo437d0142023-01-18 16:43:49 -0800240async fn store_rkpd_attestation_key_with_registration_async(
241 registration: &Strong<dyn IRegistration>,
242 key_blob: &[u8],
243 upgraded_blob: &[u8],
244) -> Result<()> {
245 let (tx, rx) = oneshot::channel();
246 let cb = StoreUpgradedKeyCallback::new_native_binder(tx);
247
248 registration
249 .storeUpgradedKeyAsync(key_blob, upgraded_blob, &cb)
250 .context(ks_err!("Failed to store upgraded blob with RKPD."))?;
251
252 match timeout(RKPD_TIMEOUT, rx).await {
253 Err(e) => Err(Error::Rc(ResponseCode::SYSTEM_ERROR))
254 .context(ks_err!("Waiting for RKPD to complete storing key: {:?}", e)),
255 Ok(v) => v.unwrap(),
256 }
257}
258
Tri Voe8f04442022-12-21 08:53:56 -0800259async fn store_rkpd_attestation_key_async(
260 security_level: &SecurityLevel,
261 key_blob: &[u8],
262 upgraded_blob: &[u8],
263) -> Result<()> {
264 let registration = get_rkpd_registration(security_level)
265 .await
266 .context(ks_err!("Trying to get to IRegistration service."))?;
Tri Vo437d0142023-01-18 16:43:49 -0800267 store_rkpd_attestation_key_with_registration_async(&registration, key_blob, upgraded_blob).await
Tri Voe8f04442022-12-21 08:53:56 -0800268}
269
270/// Get attestation key from RKPD.
271pub fn get_rkpd_attestation_key(
272 security_level: &SecurityLevel,
273 caller_uid: u32,
274) -> Result<RemotelyProvisionedKey> {
275 let _wp = wd::watch_millis("Calling get_rkpd_attestation_key()", 500);
Tri Vo437d0142023-01-18 16:43:49 -0800276 tokio_rt().block_on(get_rkpd_attestation_key_async(security_level, caller_uid))
Tri Voe8f04442022-12-21 08:53:56 -0800277}
278
279/// Store attestation key in RKPD.
280pub fn store_rkpd_attestation_key(
281 security_level: &SecurityLevel,
282 key_blob: &[u8],
283 upgraded_blob: &[u8],
284) -> Result<()> {
285 let _wp = wd::watch_millis("Calling store_rkpd_attestation_key()", 500);
Tri Vo437d0142023-01-18 16:43:49 -0800286 tokio_rt().block_on(store_rkpd_attestation_key_async(security_level, key_blob, upgraded_blob))
Tri Voe8f04442022-12-21 08:53:56 -0800287}
288
289#[cfg(test)]
290mod tests {
291 use super::*;
Tri Vo30268da2023-01-24 15:35:45 -0800292 use crate::error::map_km_error;
293 use crate::globals::get_keymint_device;
294 use crate::utils::upgrade_keyblob_if_required_with;
295 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
296 Algorithm::Algorithm, AttestationKey::AttestationKey, KeyParameter::KeyParameter,
297 KeyParameterValue::KeyParameterValue, Tag::Tag,
298 };
Tri Voe8f04442022-12-21 08:53:56 -0800299 use android_security_rkp_aidl::aidl::android::security::rkp::IRegistration::BnRegistration;
Tri Vo30268da2023-01-24 15:35:45 -0800300 use keystore2_crypto::parse_subject_from_certificate;
Tri Vo4b1cd822023-01-23 13:05:35 -0800301 use std::sync::atomic::{AtomicU32, Ordering};
Tri Voe8f04442022-12-21 08:53:56 -0800302
303 #[derive(Default)]
Tri Vo437d0142023-01-18 16:43:49 -0800304 struct MockRegistration {
305 key: RemotelyProvisionedKey,
306 latency: Option<Duration>,
Tri Voe8f04442022-12-21 08:53:56 -0800307 }
308
Tri Voe8f04442022-12-21 08:53:56 -0800309 impl MockRegistration {
Tri Vo437d0142023-01-18 16:43:49 -0800310 pub fn new_native_binder(
311 key: &RemotelyProvisionedKey,
312 latency: Option<Duration>,
313 ) -> Strong<dyn IRegistration> {
314 let result = Self {
315 key: RemotelyProvisionedKey {
316 keyBlob: key.keyBlob.clone(),
317 encodedCertChain: key.encodedCertChain.clone(),
318 },
319 latency,
320 };
Tri Voe8f04442022-12-21 08:53:56 -0800321 BnRegistration::new_binder(result, BinderFeatures::default())
322 }
323 }
324
325 impl Interface for MockRegistration {}
326
327 impl IRegistration for MockRegistration {
Tri Vo437d0142023-01-18 16:43:49 -0800328 fn getKey(&self, _: i32, cb: &Strong<dyn IGetKeyCallback>) -> binder::Result<()> {
329 let key = RemotelyProvisionedKey {
330 keyBlob: self.key.keyBlob.clone(),
331 encodedCertChain: self.key.encodedCertChain.clone(),
332 };
333 let latency = self.latency;
334 let get_key_cb = cb.clone();
335
336 // Need a separate thread to trigger timeout in the caller.
337 std::thread::spawn(move || {
338 if let Some(duration) = latency {
339 std::thread::sleep(duration);
340 }
341 get_key_cb.onSuccess(&key).unwrap();
342 });
343 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800344 }
345
346 fn cancelGetKey(&self, _: &Strong<dyn IGetKeyCallback>) -> binder::Result<()> {
347 todo!()
348 }
349
Seth Moorea55428e2023-01-10 13:07:31 -0800350 fn storeUpgradedKeyAsync(
351 &self,
352 _: &[u8],
353 _: &[u8],
Tri Vo437d0142023-01-18 16:43:49 -0800354 cb: &Strong<dyn IStoreUpgradedKeyCallback>,
Seth Moorea55428e2023-01-10 13:07:31 -0800355 ) -> binder::Result<()> {
Tri Vo437d0142023-01-18 16:43:49 -0800356 // We are primarily concerned with timing out correctly. Storing the key in this mock
357 // registration isn't particularly interesting, so skip that part.
358 let store_cb = cb.clone();
359 let latency = self.latency;
360
361 std::thread::spawn(move || {
362 if let Some(duration) = latency {
363 std::thread::sleep(duration);
364 }
365 store_cb.onSuccess().unwrap();
366 });
367 Ok(())
Tri Voe8f04442022-12-21 08:53:56 -0800368 }
369 }
370
Tri Vo437d0142023-01-18 16:43:49 -0800371 fn get_mock_registration(
372 key: &RemotelyProvisionedKey,
373 latency: Option<Duration>,
374 ) -> Result<binder::Strong<dyn IRegistration>> {
Tri Voe8f04442022-12-21 08:53:56 -0800375 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800376 let cb = GetRegistrationCallback::new_native_binder(tx);
Tri Vo437d0142023-01-18 16:43:49 -0800377 let mock_registration = MockRegistration::new_native_binder(key, latency);
Tri Voe8f04442022-12-21 08:53:56 -0800378
379 assert!(cb.onSuccess(&mock_registration).is_ok());
Tri Vo437d0142023-01-18 16:43:49 -0800380 tokio_rt().block_on(rx).unwrap()
Tri Voe8f04442022-12-21 08:53:56 -0800381 }
382
Tri Vo4b1cd822023-01-23 13:05:35 -0800383 // Using the same key ID makes test cases race with each other. So, we use separate key IDs for
384 // different test cases.
385 fn get_next_key_id() -> u32 {
386 static ID: AtomicU32 = AtomicU32::new(0);
387 ID.fetch_add(1, Ordering::Relaxed)
388 }
389
Tri Voe8f04442022-12-21 08:53:56 -0800390 #[test]
391 fn test_get_registration_cb_success() {
Tri Vo437d0142023-01-18 16:43:49 -0800392 let key: RemotelyProvisionedKey = Default::default();
393 let registration = get_mock_registration(&key, /*latency=*/ None);
Tri Voe8f04442022-12-21 08:53:56 -0800394 assert!(registration.is_ok());
395 }
396
397 #[test]
398 fn test_get_registration_cb_cancel() {
399 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800400 let cb = GetRegistrationCallback::new_native_binder(tx);
Tri Voe8f04442022-12-21 08:53:56 -0800401 assert!(cb.onCancel().is_ok());
402
Tri Vo437d0142023-01-18 16:43:49 -0800403 let result = tokio_rt().block_on(rx).unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800404 assert_eq!(
405 result.unwrap_err().downcast::<Error>().unwrap(),
Tri Vo437d0142023-01-18 16:43:49 -0800406 Error::Rc(ResponseCode::OUT_OF_KEYS)
Tri Voe8f04442022-12-21 08:53:56 -0800407 );
408 }
409
410 #[test]
411 fn test_get_registration_cb_error() {
412 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800413 let cb = GetRegistrationCallback::new_native_binder(tx);
Tri Voe8f04442022-12-21 08:53:56 -0800414 assert!(cb.onError("error").is_ok());
415
Tri Vo437d0142023-01-18 16:43:49 -0800416 let result = tokio_rt().block_on(rx).unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800417 assert_eq!(
418 result.unwrap_err().downcast::<Error>().unwrap(),
Tri Vo437d0142023-01-18 16:43:49 -0800419 Error::Rc(ResponseCode::OUT_OF_KEYS)
Tri Voe8f04442022-12-21 08:53:56 -0800420 );
421 }
422
423 #[test]
424 fn test_get_key_cb_success() {
425 let mock_key =
426 RemotelyProvisionedKey { keyBlob: vec![1, 2, 3], encodedCertChain: vec![4, 5, 6] };
427 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800428 let cb = GetKeyCallback::new_native_binder(tx);
Tri Voe8f04442022-12-21 08:53:56 -0800429 assert!(cb.onSuccess(&mock_key).is_ok());
430
Tri Vo437d0142023-01-18 16:43:49 -0800431 let key = tokio_rt().block_on(rx).unwrap().unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800432 assert_eq!(key, mock_key);
433 }
434
435 #[test]
436 fn test_get_key_cb_cancel() {
437 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800438 let cb = GetKeyCallback::new_native_binder(tx);
Tri Voe8f04442022-12-21 08:53:56 -0800439 assert!(cb.onCancel().is_ok());
440
Tri Vo437d0142023-01-18 16:43:49 -0800441 let result = tokio_rt().block_on(rx).unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800442 assert_eq!(
443 result.unwrap_err().downcast::<Error>().unwrap(),
Tri Vo437d0142023-01-18 16:43:49 -0800444 Error::Rc(ResponseCode::OUT_OF_KEYS)
Tri Voe8f04442022-12-21 08:53:56 -0800445 );
446 }
447
448 #[test]
449 fn test_get_key_cb_error() {
450 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800451 let cb = GetKeyCallback::new_native_binder(tx);
Tri Voe8f04442022-12-21 08:53:56 -0800452 assert!(cb.onError("error").is_ok());
453
Tri Vo437d0142023-01-18 16:43:49 -0800454 let result = tokio_rt().block_on(rx).unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800455 assert_eq!(
456 result.unwrap_err().downcast::<Error>().unwrap(),
Tri Vo437d0142023-01-18 16:43:49 -0800457 Error::Rc(ResponseCode::OUT_OF_KEYS)
Tri Voe8f04442022-12-21 08:53:56 -0800458 );
459 }
460
461 #[test]
Seth Moore613a1fd2023-01-11 10:42:26 -0800462 fn test_store_upgraded_cb_success() {
Seth Moorea55428e2023-01-10 13:07:31 -0800463 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800464 let cb = StoreUpgradedKeyCallback::new_native_binder(tx);
Seth Moorea55428e2023-01-10 13:07:31 -0800465 assert!(cb.onSuccess().is_ok());
466
Tri Vo437d0142023-01-18 16:43:49 -0800467 tokio_rt().block_on(rx).unwrap().unwrap();
Seth Moorea55428e2023-01-10 13:07:31 -0800468 }
469
470 #[test]
471 fn test_store_upgraded_key_cb_error() {
472 let (tx, rx) = oneshot::channel();
Seth Moore613a1fd2023-01-11 10:42:26 -0800473 let cb = StoreUpgradedKeyCallback::new_native_binder(tx);
Seth Moorea55428e2023-01-10 13:07:31 -0800474 assert!(cb.onError("oh no! it failed").is_ok());
475
Tri Vo437d0142023-01-18 16:43:49 -0800476 let result = tokio_rt().block_on(rx).unwrap();
Seth Moorea55428e2023-01-10 13:07:31 -0800477 assert_eq!(
478 result.unwrap_err().downcast::<Error>().unwrap(),
Tri Vo437d0142023-01-18 16:43:49 -0800479 Error::Rc(ResponseCode::SYSTEM_ERROR)
480 );
481 }
482
483 #[test]
484 fn test_get_mock_key_success() {
485 let mock_key =
486 RemotelyProvisionedKey { keyBlob: vec![1, 2, 3], encodedCertChain: vec![4, 5, 6] };
487 let registration = get_mock_registration(&mock_key, /*latency=*/ None).unwrap();
488
489 let key = tokio_rt()
490 .block_on(get_rkpd_attestation_key_from_registration_async(&registration, 0))
491 .unwrap();
492 assert_eq!(key, mock_key);
493 }
494
495 #[test]
496 fn test_get_mock_key_timeout() {
497 let mock_key =
498 RemotelyProvisionedKey { keyBlob: vec![1, 2, 3], encodedCertChain: vec![4, 5, 6] };
499 let latency = RKPD_TIMEOUT + Duration::from_secs(10);
500 let registration = get_mock_registration(&mock_key, Some(latency)).unwrap();
501
502 let result =
503 tokio_rt().block_on(get_rkpd_attestation_key_from_registration_async(&registration, 0));
504 assert_eq!(
505 result.unwrap_err().downcast::<Error>().unwrap(),
506 Error::Rc(ResponseCode::OUT_OF_KEYS)
507 );
508 }
509
510 #[test]
511 fn test_store_mock_key_success() {
512 let mock_key =
513 RemotelyProvisionedKey { keyBlob: vec![1, 2, 3], encodedCertChain: vec![4, 5, 6] };
514 let registration = get_mock_registration(&mock_key, /*latency=*/ None).unwrap();
515 tokio_rt()
516 .block_on(store_rkpd_attestation_key_with_registration_async(&registration, &[], &[]))
517 .unwrap();
518 }
519
520 #[test]
521 fn test_store_mock_key_timeout() {
522 let mock_key =
523 RemotelyProvisionedKey { keyBlob: vec![1, 2, 3], encodedCertChain: vec![4, 5, 6] };
524 let latency = RKPD_TIMEOUT + Duration::from_secs(10);
525 let registration = get_mock_registration(&mock_key, Some(latency)).unwrap();
526
527 let result = tokio_rt().block_on(store_rkpd_attestation_key_with_registration_async(
528 &registration,
529 &[],
530 &[],
531 ));
532 assert_eq!(
533 result.unwrap_err().downcast::<Error>().unwrap(),
534 Error::Rc(ResponseCode::SYSTEM_ERROR)
Seth Moorea55428e2023-01-10 13:07:31 -0800535 );
536 }
537
538 #[test]
Tri Voe8f04442022-12-21 08:53:56 -0800539 fn test_get_rkpd_attestation_key() {
Seth Mooref896d362023-01-11 08:06:17 -0800540 binder::ProcessState::start_thread_pool();
Tri Vo437d0142023-01-18 16:43:49 -0800541 let key_id = get_next_key_id();
542 let key = get_rkpd_attestation_key(&SecurityLevel::TRUSTED_ENVIRONMENT, key_id).unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800543 assert!(!key.keyBlob.is_empty());
544 assert!(!key.encodedCertChain.is_empty());
545 }
546
547 #[test]
Tri Voe8f04442022-12-21 08:53:56 -0800548 fn test_get_rkpd_attestation_key_same_caller() {
Seth Mooref896d362023-01-11 08:06:17 -0800549 binder::ProcessState::start_thread_pool();
Tri Voe8f04442022-12-21 08:53:56 -0800550 let sec_level = SecurityLevel::TRUSTED_ENVIRONMENT;
Tri Vo4b1cd822023-01-23 13:05:35 -0800551 let key_id = get_next_key_id();
Tri Voe8f04442022-12-21 08:53:56 -0800552
553 // Multiple calls should return the same key.
Tri Vo4b1cd822023-01-23 13:05:35 -0800554 let first_key = get_rkpd_attestation_key(&sec_level, key_id).unwrap();
555 let second_key = get_rkpd_attestation_key(&sec_level, key_id).unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800556
557 assert_eq!(first_key.keyBlob, second_key.keyBlob);
558 assert_eq!(first_key.encodedCertChain, second_key.encodedCertChain);
559 }
560
561 #[test]
Tri Voe8f04442022-12-21 08:53:56 -0800562 fn test_get_rkpd_attestation_key_different_caller() {
Seth Mooref896d362023-01-11 08:06:17 -0800563 binder::ProcessState::start_thread_pool();
Tri Voe8f04442022-12-21 08:53:56 -0800564 let sec_level = SecurityLevel::TRUSTED_ENVIRONMENT;
Tri Vo4b1cd822023-01-23 13:05:35 -0800565 let first_key_id = get_next_key_id();
566 let second_key_id = get_next_key_id();
Tri Voe8f04442022-12-21 08:53:56 -0800567
568 // Different callers should be getting different keys.
Tri Vo4b1cd822023-01-23 13:05:35 -0800569 let first_key = get_rkpd_attestation_key(&sec_level, first_key_id).unwrap();
570 let second_key = get_rkpd_attestation_key(&sec_level, second_key_id).unwrap();
Tri Voe8f04442022-12-21 08:53:56 -0800571
572 assert_ne!(first_key.keyBlob, second_key.keyBlob);
573 assert_ne!(first_key.encodedCertChain, second_key.encodedCertChain);
574 }
575
576 #[test]
Tri Vobac3b522023-01-23 13:10:24 -0800577 // Couple of things to note:
578 // 1. This test must never run with UID of keystore. Otherwise, it can mess up keys stored by
579 // keystore.
580 // 2. Storing and reading the stored key is prone to race condition. So, we only do this in one
581 // test case.
Tri Voe8f04442022-12-21 08:53:56 -0800582 fn test_store_rkpd_attestation_key() {
Seth Mooref896d362023-01-11 08:06:17 -0800583 binder::ProcessState::start_thread_pool();
Tri Voe8f04442022-12-21 08:53:56 -0800584 let sec_level = SecurityLevel::TRUSTED_ENVIRONMENT;
Tri Vo4b1cd822023-01-23 13:05:35 -0800585 let key_id = get_next_key_id();
586 let key = get_rkpd_attestation_key(&SecurityLevel::TRUSTED_ENVIRONMENT, key_id).unwrap();
Tri Vobac3b522023-01-23 13:10:24 -0800587 let new_blob: [u8; 8] = rand::random();
Tri Voe8f04442022-12-21 08:53:56 -0800588
Tri Vobac3b522023-01-23 13:10:24 -0800589 assert!(store_rkpd_attestation_key(&sec_level, &key.keyBlob, &new_blob).is_ok());
590
591 let new_key =
592 get_rkpd_attestation_key(&SecurityLevel::TRUSTED_ENVIRONMENT, key_id).unwrap();
593 assert_eq!(new_key.keyBlob, new_blob);
Tri Voe8f04442022-12-21 08:53:56 -0800594 }
Tri Vo30268da2023-01-24 15:35:45 -0800595
596 #[test]
597 // This is a helper for a manual test. We want to check that after a system upgrade RKPD
598 // attestation keys can also be upgraded and stored again with RKPD. The steps are:
599 // 1. Run this test and check in stdout that no key upgrade happened.
600 // 2. Perform a system upgrade.
601 // 3. Run this test and check in stdout that key upgrade did happen.
602 //
603 // Note that this test must be run with that same UID every time. Running as root, i.e. UID 0,
604 // should do the trick. Also, use "--nocapture" flag to get stdout.
605 fn test_rkpd_attestation_key_upgrade() {
606 binder::ProcessState::start_thread_pool();
607 let security_level = SecurityLevel::TRUSTED_ENVIRONMENT;
608 let (keymint, _, _) = get_keymint_device(&security_level).unwrap();
609 let key_id = get_next_key_id();
610 let mut key_upgraded = false;
611
612 let key = get_rkpd_attestation_key(&security_level, key_id).unwrap();
613 assert!(!key.keyBlob.is_empty());
614 assert!(!key.encodedCertChain.is_empty());
615
616 upgrade_keyblob_if_required_with(
617 &*keymint,
618 &key.keyBlob,
619 /*upgrade_params=*/ &[],
620 /*km_op=*/
621 |blob| {
622 let params = vec![
623 KeyParameter {
624 tag: Tag::ALGORITHM,
625 value: KeyParameterValue::Algorithm(Algorithm::AES),
626 },
627 KeyParameter { tag: Tag::KEY_SIZE, value: KeyParameterValue::Integer(128) },
628 ];
629 let attestation_key = AttestationKey {
630 keyBlob: blob.to_vec(),
631 attestKeyParams: vec![],
632 issuerSubjectName: parse_subject_from_certificate(&key.encodedCertChain)
633 .unwrap(),
634 };
635
636 map_km_error(keymint.generateKey(&params, Some(&attestation_key)))
637 },
638 /*new_blob_handler=*/
639 |new_blob| {
640 // This handler is only executed if a key upgrade was performed.
641 key_upgraded = true;
642 store_rkpd_attestation_key(&security_level, &key.keyBlob, new_blob).unwrap();
643 Ok(())
644 },
645 )
646 .unwrap();
647
648 if key_upgraded {
649 println!("RKPD key was upgraded and stored with RKPD.");
650 } else {
651 println!("RKPD key was NOT upgraded.");
652 }
653 }
Tri Vo02f0fa42023-01-24 12:32:08 -0800654
655 #[test]
656 #[ignore] // b/266607003
657 fn test_stress_get_rkpd_attestation_key() {
658 binder::ProcessState::start_thread_pool();
659 let key_id = get_next_key_id();
660 let mut threads = vec![];
661 const NTHREADS: u32 = 10;
662 const NCALLS: u32 = 1000;
663
664 for _ in 0..NTHREADS {
665 threads.push(std::thread::spawn(move || {
666 for _ in 0..NCALLS {
667 let key = get_rkpd_attestation_key(&SecurityLevel::TRUSTED_ENVIRONMENT, key_id)
668 .unwrap();
669 assert!(!key.keyBlob.is_empty());
670 assert!(!key.encodedCertChain.is_empty());
671 }
672 }));
673 }
674
675 for t in threads {
676 assert!(t.join().is_ok());
677 }
678 }
Tri Voe8f04442022-12-21 08:53:56 -0800679}