blob: 92b04f27b26493493e04344561e5e7a3305fb19e [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};
Victor Hsieh23f73592021-08-06 18:08:24 -070028use android_system_keystore2::binder::{wait_for_interface, Strong};
Alan Stokes337874a2021-06-16 16:49:32 +010029use anyhow::{anyhow, Context, Result};
Victor Hsieh23f73592021-08-06 18:08:24 -070030use compos_aidl_interface::aidl::com::android::compos::CompOsKeyData::CompOsKeyData;
Alan Stokes337874a2021-06-16 16:49:32 +010031use ring::rand::{SecureRandom, SystemRandom};
32use ring::signature;
33use scopeguard::ScopeGuard;
Alan Stokes337874a2021-06-16 16:49:32 +010034
Alan Stokesb15c93f2021-07-15 16:21:50 +010035/// Keystore2 namespace IDs, used for access control to keys.
36#[derive(Copy, Clone, Debug, PartialEq, Eq)]
37pub enum KeystoreNamespace {
38 /// In the host we re-use the ID assigned to odsign. See system/sepolicy/private/keystore2_key_contexts.
39 // TODO(alanstokes): Remove this.
40 Odsign = 101,
41 /// In a VM we can use the generic ID allocated for payloads. See microdroid's keystore2_key_contexts.
42 VmPayload = 140,
43}
44
Alan Stokes337874a2021-06-16 16:49:32 +010045const KEYSTORE_SERVICE_NAME: &str = "android.system.keystore2.IKeystoreService/default";
Alan Stokes337874a2021-06-16 16:49:32 +010046const PURPOSE_SIGN: KeyParameter =
47 KeyParameter { tag: Tag::PURPOSE, value: KeyParameterValue::KeyPurpose(KeyPurpose::SIGN) };
48const ALGORITHM: KeyParameter =
49 KeyParameter { tag: Tag::ALGORITHM, value: KeyParameterValue::Algorithm(Algorithm::RSA) };
50const PADDING: KeyParameter = KeyParameter {
51 tag: Tag::PADDING,
52 value: KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
53};
54const DIGEST: KeyParameter =
55 KeyParameter { tag: Tag::DIGEST, value: KeyParameterValue::Digest(Digest::SHA_2_256) };
56const KEY_SIZE: KeyParameter =
57 KeyParameter { tag: Tag::KEY_SIZE, value: KeyParameterValue::Integer(2048) };
58const EXPONENT: KeyParameter =
59 KeyParameter { tag: Tag::RSA_PUBLIC_EXPONENT, value: KeyParameterValue::LongInteger(65537) };
60const NO_AUTH_REQUIRED: KeyParameter =
61 KeyParameter { tag: Tag::NO_AUTH_REQUIRED, value: KeyParameterValue::BoolValue(true) };
62
Alan Stokesb15c93f2021-07-15 16:21:50 +010063const BLOB_KEY_DESCRIPTOR: KeyDescriptor =
64 KeyDescriptor { domain: Domain::BLOB, nspace: 0, alias: None, blob: None };
Alan Stokes337874a2021-06-16 16:49:32 +010065
Victor Hsieha64194b2021-08-06 17:43:36 -070066/// An internal service for CompOS key management.
Alan Stokes7ec4e7f2021-07-21 11:29:10 +010067#[derive(Clone)]
Victor Hsieha64194b2021-08-06 17:43:36 -070068pub struct CompOsKeyService {
Alan Stokesb15c93f2021-07-15 16:21:50 +010069 namespace: KeystoreNamespace,
Alan Stokes337874a2021-06-16 16:49:32 +010070 random: SystemRandom,
Alan Stokes337874a2021-06-16 16:49:32 +010071 security_level: Strong<dyn IKeystoreSecurityLevel>,
72}
73
Alan Stokes7ec4e7f2021-07-21 11:29:10 +010074impl CompOsKeyService {
Victor Hsieh23f73592021-08-06 18:08:24 -070075 pub fn new(rpc_binder: bool) -> Result<Self> {
Victor Hsieha64194b2021-08-06 17:43:36 -070076 let keystore_service = wait_for_interface::<dyn IKeystoreService>(KEYSTORE_SERVICE_NAME)
77 .context("No Keystore service")?;
78
Victor Hsieh23f73592021-08-06 18:08:24 -070079 let namespace =
80 if rpc_binder { KeystoreNamespace::VmPayload } else { KeystoreNamespace::Odsign };
Victor Hsieha64194b2021-08-06 17:43:36 -070081 Ok(CompOsKeyService {
82 namespace,
83 random: SystemRandom::new(),
84 security_level: keystore_service
85 .getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT)
86 .context("Getting SecurityLevel failed")?,
87 })
88 }
89
Victor Hsieh23f73592021-08-06 18:08:24 -070090 pub fn do_generate(&self) -> Result<CompOsKeyData> {
Alan Stokesb15c93f2021-07-15 16:21:50 +010091 let key_descriptor = KeyDescriptor { nspace: self.namespace as i64, ..BLOB_KEY_DESCRIPTOR };
Alan Stokes337874a2021-06-16 16:49:32 +010092 let key_parameters =
93 [PURPOSE_SIGN, ALGORITHM, PADDING, DIGEST, KEY_SIZE, EXPONENT, NO_AUTH_REQUIRED];
94 let attestation_key = None;
95 let flags = 0;
96 let entropy = [];
97
98 let key_metadata = self
Alan Stokes4a489d42021-06-28 10:12:05 +010099 .security_level
Alan Stokesb15c93f2021-07-15 16:21:50 +0100100 .generateKey(&key_descriptor, attestation_key, &key_parameters, flags, &entropy)
Alan Stokes337874a2021-06-16 16:49:32 +0100101 .context("Generating key failed")?;
102
103 if let (Some(certificate), Some(blob)) = (key_metadata.certificate, key_metadata.key.blob) {
104 Ok(CompOsKeyData { certificate, keyBlob: blob })
105 } else {
106 Err(anyhow!("Missing cert or blob"))
107 }
108 }
109
Victor Hsieh23f73592021-08-06 18:08:24 -0700110 pub fn do_verify(&self, key_blob: &[u8], public_key: &[u8]) -> Result<()> {
Alan Stokes337874a2021-06-16 16:49:32 +0100111 let mut data = [0u8; 32];
112 self.random.fill(&mut data).context("No random data")?;
113
Alan Stokesc3bab542021-07-06 15:48:33 +0100114 let signature = self.do_sign(key_blob, &data)?;
Alan Stokes337874a2021-06-16 16:49:32 +0100115
116 let public_key =
117 signature::UnparsedPublicKey::new(&signature::RSA_PKCS1_2048_8192_SHA256, public_key);
118 public_key.verify(&data, &signature).context("Signature verification failed")?;
119
120 Ok(())
121 }
122
Victor Hsieh23f73592021-08-06 18:08:24 -0700123 pub fn do_sign(&self, key_blob: &[u8], data: &[u8]) -> Result<Vec<u8>> {
Alan Stokesb15c93f2021-07-15 16:21:50 +0100124 let key_descriptor = KeyDescriptor {
125 nspace: self.namespace as i64,
126 blob: Some(key_blob.to_vec()),
127 ..BLOB_KEY_DESCRIPTOR
128 };
Alan Stokes337874a2021-06-16 16:49:32 +0100129 let operation_parameters = [PURPOSE_SIGN, ALGORITHM, PADDING, DIGEST];
130 let forced = false;
131
132 let response = self
Alan Stokes4a489d42021-06-28 10:12:05 +0100133 .security_level
Alan Stokes337874a2021-06-16 16:49:32 +0100134 .createOperation(&key_descriptor, &operation_parameters, forced)
135 .context("Creating key failed")?;
136 let operation = scopeguard::guard(
137 response.iOperation.ok_or_else(|| anyhow!("No operation created"))?,
138 |op| op.abort().unwrap_or_default(),
139 );
140
141 if response.operationChallenge.is_some() {
142 return Err(anyhow!("Key requires user authorization"));
143 }
144
Chris Wailes68c39f82021-07-27 16:03:44 -0700145 let signature = operation.finish(Some(data), None).context("Signing failed")?;
Alan Stokes337874a2021-06-16 16:49:32 +0100146 // Operation has finished, we're no longer responsible for aborting it
147 ScopeGuard::into_inner(operation);
148
149 signature.ok_or_else(|| anyhow!("No signature returned"))
150 }
151}