blob: 6b62e0f3166e574958fd2ad624a71c34cf314fe8 [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::{
Alan Stokes8ccebf12021-07-14 12:04:31 +010033 self, get_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 Stokes337874a2021-06-16 16:49:32 +010041const KEYSTORE_SERVICE_NAME: &str = "android.system.keystore2.IKeystoreService/default";
42const COMPOS_NAMESPACE: i64 = 101;
43const PURPOSE_SIGN: KeyParameter =
44 KeyParameter { tag: Tag::PURPOSE, value: KeyParameterValue::KeyPurpose(KeyPurpose::SIGN) };
45const ALGORITHM: KeyParameter =
46 KeyParameter { tag: Tag::ALGORITHM, value: KeyParameterValue::Algorithm(Algorithm::RSA) };
47const PADDING: KeyParameter = KeyParameter {
48 tag: Tag::PADDING,
49 value: KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
50};
51const DIGEST: KeyParameter =
52 KeyParameter { tag: Tag::DIGEST, value: KeyParameterValue::Digest(Digest::SHA_2_256) };
53const KEY_SIZE: KeyParameter =
54 KeyParameter { tag: Tag::KEY_SIZE, value: KeyParameterValue::Integer(2048) };
55const EXPONENT: KeyParameter =
56 KeyParameter { tag: Tag::RSA_PUBLIC_EXPONENT, value: KeyParameterValue::LongInteger(65537) };
57const NO_AUTH_REQUIRED: KeyParameter =
58 KeyParameter { tag: Tag::NO_AUTH_REQUIRED, value: KeyParameterValue::BoolValue(true) };
59
60const KEY_DESCRIPTOR: KeyDescriptor =
61 KeyDescriptor { domain: Domain::BLOB, nspace: COMPOS_NAMESPACE, alias: None, blob: None };
62
Alan Stokes8ccebf12021-07-14 12:04:31 +010063pub struct CompOsKeyService {
Alan Stokes337874a2021-06-16 16:49:32 +010064 random: SystemRandom,
Alan Stokes337874a2021-06-16 16:49:32 +010065 security_level: Strong<dyn IKeystoreSecurityLevel>,
66}
67
68impl Interface for CompOsKeyService {}
69
70impl ICompOsKeyService for CompOsKeyService {
71 fn generateSigningKey(&self) -> binder::Result<CompOsKeyData> {
72 self.do_generate()
73 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))
74 }
75
76 fn verifySigningKey(&self, key_blob: &[u8], public_key: &[u8]) -> binder::Result<bool> {
77 Ok(if let Err(e) = self.do_verify(key_blob, public_key) {
78 warn!("Signing key verification failed: {}", e.to_string());
79 false
80 } else {
81 true
82 })
83 }
Alan Stokesc3bab542021-07-06 15:48:33 +010084
85 fn sign(&self, key_blob: &[u8], data: &[u8]) -> binder::Result<Vec<u8>> {
86 self.do_sign(key_blob, data)
87 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))
88 }
Alan Stokes337874a2021-06-16 16:49:32 +010089}
90
91/// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
92fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
93 Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
94}
95
96impl CompOsKeyService {
Alan Stokes8ccebf12021-07-14 12:04:31 +010097 pub fn new() -> Result<Self> {
98 let keystore_service = get_interface::<dyn IKeystoreService>(KEYSTORE_SERVICE_NAME)
99 .context("No Keystore service")?;
100
101 Ok(Self {
Alan Stokes337874a2021-06-16 16:49:32 +0100102 random: SystemRandom::new(),
Alan Stokes4a489d42021-06-28 10:12:05 +0100103 security_level: keystore_service
104 .getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT)
Alan Stokes8ccebf12021-07-14 12:04:31 +0100105 .context("Getting SecurityLevel failed")?,
106 })
Alan Stokes337874a2021-06-16 16:49:32 +0100107 }
108
Alan Stokes337874a2021-06-16 16:49:32 +0100109 fn do_generate(&self) -> Result<CompOsKeyData> {
110 let key_parameters =
111 [PURPOSE_SIGN, ALGORITHM, PADDING, DIGEST, KEY_SIZE, EXPONENT, NO_AUTH_REQUIRED];
112 let attestation_key = None;
113 let flags = 0;
114 let entropy = [];
115
116 let key_metadata = self
Alan Stokes4a489d42021-06-28 10:12:05 +0100117 .security_level
Alan Stokes337874a2021-06-16 16:49:32 +0100118 .generateKey(&KEY_DESCRIPTOR, attestation_key, &key_parameters, flags, &entropy)
119 .context("Generating key failed")?;
120
121 if let (Some(certificate), Some(blob)) = (key_metadata.certificate, key_metadata.key.blob) {
122 Ok(CompOsKeyData { certificate, keyBlob: blob })
123 } else {
124 Err(anyhow!("Missing cert or blob"))
125 }
126 }
127
128 fn do_verify(&self, key_blob: &[u8], public_key: &[u8]) -> Result<()> {
129 let mut data = [0u8; 32];
130 self.random.fill(&mut data).context("No random data")?;
131
Alan Stokesc3bab542021-07-06 15:48:33 +0100132 let signature = self.do_sign(key_blob, &data)?;
Alan Stokes337874a2021-06-16 16:49:32 +0100133
134 let public_key =
135 signature::UnparsedPublicKey::new(&signature::RSA_PKCS1_2048_8192_SHA256, public_key);
136 public_key.verify(&data, &signature).context("Signature verification failed")?;
137
138 Ok(())
139 }
140
Alan Stokesc3bab542021-07-06 15:48:33 +0100141 fn do_sign(&self, key_blob: &[u8], data: &[u8]) -> Result<Vec<u8>> {
Alan Stokes337874a2021-06-16 16:49:32 +0100142 let key_descriptor = KeyDescriptor { blob: Some(key_blob.to_vec()), ..KEY_DESCRIPTOR };
143 let operation_parameters = [PURPOSE_SIGN, ALGORITHM, PADDING, DIGEST];
144 let forced = false;
145
146 let response = self
Alan Stokes4a489d42021-06-28 10:12:05 +0100147 .security_level
Alan Stokes337874a2021-06-16 16:49:32 +0100148 .createOperation(&key_descriptor, &operation_parameters, forced)
149 .context("Creating key failed")?;
150 let operation = scopeguard::guard(
151 response.iOperation.ok_or_else(|| anyhow!("No operation created"))?,
152 |op| op.abort().unwrap_or_default(),
153 );
154
155 if response.operationChallenge.is_some() {
156 return Err(anyhow!("Key requires user authorization"));
157 }
158
159 let signature = operation.finish(Some(&data), None).context("Signing failed")?;
160 // Operation has finished, we're no longer responsible for aborting it
161 ScopeGuard::into_inner(operation);
162
163 signature.ok_or_else(|| anyhow!("No signature returned"))
164 }
165}