Merge changes I26394509,I9d76a0ec,I88779273 into main
* changes:
keystore2: link to android.security flags library
keystore2: log super key creation
keystore2: factor out create_super_key()
diff --git a/keystore2/Android.bp b/keystore2/Android.bp
index 2e6eb17..e59b6f2 100644
--- a/keystore2/Android.bp
+++ b/keystore2/Android.bp
@@ -56,12 +56,14 @@
"liblibc",
"liblog_event_list",
"liblog_rust",
+ "libmessage_macro",
"librand",
"librustutils",
"libserde",
"libserde_cbor",
"libthiserror",
"libtokio",
+ "libwatchdog_rs",
],
shared_libs: [
"libcutils",
diff --git a/keystore2/TEST_MAPPING b/keystore2/TEST_MAPPING
index f8a1302..1038bea 100644
--- a/keystore2/TEST_MAPPING
+++ b/keystore2/TEST_MAPPING
@@ -33,6 +33,9 @@
},
{
"name": "keystore2_client_tests"
+ },
+ {
+ "name": "libwatchdog_rs.test"
}
]
}
diff --git a/keystore2/message_macro/Android.bp b/keystore2/message_macro/Android.bp
new file mode 100644
index 0000000..f1fbad7
--- /dev/null
+++ b/keystore2/message_macro/Android.bp
@@ -0,0 +1,37 @@
+// Copyright 2023, The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "system_security_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-Apache-2.0
+ default_applicable_licenses: ["system_security_license"],
+}
+
+rust_defaults {
+ name: "libmessage_macro_defaults",
+ crate_name: "message_macro",
+ srcs: ["src/lib.rs"],
+}
+
+rust_library {
+ name: "libmessage_macro",
+ defaults: ["libmessage_macro_defaults"],
+ apex_available: [
+ "//apex_available:platform",
+ "com.android.virt",
+ ],
+}
diff --git a/keystore2/src/ks_err.rs b/keystore2/message_macro/src/lib.rs
similarity index 76%
rename from keystore2/src/ks_err.rs
rename to keystore2/message_macro/src/lib.rs
index c9c38c0..d8cfab0 100644
--- a/keystore2/src/ks_err.rs
+++ b/keystore2/message_macro/src/lib.rs
@@ -12,20 +12,20 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-//! A ks_err macro that expands error messages to include the file and line number
+//! A macro that generates a message containing the current source file name
+//! and line number.
+/// Generates a message containing the current source file name and line number.
///
/// # Examples
///
/// ```
-/// use crate::ks_err;
-///
-/// ks_err!("Key is expired.");
+/// source_location_msg!("Key is expired.");
/// Result:
/// "src/lib.rs:7 Key is expired."
/// ```
#[macro_export]
-macro_rules! ks_err {
+macro_rules! source_location_msg {
{ $($arg:tt)+ } => {
format!("{}:{}: {}", file!(), line!(), format_args!($($arg)+))
};
diff --git a/keystore2/src/database.rs b/keystore2/src/database.rs
index 825a4b0..83963f9 100644
--- a/keystore2/src/database.rs
+++ b/keystore2/src/database.rs
@@ -5051,7 +5051,6 @@
for storage in increased_storage_types {
// Verify the expected storage increased.
let new = db.get_storage_stat(storage).unwrap();
- let storage = storage;
let old = &baseline[&storage.0];
assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
assert!(
diff --git a/keystore2/src/km_compat.rs b/keystore2/src/km_compat.rs
index f8673fb..cd58fe4 100644
--- a/keystore2/src/km_compat.rs
+++ b/keystore2/src/km_compat.rs
@@ -164,7 +164,7 @@
}
}
-impl<T> binder::Interface for BacklevelKeyMintWrapper<T> where T: EmulationDetector {}
+impl<T> binder::Interface for BacklevelKeyMintWrapper<T> where T: EmulationDetector + 'static {}
impl<T> IKeyMintDevice for BacklevelKeyMintWrapper<T>
where
diff --git a/keystore2/src/lib.rs b/keystore2/src/lib.rs
index 3233017..e51a319 100644
--- a/keystore2/src/lib.rs
+++ b/keystore2/src/lib.rs
@@ -28,7 +28,6 @@
pub mod id_rotation;
/// Internal Representation of Key Parameter and convenience functions.
pub mod key_parameter;
-pub mod ks_err;
pub mod legacy_blob;
pub mod legacy_importer;
pub mod maintenance;
@@ -50,6 +49,6 @@
mod km_compat;
mod super_key;
mod sw_keyblob;
+mod watchdog_helper;
-#[cfg(feature = "watchdog")]
-mod watchdog;
+use message_macro::source_location_msg as ks_err;
diff --git a/keystore2/src/remote_provisioning.rs b/keystore2/src/remote_provisioning.rs
index 811ad98..1e33ef1 100644
--- a/keystore2/src/remote_provisioning.rs
+++ b/keystore2/src/remote_provisioning.rs
@@ -31,6 +31,7 @@
use keystore2_crypto::parse_subject_from_certificate;
use crate::database::Uuid;
+use crate::globals::get_remotely_provisioned_component_name;
use crate::ks_err;
use crate::metrics_store::log_rkp_error_stats;
use crate::rkpd_client::get_rkpd_attestation_key;
@@ -93,7 +94,9 @@
if !self.is_asymmetric_key(params) || key.domain != Domain::APP {
Ok(None)
} else {
- match get_rkpd_attestation_key(&self.security_level, caller_uid) {
+ let rpc_name = get_remotely_provisioned_component_name(&self.security_level)
+ .context(ks_err!("Trying to get IRPC name."))?;
+ match get_rkpd_attestation_key(&rpc_name, caller_uid) {
Err(e) => {
if self.is_rkp_only() {
log::error!("Error occurred: {:?}", e);
diff --git a/keystore2/src/rkpd_client.rs b/keystore2/src/rkpd_client.rs
index 7b4131d..9317824 100644
--- a/keystore2/src/rkpd_client.rs
+++ b/keystore2/src/rkpd_client.rs
@@ -15,10 +15,7 @@
//! Helper wrapper around RKPD interface.
use crate::error::{map_binder_status_code, Error, ResponseCode};
-use crate::globals::get_remotely_provisioned_component_name;
-use crate::ks_err;
-use crate::utils::watchdog as wd;
-use android_hardware_security_keymint::aidl::android::hardware::security::keymint::SecurityLevel::SecurityLevel;
+use crate::watchdog_helper::watchdog as wd;
use android_security_rkp_aidl::aidl::android::security::rkp::{
IGetKeyCallback::BnGetKeyCallback, IGetKeyCallback::ErrorCode::ErrorCode as GetKeyErrorCode,
IGetKeyCallback::IGetKeyCallback, IGetRegistrationCallback::BnGetRegistrationCallback,
@@ -30,6 +27,7 @@
};
use android_security_rkp_aidl::binder::{BinderFeatures, Interface, Strong};
use anyhow::{Context, Result};
+use message_macro::source_location_msg;
use std::sync::Mutex;
use std::time::Duration;
use tokio::sync::oneshot;
@@ -93,43 +91,37 @@
log::warn!("IGetRegistrationCallback cancelled");
self.registration_tx.send(
Err(Error::Rc(ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR))
- .context(ks_err!("GetRegistrationCallback cancelled.")),
+ .context(source_location_msg!("GetRegistrationCallback cancelled.")),
);
Ok(())
}
fn onError(&self, description: &str) -> binder::Result<()> {
let _wp = wd::watch_millis("IGetRegistrationCallback::onError", 500);
log::error!("IGetRegistrationCallback failed: '{description}'");
- self.registration_tx.send(
- Err(Error::Rc(ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR))
- .context(ks_err!("GetRegistrationCallback failed: {:?}", description)),
- );
+ self.registration_tx
+ .send(Err(Error::Rc(ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR)).context(
+ source_location_msg!("GetRegistrationCallback failed: {:?}", description),
+ ));
Ok(())
}
}
/// Make a new connection to a IRegistration service.
-async fn get_rkpd_registration(
- security_level: &SecurityLevel,
-) -> Result<binder::Strong<dyn IRegistration>> {
+async fn get_rkpd_registration(rpc_name: &str) -> Result<binder::Strong<dyn IRegistration>> {
let remote_provisioning: Strong<dyn IRemoteProvisioning> =
map_binder_status_code(binder::get_interface("remote_provisioning"))
- .context(ks_err!("Trying to connect to IRemoteProvisioning service."))?;
-
- let rpc_name = get_remotely_provisioned_component_name(security_level)
- .context(ks_err!("Trying to get IRPC name."))?;
+ .context(source_location_msg!("Trying to connect to IRemoteProvisioning service."))?;
let (tx, rx) = oneshot::channel();
let cb = GetRegistrationCallback::new_native_binder(tx);
remote_provisioning
- .getRegistration(&rpc_name, &cb)
- .context(ks_err!("Trying to get registration."))?;
+ .getRegistration(rpc_name, &cb)
+ .context(source_location_msg!("Trying to get registration."))?;
match timeout(RKPD_TIMEOUT, rx).await {
- Err(e) => {
- Err(Error::Rc(ResponseCode::SYSTEM_ERROR)).context(ks_err!("Waiting for RKPD: {:?}", e))
- }
+ Err(e) => Err(Error::Rc(ResponseCode::SYSTEM_ERROR))
+ .context(source_location_msg!("Waiting for RKPD: {:?}", e)),
Ok(v) => v.unwrap(),
}
}
@@ -163,7 +155,7 @@
log::warn!("IGetKeyCallback cancelled");
self.key_tx.send(
Err(Error::Rc(ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR))
- .context(ks_err!("GetKeyCallback cancelled.")),
+ .context(source_location_msg!("GetKeyCallback cancelled.")),
);
Ok(())
}
@@ -184,7 +176,7 @@
ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR
}
};
- self.key_tx.send(Err(Error::Rc(rc)).context(ks_err!(
+ self.key_tx.send(Err(Error::Rc(rc)).context(source_location_msg!(
"GetKeyCallback failed: {:?} {:?}",
error,
description
@@ -202,7 +194,7 @@
registration
.getKey(caller_uid.try_into().unwrap(), &cb)
- .context(ks_err!("Trying to get key."))?;
+ .context(source_location_msg!("Trying to get key."))?;
match timeout(RKPD_TIMEOUT, rx).await {
Err(e) => {
@@ -211,19 +203,19 @@
log::error!("IRegistration::cancelGetKey failed: {:?}", e);
}
Err(Error::Rc(ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR))
- .context(ks_err!("Waiting for RKPD key timed out: {:?}", e))
+ .context(source_location_msg!("Waiting for RKPD key timed out: {:?}", e))
}
Ok(v) => v.unwrap(),
}
}
async fn get_rkpd_attestation_key_async(
- security_level: &SecurityLevel,
+ rpc_name: &str,
caller_uid: u32,
) -> Result<RemotelyProvisionedKey> {
- let registration = get_rkpd_registration(security_level)
+ let registration = get_rkpd_registration(rpc_name)
.await
- .context(ks_err!("Trying to get to IRegistration service."))?;
+ .context(source_location_msg!("Trying to get to IRegistration service."))?;
get_rkpd_attestation_key_from_registration_async(®istration, caller_uid).await
}
@@ -254,7 +246,7 @@
log::error!("IGetRegistrationCallback failed: {error}");
self.completer.send(
Err(Error::Rc(ResponseCode::SYSTEM_ERROR))
- .context(ks_err!("Failed to store upgraded key: {:?}", error)),
+ .context(source_location_msg!("Failed to store upgraded key: {:?}", error)),
);
Ok(())
}
@@ -270,61 +262,53 @@
registration
.storeUpgradedKeyAsync(key_blob, upgraded_blob, &cb)
- .context(ks_err!("Failed to store upgraded blob with RKPD."))?;
+ .context(source_location_msg!("Failed to store upgraded blob with RKPD."))?;
match timeout(RKPD_TIMEOUT, rx).await {
Err(e) => Err(Error::Rc(ResponseCode::SYSTEM_ERROR))
- .context(ks_err!("Waiting for RKPD to complete storing key: {:?}", e)),
+ .context(source_location_msg!("Waiting for RKPD to complete storing key: {:?}", e)),
Ok(v) => v.unwrap(),
}
}
async fn store_rkpd_attestation_key_async(
- security_level: &SecurityLevel,
+ rpc_name: &str,
key_blob: &[u8],
upgraded_blob: &[u8],
) -> Result<()> {
- let registration = get_rkpd_registration(security_level)
+ let registration = get_rkpd_registration(rpc_name)
.await
- .context(ks_err!("Trying to get to IRegistration service."))?;
+ .context(source_location_msg!("Trying to get to IRegistration service."))?;
store_rkpd_attestation_key_with_registration_async(®istration, key_blob, upgraded_blob).await
}
/// Get attestation key from RKPD.
-pub fn get_rkpd_attestation_key(
- security_level: &SecurityLevel,
- caller_uid: u32,
-) -> Result<RemotelyProvisionedKey> {
+pub fn get_rkpd_attestation_key(rpc_name: &str, caller_uid: u32) -> Result<RemotelyProvisionedKey> {
let _wp = wd::watch_millis("Calling get_rkpd_attestation_key()", 500);
- tokio_rt().block_on(get_rkpd_attestation_key_async(security_level, caller_uid))
+ tokio_rt().block_on(get_rkpd_attestation_key_async(rpc_name, caller_uid))
}
/// Store attestation key in RKPD.
pub fn store_rkpd_attestation_key(
- security_level: &SecurityLevel,
+ rpc_name: &str,
key_blob: &[u8],
upgraded_blob: &[u8],
) -> Result<()> {
let _wp = wd::watch_millis("Calling store_rkpd_attestation_key()", 500);
- tokio_rt().block_on(store_rkpd_attestation_key_async(security_level, key_blob, upgraded_blob))
+ tokio_rt().block_on(store_rkpd_attestation_key_async(rpc_name, key_blob, upgraded_blob))
}
#[cfg(test)]
mod tests {
use super::*;
- use crate::error::map_km_error;
- use crate::globals::get_keymint_device;
- use crate::utils::upgrade_keyblob_if_required_with;
- use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
- Algorithm::Algorithm, AttestationKey::AttestationKey, KeyParameter::KeyParameter,
- KeyParameterValue::KeyParameterValue, Tag::Tag,
- };
use android_security_rkp_aidl::aidl::android::security::rkp::IRegistration::BnRegistration;
- use keystore2_crypto::parse_subject_from_certificate;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex};
+ const DEFAULT_RPC_SERVICE_NAME: &str =
+ "android.hardware.security.keymint.IRemotelyProvisionedComponent/default";
+
struct MockRegistrationValues {
key: RemotelyProvisionedKey,
latency: Option<Duration>,
@@ -597,7 +581,7 @@
fn test_get_rkpd_attestation_key() {
binder::ProcessState::start_thread_pool();
let key_id = get_next_key_id();
- let key = get_rkpd_attestation_key(&SecurityLevel::TRUSTED_ENVIRONMENT, key_id).unwrap();
+ let key = get_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, key_id).unwrap();
assert!(!key.keyBlob.is_empty());
assert!(!key.encodedCertChain.is_empty());
}
@@ -605,12 +589,11 @@
#[test]
fn test_get_rkpd_attestation_key_same_caller() {
binder::ProcessState::start_thread_pool();
- let sec_level = SecurityLevel::TRUSTED_ENVIRONMENT;
let key_id = get_next_key_id();
// Multiple calls should return the same key.
- let first_key = get_rkpd_attestation_key(&sec_level, key_id).unwrap();
- let second_key = get_rkpd_attestation_key(&sec_level, key_id).unwrap();
+ let first_key = get_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, key_id).unwrap();
+ let second_key = get_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, key_id).unwrap();
assert_eq!(first_key.keyBlob, second_key.keyBlob);
assert_eq!(first_key.encodedCertChain, second_key.encodedCertChain);
@@ -619,13 +602,12 @@
#[test]
fn test_get_rkpd_attestation_key_different_caller() {
binder::ProcessState::start_thread_pool();
- let sec_level = SecurityLevel::TRUSTED_ENVIRONMENT;
let first_key_id = get_next_key_id();
let second_key_id = get_next_key_id();
// Different callers should be getting different keys.
- let first_key = get_rkpd_attestation_key(&sec_level, first_key_id).unwrap();
- let second_key = get_rkpd_attestation_key(&sec_level, second_key_id).unwrap();
+ let first_key = get_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, first_key_id).unwrap();
+ let second_key = get_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, second_key_id).unwrap();
assert_ne!(first_key.keyBlob, second_key.keyBlob);
assert_ne!(first_key.encodedCertChain, second_key.encodedCertChain);
@@ -639,86 +621,24 @@
// test case.
fn test_store_rkpd_attestation_key() {
binder::ProcessState::start_thread_pool();
- let sec_level = SecurityLevel::TRUSTED_ENVIRONMENT;
let key_id = get_next_key_id();
- let key = get_rkpd_attestation_key(&SecurityLevel::TRUSTED_ENVIRONMENT, key_id).unwrap();
+ let key = get_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, key_id).unwrap();
let new_blob: [u8; 8] = rand::random();
- assert!(store_rkpd_attestation_key(&sec_level, &key.keyBlob, &new_blob).is_ok());
+ assert!(
+ store_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, &key.keyBlob, &new_blob).is_ok()
+ );
- let new_key =
- get_rkpd_attestation_key(&SecurityLevel::TRUSTED_ENVIRONMENT, key_id).unwrap();
+ let new_key = get_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, key_id).unwrap();
// Restore original key so that we don't leave RKPD with invalid blobs.
- assert!(store_rkpd_attestation_key(&sec_level, &new_blob, &key.keyBlob).is_ok());
+ assert!(
+ store_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, &new_blob, &key.keyBlob).is_ok()
+ );
assert_eq!(new_key.keyBlob, new_blob);
}
#[test]
- // This is a helper for a manual test. We want to check that after a system upgrade RKPD
- // attestation keys can also be upgraded and stored again with RKPD. The steps are:
- // 1. Run this test and check in stdout that no key upgrade happened.
- // 2. Perform a system upgrade.
- // 3. Run this test and check in stdout that key upgrade did happen.
- //
- // Note that this test must be run with that same UID every time. Running as root, i.e. UID 0,
- // should do the trick. Also, use "--nocapture" flag to get stdout.
- fn test_rkpd_attestation_key_upgrade() {
- binder::ProcessState::start_thread_pool();
- let security_level = SecurityLevel::TRUSTED_ENVIRONMENT;
- let (keymint, info, _) = get_keymint_device(&security_level).unwrap();
- let key_id = get_next_key_id();
- let mut key_upgraded = false;
-
- let key = get_rkpd_attestation_key(&security_level, key_id).unwrap();
- assert!(!key.keyBlob.is_empty());
- assert!(!key.encodedCertChain.is_empty());
-
- upgrade_keyblob_if_required_with(
- &*keymint,
- info.versionNumber,
- &key.keyBlob,
- /*upgrade_params=*/ &[],
- /*km_op=*/
- |blob| {
- let params = vec![
- KeyParameter {
- tag: Tag::ALGORITHM,
- value: KeyParameterValue::Algorithm(Algorithm::AES),
- },
- KeyParameter {
- tag: Tag::ATTESTATION_CHALLENGE,
- value: KeyParameterValue::Blob(vec![0; 16]),
- },
- KeyParameter { tag: Tag::KEY_SIZE, value: KeyParameterValue::Integer(128) },
- ];
- let attestation_key = AttestationKey {
- keyBlob: blob.to_vec(),
- attestKeyParams: vec![],
- issuerSubjectName: parse_subject_from_certificate(&key.encodedCertChain)
- .unwrap(),
- };
-
- map_km_error(keymint.generateKey(¶ms, Some(&attestation_key)))
- },
- /*new_blob_handler=*/
- |new_blob| {
- // This handler is only executed if a key upgrade was performed.
- key_upgraded = true;
- store_rkpd_attestation_key(&security_level, &key.keyBlob, new_blob).unwrap();
- Ok(())
- },
- )
- .unwrap();
-
- if key_upgraded {
- println!("RKPD key was upgraded and stored with RKPD.");
- } else {
- println!("RKPD key was NOT upgraded.");
- }
- }
-
- #[test]
fn test_stress_get_rkpd_attestation_key() {
binder::ProcessState::start_thread_pool();
let key_id = get_next_key_id();
@@ -729,8 +649,7 @@
for _ in 0..NTHREADS {
threads.push(std::thread::spawn(move || {
for _ in 0..NCALLS {
- let key = get_rkpd_attestation_key(&SecurityLevel::TRUSTED_ENVIRONMENT, key_id)
- .unwrap();
+ let key = get_rkpd_attestation_key(DEFAULT_RPC_SERVICE_NAME, key_id).unwrap();
assert!(!key.keyBlob.is_empty());
assert!(!key.encodedCertChain.is_empty());
}
diff --git a/keystore2/src/security_level.rs b/keystore2/src/security_level.rs
index 6696113..50ada74 100644
--- a/keystore2/src/security_level.rs
+++ b/keystore2/src/security_level.rs
@@ -20,7 +20,9 @@
};
use crate::database::{BlobInfo, CertificateInfo, KeyIdGuard};
use crate::error::{self, map_km_error, map_or_log_err, Error, ErrorCode};
-use crate::globals::{DB, ENFORCEMENTS, LEGACY_IMPORTER, SUPER_KEY};
+use crate::globals::{
+ get_remotely_provisioned_component_name, DB, ENFORCEMENTS, LEGACY_IMPORTER, SUPER_KEY,
+};
use crate::key_parameter::KeyParameter as KsKeyParam;
use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
use crate::ks_err;
@@ -888,6 +890,8 @@
where
F: Fn(&[u8]) -> Result<T, Error>,
{
+ let rpc_name = get_remotely_provisioned_component_name(&self.security_level)
+ .context(ks_err!("Trying to get IRPC name."))?;
crate::utils::upgrade_keyblob_if_required_with(
&*self.keymint,
self.hw_info.versionNumber,
@@ -895,7 +899,7 @@
params,
f,
|upgraded_blob| {
- store_rkpd_attestation_key(&self.security_level, key_blob, upgraded_blob)
+ store_rkpd_attestation_key(&rpc_name, key_blob, upgraded_blob)
.context(ks_err!("Failed store_rkpd_attestation_key()."))
},
)
@@ -1057,3 +1061,82 @@
map_or_log_err(result, Ok)
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::error::map_km_error;
+ use crate::globals::get_keymint_device;
+ use crate::rkpd_client::{get_rkpd_attestation_key, store_rkpd_attestation_key};
+ use crate::utils::upgrade_keyblob_if_required_with;
+ use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
+ Algorithm::Algorithm, AttestationKey::AttestationKey, KeyParameter::KeyParameter,
+ KeyParameterValue::KeyParameterValue, Tag::Tag,
+ };
+ use keystore2_crypto::parse_subject_from_certificate;
+
+ #[test]
+ // This is a helper for a manual test. We want to check that after a system upgrade RKPD
+ // attestation keys can also be upgraded and stored again with RKPD. The steps are:
+ // 1. Run this test and check in stdout that no key upgrade happened.
+ // 2. Perform a system upgrade.
+ // 3. Run this test and check in stdout that key upgrade did happen.
+ //
+ // Note that this test must be run with that same UID every time. Running as root, i.e. UID 0,
+ // should do the trick. Also, use "--nocapture" flag to get stdout.
+ fn test_rkpd_attestation_key_upgrade() {
+ binder::ProcessState::start_thread_pool();
+ let security_level = SecurityLevel::TRUSTED_ENVIRONMENT;
+ let (keymint, info, _) = get_keymint_device(&security_level).unwrap();
+ let key_id = 0;
+ let mut key_upgraded = false;
+
+ let rpc_name = get_remotely_provisioned_component_name(&security_level).unwrap();
+ let key = get_rkpd_attestation_key(&rpc_name, key_id).unwrap();
+ assert!(!key.keyBlob.is_empty());
+ assert!(!key.encodedCertChain.is_empty());
+
+ upgrade_keyblob_if_required_with(
+ &*keymint,
+ info.versionNumber,
+ &key.keyBlob,
+ /*upgrade_params=*/ &[],
+ /*km_op=*/
+ |blob| {
+ let params = vec![
+ KeyParameter {
+ tag: Tag::ALGORITHM,
+ value: KeyParameterValue::Algorithm(Algorithm::AES),
+ },
+ KeyParameter {
+ tag: Tag::ATTESTATION_CHALLENGE,
+ value: KeyParameterValue::Blob(vec![0; 16]),
+ },
+ KeyParameter { tag: Tag::KEY_SIZE, value: KeyParameterValue::Integer(128) },
+ ];
+ let attestation_key = AttestationKey {
+ keyBlob: blob.to_vec(),
+ attestKeyParams: vec![],
+ issuerSubjectName: parse_subject_from_certificate(&key.encodedCertChain)
+ .unwrap(),
+ };
+
+ map_km_error(keymint.generateKey(¶ms, Some(&attestation_key)))
+ },
+ /*new_blob_handler=*/
+ |new_blob| {
+ // This handler is only executed if a key upgrade was performed.
+ key_upgraded = true;
+ store_rkpd_attestation_key(&rpc_name, &key.keyBlob, new_blob).unwrap();
+ Ok(())
+ },
+ )
+ .unwrap();
+
+ if key_upgraded {
+ println!("RKPD key was upgraded and stored with RKPD.");
+ } else {
+ println!("RKPD key was NOT upgraded.");
+ }
+ }
+}
diff --git a/keystore2/src/utils.rs b/keystore2/src/utils.rs
index 80aa7c3..4fd9c8d 100644
--- a/keystore2/src/utils.rs
+++ b/keystore2/src/utils.rs
@@ -20,6 +20,7 @@
use crate::ks_err;
use crate::permission;
use crate::permission::{KeyPerm, KeyPermSet, KeystorePerm};
+pub use crate::watchdog_helper::watchdog;
use crate::{
database::{KeyType, KeystoreDB},
globals::LEGACY_IMPORTER,
@@ -268,7 +269,7 @@
let mut current_time = libc::timespec { tv_sec: 0, tv_nsec: 0 };
// SAFETY: The pointer is valid because it comes from a reference, and clock_gettime doesn't
// retain it beyond the call.
- unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut current_time) };
+ unsafe { libc::clock_gettime(libc::CLOCK_BOOTTIME, &mut current_time) };
current_time.tv_sec as i64 * 1000 + (current_time.tv_nsec as i64 / 1_000_000)
}
@@ -421,36 +422,6 @@
Ok((legacy_keys.len() + num_keys_in_db) as i32)
}
-/// This module provides helpers for simplified use of the watchdog module.
-#[cfg(feature = "watchdog")]
-pub mod watchdog {
- pub use crate::watchdog::WatchPoint;
- use crate::watchdog::Watchdog;
- use lazy_static::lazy_static;
- use std::sync::Arc;
- use std::time::Duration;
-
- lazy_static! {
- /// A Watchdog thread, that can be used to create watch points.
- static ref WD: Arc<Watchdog> = Watchdog::new(Duration::from_secs(10));
- }
-
- /// Sets a watch point with `id` and a timeout of `millis` milliseconds.
- pub fn watch_millis(id: &'static str, millis: u64) -> Option<WatchPoint> {
- Watchdog::watch(&WD, id, Duration::from_millis(millis))
- }
-
- /// Like `watch_millis` but with a callback that is called every time a report
- /// is printed about this watch point.
- pub fn watch_millis_with(
- id: &'static str,
- millis: u64,
- callback: impl Fn() -> String + Send + 'static,
- ) -> Option<WatchPoint> {
- Watchdog::watch_with(&WD, id, Duration::from_millis(millis), callback)
- }
-}
-
/// Trait implemented by objects that can be used to decrypt cipher text using AES-GCM.
pub trait AesGcm {
/// Deciphers `data` using the initialization vector `iv` and AEAD tag `tag`
@@ -480,25 +451,6 @@
}
}
-/// This module provides empty/noop implementations of the watch dog utility functions.
-#[cfg(not(feature = "watchdog"))]
-pub mod watchdog {
- /// Noop watch point.
- pub struct WatchPoint();
- /// Sets a Noop watch point.
- fn watch_millis(_: &'static str, _: u64) -> Option<WatchPoint> {
- None
- }
-
- pub fn watch_millis_with(
- _: &'static str,
- _: u64,
- _: impl Fn() -> String + Send + 'static,
- ) -> Option<WatchPoint> {
- None
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/keystore2/src/watchdog_helper.rs b/keystore2/src/watchdog_helper.rs
new file mode 100644
index 0000000..92a0abc
--- /dev/null
+++ b/keystore2/src/watchdog_helper.rs
@@ -0,0 +1,64 @@
+// Copyright 2023, The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Helpers for the watchdog module.
+
+/// This module provides helpers for simplified use of the watchdog module.
+#[cfg(feature = "watchdog")]
+pub mod watchdog {
+ use lazy_static::lazy_static;
+ use std::sync::Arc;
+ use std::time::Duration;
+ pub use watchdog_rs::WatchPoint;
+ use watchdog_rs::Watchdog;
+
+ lazy_static! {
+ /// A Watchdog thread, that can be used to create watch points.
+ static ref WD: Arc<Watchdog> = Watchdog::new(Duration::from_secs(10));
+ }
+
+ /// Sets a watch point with `id` and a timeout of `millis` milliseconds.
+ pub fn watch_millis(id: &'static str, millis: u64) -> Option<WatchPoint> {
+ Watchdog::watch(&WD, id, Duration::from_millis(millis))
+ }
+
+ /// Like `watch_millis` but with a callback that is called every time a report
+ /// is printed about this watch point.
+ pub fn watch_millis_with(
+ id: &'static str,
+ millis: u64,
+ callback: impl Fn() -> String + Send + 'static,
+ ) -> Option<WatchPoint> {
+ Watchdog::watch_with(&WD, id, Duration::from_millis(millis), callback)
+ }
+}
+
+/// This module provides empty/noop implementations of the watch dog utility functions.
+#[cfg(not(feature = "watchdog"))]
+pub mod watchdog {
+ /// Noop watch point.
+ pub struct WatchPoint();
+ /// Sets a Noop watch point.
+ fn watch_millis(_: &'static str, _: u64) -> Option<WatchPoint> {
+ None
+ }
+
+ pub fn watch_millis_with(
+ _: &'static str,
+ _: u64,
+ _: impl Fn() -> String + Send + 'static,
+ ) -> Option<WatchPoint> {
+ None
+ }
+}
diff --git a/keystore2/watchdog/Android.bp b/keystore2/watchdog/Android.bp
new file mode 100644
index 0000000..62ede89
--- /dev/null
+++ b/keystore2/watchdog/Android.bp
@@ -0,0 +1,49 @@
+// Copyright 2023, The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "system_security_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-Apache-2.0
+ default_applicable_licenses: ["system_security_license"],
+}
+
+rust_defaults {
+ name: "libwatchdog_defaults",
+ crate_name: "watchdog_rs",
+ srcs: ["src/lib.rs"],
+ rustlibs: [
+ "liblog_rust",
+ ]
+}
+
+rust_library {
+ name: "libwatchdog_rs",
+ defaults: ["libwatchdog_defaults"],
+ apex_available: [
+ "//apex_available:platform",
+ "com.android.virt",
+ ],
+}
+
+rust_test {
+ name: "libwatchdog_rs.test",
+ defaults: ["libwatchdog_defaults"],
+ test_suites: ["general-tests"],
+ rustlibs: [
+ "libandroid_logger",
+ ]
+}
diff --git a/keystore2/src/watchdog.rs b/keystore2/watchdog/src/lib.rs
similarity index 100%
rename from keystore2/src/watchdog.rs
rename to keystore2/watchdog/src/lib.rs