blob: 66451b388256182def478c16c7bbd08dc99b4242 [file] [log] [blame]
Alan Stokes337874a2021-06-16 16:49:32 +01001// Copyright 2021, 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//! Provides a binder service for key generation & verification for CompOs. We assume we have
16//! access to Keystore in the VM, but not persistent storage; instead the host stores the key
17//! on our behalf via this service.
18
19use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
20 Algorithm::Algorithm, Digest::Digest, KeyParameter::KeyParameter,
21 KeyParameterValue::KeyParameterValue, KeyPurpose::KeyPurpose, PaddingMode::PaddingMode,
22 SecurityLevel::SecurityLevel, Tag::Tag,
23};
24use android_system_keystore2::aidl::android::system::keystore2::{
25 Domain::Domain, IKeystoreSecurityLevel::IKeystoreSecurityLevel,
26 IKeystoreService::IKeystoreService, KeyDescriptor::KeyDescriptor,
27};
28use anyhow::{anyhow, Context, Result};
29use compos_aidl_interface::aidl::com::android::compos::{
Alan Stokes8ccebf12021-07-14 12:04:31 +010030 CompOsKeyData::CompOsKeyData, ICompOsKeyService::ICompOsKeyService,
Alan Stokes337874a2021-06-16 16:49:32 +010031};
32use compos_aidl_interface::binder::{
Andrew Scullffdf7ad2021-07-14 17:55:15 +000033 self, wait_for_interface, ExceptionCode, Interface, Status, Strong,
Alan Stokes337874a2021-06-16 16:49:32 +010034};
Alan Stokes8ccebf12021-07-14 12:04:31 +010035use log::warn;
Alan Stokes337874a2021-06-16 16:49:32 +010036use ring::rand::{SecureRandom, SystemRandom};
37use ring::signature;
38use scopeguard::ScopeGuard;
39use std::ffi::CString;
Alan Stokes337874a2021-06-16 16:49:32 +010040
Alan Stokesb15c93f2021-07-15 16:21:50 +010041/// Keystore2 namespace IDs, used for access control to keys.
42#[derive(Copy, Clone, Debug, PartialEq, Eq)]
43pub enum KeystoreNamespace {
44 /// In the host we re-use the ID assigned to odsign. See system/sepolicy/private/keystore2_key_contexts.
45 // TODO(alanstokes): Remove this.
46 Odsign = 101,
47 /// In a VM we can use the generic ID allocated for payloads. See microdroid's keystore2_key_contexts.
48 VmPayload = 140,
49}
50
Alan Stokes337874a2021-06-16 16:49:32 +010051const KEYSTORE_SERVICE_NAME: &str = "android.system.keystore2.IKeystoreService/default";
Alan Stokes337874a2021-06-16 16:49:32 +010052const PURPOSE_SIGN: KeyParameter =
53 KeyParameter { tag: Tag::PURPOSE, value: KeyParameterValue::KeyPurpose(KeyPurpose::SIGN) };
54const ALGORITHM: KeyParameter =
55 KeyParameter { tag: Tag::ALGORITHM, value: KeyParameterValue::Algorithm(Algorithm::RSA) };
56const PADDING: KeyParameter = KeyParameter {
57 tag: Tag::PADDING,
58 value: KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
59};
60const DIGEST: KeyParameter =
61 KeyParameter { tag: Tag::DIGEST, value: KeyParameterValue::Digest(Digest::SHA_2_256) };
62const KEY_SIZE: KeyParameter =
63 KeyParameter { tag: Tag::KEY_SIZE, value: KeyParameterValue::Integer(2048) };
64const EXPONENT: KeyParameter =
65 KeyParameter { tag: Tag::RSA_PUBLIC_EXPONENT, value: KeyParameterValue::LongInteger(65537) };
66const NO_AUTH_REQUIRED: KeyParameter =
67 KeyParameter { tag: Tag::NO_AUTH_REQUIRED, value: KeyParameterValue::BoolValue(true) };
68
Alan Stokesb15c93f2021-07-15 16:21:50 +010069const BLOB_KEY_DESCRIPTOR: KeyDescriptor =
70 KeyDescriptor { domain: Domain::BLOB, nspace: 0, alias: None, blob: None };
Alan Stokes337874a2021-06-16 16:49:32 +010071
Alan Stokes8ccebf12021-07-14 12:04:31 +010072pub struct CompOsKeyService {
Alan Stokesb15c93f2021-07-15 16:21:50 +010073 namespace: KeystoreNamespace,
Alan Stokes337874a2021-06-16 16:49:32 +010074 random: SystemRandom,
Alan Stokes337874a2021-06-16 16:49:32 +010075 security_level: Strong<dyn IKeystoreSecurityLevel>,
76}
77
78impl Interface for CompOsKeyService {}
79
80impl ICompOsKeyService for CompOsKeyService {
81 fn generateSigningKey(&self) -> binder::Result<CompOsKeyData> {
82 self.do_generate()
83 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))
84 }
85
86 fn verifySigningKey(&self, key_blob: &[u8], public_key: &[u8]) -> binder::Result<bool> {
87 Ok(if let Err(e) = self.do_verify(key_blob, public_key) {
88 warn!("Signing key verification failed: {}", e.to_string());
89 false
90 } else {
91 true
92 })
93 }
Alan Stokesc3bab542021-07-06 15:48:33 +010094
95 fn sign(&self, key_blob: &[u8], data: &[u8]) -> binder::Result<Vec<u8>> {
96 self.do_sign(key_blob, data)
97 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))
98 }
Alan Stokes337874a2021-06-16 16:49:32 +010099}
100
101/// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
102fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
103 Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
104}
105
106impl CompOsKeyService {
Alan Stokesb15c93f2021-07-15 16:21:50 +0100107 pub fn new(namespace: KeystoreNamespace) -> Result<Self> {
Andrew Scullffdf7ad2021-07-14 17:55:15 +0000108 let keystore_service = wait_for_interface::<dyn IKeystoreService>(KEYSTORE_SERVICE_NAME)
Alan Stokes8ccebf12021-07-14 12:04:31 +0100109 .context("No Keystore service")?;
110
111 Ok(Self {
Alan Stokesb15c93f2021-07-15 16:21:50 +0100112 namespace,
Alan Stokes337874a2021-06-16 16:49:32 +0100113 random: SystemRandom::new(),
Alan Stokes4a489d42021-06-28 10:12:05 +0100114 security_level: keystore_service
115 .getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT)
Alan Stokes8ccebf12021-07-14 12:04:31 +0100116 .context("Getting SecurityLevel failed")?,
117 })
Alan Stokes337874a2021-06-16 16:49:32 +0100118 }
119
Alan Stokes337874a2021-06-16 16:49:32 +0100120 fn do_generate(&self) -> Result<CompOsKeyData> {
Alan Stokesb15c93f2021-07-15 16:21:50 +0100121 let key_descriptor = KeyDescriptor { nspace: self.namespace as i64, ..BLOB_KEY_DESCRIPTOR };
Alan Stokes337874a2021-06-16 16:49:32 +0100122 let key_parameters =
123 [PURPOSE_SIGN, ALGORITHM, PADDING, DIGEST, KEY_SIZE, EXPONENT, NO_AUTH_REQUIRED];
124 let attestation_key = None;
125 let flags = 0;
126 let entropy = [];
127
128 let key_metadata = self
Alan Stokes4a489d42021-06-28 10:12:05 +0100129 .security_level
Alan Stokesb15c93f2021-07-15 16:21:50 +0100130 .generateKey(&key_descriptor, attestation_key, &key_parameters, flags, &entropy)
Alan Stokes337874a2021-06-16 16:49:32 +0100131 .context("Generating key failed")?;
132
133 if let (Some(certificate), Some(blob)) = (key_metadata.certificate, key_metadata.key.blob) {
134 Ok(CompOsKeyData { certificate, keyBlob: blob })
135 } else {
136 Err(anyhow!("Missing cert or blob"))
137 }
138 }
139
140 fn do_verify(&self, key_blob: &[u8], public_key: &[u8]) -> Result<()> {
141 let mut data = [0u8; 32];
142 self.random.fill(&mut data).context("No random data")?;
143
Alan Stokesc3bab542021-07-06 15:48:33 +0100144 let signature = self.do_sign(key_blob, &data)?;
Alan Stokes337874a2021-06-16 16:49:32 +0100145
146 let public_key =
147 signature::UnparsedPublicKey::new(&signature::RSA_PKCS1_2048_8192_SHA256, public_key);
148 public_key.verify(&data, &signature).context("Signature verification failed")?;
149
150 Ok(())
151 }
152
Alan Stokesc3bab542021-07-06 15:48:33 +0100153 fn do_sign(&self, key_blob: &[u8], data: &[u8]) -> Result<Vec<u8>> {
Alan Stokesb15c93f2021-07-15 16:21:50 +0100154 let key_descriptor = KeyDescriptor {
155 nspace: self.namespace as i64,
156 blob: Some(key_blob.to_vec()),
157 ..BLOB_KEY_DESCRIPTOR
158 };
Alan Stokes337874a2021-06-16 16:49:32 +0100159 let operation_parameters = [PURPOSE_SIGN, ALGORITHM, PADDING, DIGEST];
160 let forced = false;
161
162 let response = self
Alan Stokes4a489d42021-06-28 10:12:05 +0100163 .security_level
Alan Stokes337874a2021-06-16 16:49:32 +0100164 .createOperation(&key_descriptor, &operation_parameters, forced)
165 .context("Creating key failed")?;
166 let operation = scopeguard::guard(
167 response.iOperation.ok_or_else(|| anyhow!("No operation created"))?,
168 |op| op.abort().unwrap_or_default(),
169 );
170
171 if response.operationChallenge.is_some() {
172 return Err(anyhow!("Key requires user authorization"));
173 }
174
175 let signature = operation.finish(Some(&data), None).context("Signing failed")?;
176 // Operation has finished, we're no longer responsible for aborting it
177 ScopeGuard::into_inner(operation);
178
179 signature.ok_or_else(|| anyhow!("No signature returned"))
180 }
181}