blob: 97fd85588f7292f47eccab184c6959f37634228c [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::{
30 CompOsKeyData::CompOsKeyData,
31 ICompOsKeyService::{BnCompOsKeyService, ICompOsKeyService},
32};
33use compos_aidl_interface::binder::{
34 self, add_service, get_interface, BinderFeatures, ExceptionCode, Interface, ProcessState,
35 Status, Strong,
36};
37use log::{info, warn, Level};
38use ring::rand::{SecureRandom, SystemRandom};
39use ring::signature;
40use scopeguard::ScopeGuard;
41use std::ffi::CString;
42use std::sync::Mutex;
43
44const LOG_TAG: &str = "CompOsKeyService";
45const OUR_SERVICE_NAME: &str = "android.system.composkeyservice";
46
47const KEYSTORE_SERVICE_NAME: &str = "android.system.keystore2.IKeystoreService/default";
48const COMPOS_NAMESPACE: i64 = 101;
49const PURPOSE_SIGN: KeyParameter =
50 KeyParameter { tag: Tag::PURPOSE, value: KeyParameterValue::KeyPurpose(KeyPurpose::SIGN) };
51const ALGORITHM: KeyParameter =
52 KeyParameter { tag: Tag::ALGORITHM, value: KeyParameterValue::Algorithm(Algorithm::RSA) };
53const PADDING: KeyParameter = KeyParameter {
54 tag: Tag::PADDING,
55 value: KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
56};
57const DIGEST: KeyParameter =
58 KeyParameter { tag: Tag::DIGEST, value: KeyParameterValue::Digest(Digest::SHA_2_256) };
59const KEY_SIZE: KeyParameter =
60 KeyParameter { tag: Tag::KEY_SIZE, value: KeyParameterValue::Integer(2048) };
61const EXPONENT: KeyParameter =
62 KeyParameter { tag: Tag::RSA_PUBLIC_EXPONENT, value: KeyParameterValue::LongInteger(65537) };
63const NO_AUTH_REQUIRED: KeyParameter =
64 KeyParameter { tag: Tag::NO_AUTH_REQUIRED, value: KeyParameterValue::BoolValue(true) };
65
66const KEY_DESCRIPTOR: KeyDescriptor =
67 KeyDescriptor { domain: Domain::BLOB, nspace: COMPOS_NAMESPACE, alias: None, blob: None };
68
69struct CompOsKeyService {
70 random: SystemRandom,
71 state: Mutex<State>,
72}
73
74struct State {
75 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 }
94}
95
96/// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
97fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
98 Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
99}
100
101impl CompOsKeyService {
102 fn new(keystore_service: &Strong<dyn IKeystoreService>) -> Self {
103 Self {
104 random: SystemRandom::new(),
105 state: Mutex::new(State {
106 security_level: keystore_service
107 .getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT)
108 .unwrap(),
109 }),
110 }
111 }
112
113 fn security_level(&self) -> Strong<dyn IKeystoreSecurityLevel> {
114 // We need the Mutex because Strong<_> isn't sync. But we don't need to keep it locked
115 // to make the call, once we've cloned the pointer.
116 self.state.lock().unwrap().security_level.clone()
117 }
118
119 fn do_generate(&self) -> Result<CompOsKeyData> {
120 let key_parameters =
121 [PURPOSE_SIGN, ALGORITHM, PADDING, DIGEST, KEY_SIZE, EXPONENT, NO_AUTH_REQUIRED];
122 let attestation_key = None;
123 let flags = 0;
124 let entropy = [];
125
126 let key_metadata = self
127 .security_level()
128 .generateKey(&KEY_DESCRIPTOR, attestation_key, &key_parameters, flags, &entropy)
129 .context("Generating key failed")?;
130
131 if let (Some(certificate), Some(blob)) = (key_metadata.certificate, key_metadata.key.blob) {
132 Ok(CompOsKeyData { certificate, keyBlob: blob })
133 } else {
134 Err(anyhow!("Missing cert or blob"))
135 }
136 }
137
138 fn do_verify(&self, key_blob: &[u8], public_key: &[u8]) -> Result<()> {
139 let mut data = [0u8; 32];
140 self.random.fill(&mut data).context("No random data")?;
141
142 let signature = self.sign(key_blob, &data)?;
143
144 let public_key =
145 signature::UnparsedPublicKey::new(&signature::RSA_PKCS1_2048_8192_SHA256, public_key);
146 public_key.verify(&data, &signature).context("Signature verification failed")?;
147
148 Ok(())
149 }
150
151 fn sign(&self, key_blob: &[u8], data: &[u8]) -> Result<Vec<u8>> {
152 let key_descriptor = KeyDescriptor { blob: Some(key_blob.to_vec()), ..KEY_DESCRIPTOR };
153 let operation_parameters = [PURPOSE_SIGN, ALGORITHM, PADDING, DIGEST];
154 let forced = false;
155
156 let response = self
157 .security_level()
158 .createOperation(&key_descriptor, &operation_parameters, forced)
159 .context("Creating key failed")?;
160 let operation = scopeguard::guard(
161 response.iOperation.ok_or_else(|| anyhow!("No operation created"))?,
162 |op| op.abort().unwrap_or_default(),
163 );
164
165 if response.operationChallenge.is_some() {
166 return Err(anyhow!("Key requires user authorization"));
167 }
168
169 let signature = operation.finish(Some(&data), None).context("Signing failed")?;
170 // Operation has finished, we're no longer responsible for aborting it
171 ScopeGuard::into_inner(operation);
172
173 signature.ok_or_else(|| anyhow!("No signature returned"))
174 }
175}
176
177fn main() -> Result<()> {
178 android_logger::init_once(
179 android_logger::Config::default().with_tag(LOG_TAG).with_min_level(Level::Trace),
180 );
181
182 // We need to start the thread pool for Binder to work properly.
183 ProcessState::start_thread_pool();
184
185 let keystore_service = get_interface::<dyn IKeystoreService>(KEYSTORE_SERVICE_NAME)
186 .context("No Keystore service")?;
187 let service = CompOsKeyService::new(&keystore_service);
188 let service = BnCompOsKeyService::new_binder(service, BinderFeatures::default());
189
190 add_service(OUR_SERVICE_NAME, service.as_binder()).context("Adding service failed")?;
191 info!("It's alive!");
192
193 ProcessState::join_thread_pool();
194
195 Ok(())
196}