blob: 0b5c77a046e109c8f84e861a5fce2cef19bddd6e [file] [log] [blame]
Janis Danisevskis1af91262020-08-10 14:58:08 -07001// Copyright 2020, 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//! This crate implements the `IKeystoreOperation` AIDL interface, which represents
16//! an ongoing key operation, as well as the operation database, which is mainly
17//! required for tracking operations for the purpose of pruning.
18//! This crate also implements an operation pruning strategy.
19//!
20//! Operations implement the API calls update, finish, and abort.
21//! Additionally, an operation can be dropped and pruned. The former
22//! happens if the client deletes a binder to the operation object.
23//! An existing operation may get pruned when running out of operation
24//! slots and a new operation takes precedence.
25//!
26//! ## Operation Lifecycle
27//! An operation gets created when the client calls `IKeystoreSecurityLevel::create`.
28//! It may receive zero or more update request. The lifecycle ends when:
29//! * `update` yields an error.
30//! * `finish` is called.
31//! * `abort` is called.
32//! * The operation gets dropped.
33//! * The operation gets pruned.
34//! `Operation` has an `Outcome` member. While the outcome is `Outcome::Unknown`,
35//! the operation is active and in a good state. Any of the above conditions may
36//! change the outcome to one of the defined outcomes Success, Abort, Dropped,
37//! Pruned, or ErrorCode. The latter is chosen in the case of an unexpected error, during
38//! `update` or `finish`. `Success` is chosen iff `finish` completes without error.
39//! Note that all operations get dropped eventually in the sense that they lose
40//! their last reference and get destroyed. At that point, the fate of the operation
41//! gets logged. However, an operation will transition to `Outcome::Dropped` iff
42//! the operation was still active (`Outcome::Unknown`) at that time.
43//!
44//! ## Operation Dropping
45//! To observe the dropping of an operation, we have to make sure that there
46//! are no strong references to the IBinder representing this operation.
47//! This would be simple enough if the operation object would need to be accessed
48//! only by transactions. But to perform pruning, we have to retain a reference to the
49//! original operation object.
50//!
51//! ## Operation Pruning
52//! Pruning an operation happens during the creation of a new operation.
53//! We have to iterate through the operation database to find a suitable
54//! candidate. Then we abort and finalize this operation setting its outcome to
55//! `Outcome::Pruned`. The corresponding KeyMint operation slot will have been freed
56//! up at this point, but the `Operation` object lingers. When the client
57//! attempts to use the operation again they will receive
58//! ErrorCode::INVALID_OPERATION_HANDLE indicating that the operation no longer
59//! exits. This should be the cue for the client to destroy its binder.
60//! At that point the operation gets dropped.
61//!
62//! ## Architecture
63//! The `IKeystoreOperation` trait is implemented by `KeystoreOperation`.
64//! This acts as a proxy object holding a strong reference to actual operation
65//! implementation `Operation`.
66//!
67//! ```
68//! struct KeystoreOperation {
69//! operation: Mutex<Option<Arc<Operation>>>,
70//! }
71//! ```
72//!
73//! The `Mutex` serves two purposes. It provides interior mutability allowing
74//! us to set the Option to None. We do this when the life cycle ends during
75//! a call to `update`, `finish`, or `abort`. As a result most of the Operation
76//! related resources are freed. The `KeystoreOperation` proxy object still
77//! lingers until dropped by the client.
78//! The second purpose is to protect operations against concurrent usage.
79//! Failing to lock this mutex yields `ResponseCode::OPERATION_BUSY` and indicates
80//! a programming error in the client.
81//!
82//! Note that the Mutex only protects the operation against concurrent client calls.
83//! We still retain weak references to the operation in the operation database:
84//!
85//! ```
86//! struct OperationDb {
87//! operations: Mutex<Vec<Weak<Operation>>>
88//! }
89//! ```
90//!
91//! This allows us to access the operations for the purpose of pruning.
92//! We do this in three phases.
93//! 1. We gather the pruning information. Besides non mutable information,
94//! we access `last_usage` which is protected by a mutex.
95//! We only lock this mutex for single statements at a time. During
96//! this phase we hold the operation db lock.
97//! 2. We choose a pruning candidate by computing the pruning resistance
98//! of each operation. We do this entirely with information we now
99//! have on the stack without holding any locks.
100//! (See `OperationDb::prune` for more details on the pruning strategy.)
101//! 3. During pruning we briefly lock the operation database again to get the
102//! the pruning candidate by index. We then attempt to abort the candidate.
103//! If the candidate was touched in the meantime or is currently fulfilling
104//! a request (i.e., the client calls update, finish, or abort),
105//! we go back to 1 and try again.
106//!
107//! So the outer Mutex in `KeystoreOperation::operation` only protects
108//! operations against concurrent client calls but not against concurrent
109//! pruning attempts. This is what the `Operation::outcome` mutex is used for.
110//!
111//! ```
112//! struct Operation {
113//! ...
114//! outcome: Mutex<Outcome>,
115//! ...
116//! }
117//! ```
118//!
119//! Any request that can change the outcome, i.e., `update`, `finish`, `abort`,
120//! `drop`, and `prune` has to take the outcome lock and check if the outcome
121//! is still `Outcome::Unknown` before entering. `prune` is special in that
122//! it will `try_lock`, because we don't want to be blocked on a potentially
123//! long running request at another operation. If it fails to get the lock
124//! the operation is either being touched, which changes its pruning resistance,
125//! or it transitions to its end-of-life, which means we may get a free slot.
126//! Either way, we have to revaluate the pruning scores.
127
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800128use crate::enforcements::AuthInfo;
Janis Danisevskis778245c2021-03-04 15:40:23 -0800129use crate::error::{map_err_with, map_km_error, map_or_log_err, Error, ErrorCode, ResponseCode};
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000130use crate::metrics::log_key_operation_event_stats;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000131use crate::utils::Asp;
132use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000133 IKeyMintOperation::IKeyMintOperation, KeyParameter::KeyParameter, KeyPurpose::KeyPurpose,
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000134 SecurityLevel::SecurityLevel,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000135};
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000136use android_hardware_security_keymint::binder::BinderFeatures;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000137use android_system_keystore2::aidl::android::system::keystore2::{
138 IKeystoreOperation::BnKeystoreOperation, IKeystoreOperation::IKeystoreOperation,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000139};
140use anyhow::{anyhow, Context, Result};
Janis Danisevskis1af91262020-08-10 14:58:08 -0700141use std::{
142 collections::HashMap,
143 sync::{Arc, Mutex, MutexGuard, Weak},
144 time::Duration,
145 time::Instant,
146};
147
Janis Danisevskis1af91262020-08-10 14:58:08 -0700148/// Operations have `Outcome::Unknown` as long as they are active. They transition
149/// to one of the other variants exactly once. The distinction in outcome is mainly
150/// for the statistic.
151#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000152pub enum Outcome {
153 /// Operations have `Outcome::Unknown` as long as they are active.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700154 Unknown,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000155 /// Operation is successful.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700156 Success,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000157 /// Operation is aborted.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700158 Abort,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000159 /// Operation is dropped.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700160 Dropped,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000161 /// Operation is pruned.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700162 Pruned,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000163 /// Operation is failed with the error code.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700164 ErrorCode(ErrorCode),
165}
166
167/// Operation bundles all of the operation related resources and tracks the operation's
168/// outcome.
169#[derive(Debug)]
170pub struct Operation {
171 // The index of this operation in the OperationDb.
172 index: usize,
173 km_op: Asp,
174 last_usage: Mutex<Instant>,
175 outcome: Mutex<Outcome>,
176 owner: u32, // Uid of the operation's owner.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800177 auth_info: Mutex<AuthInfo>,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800178 forced: bool,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000179 logging_info: LoggingInfo,
180}
181
182/// Keeps track of the information required for logging operations.
183#[derive(Debug)]
184pub struct LoggingInfo {
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000185 sec_level: SecurityLevel,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000186 purpose: KeyPurpose,
187 op_params: Vec<KeyParameter>,
188 key_upgraded: bool,
189}
190
191impl LoggingInfo {
192 /// Constructor
193 pub fn new(
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000194 sec_level: SecurityLevel,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000195 purpose: KeyPurpose,
196 op_params: Vec<KeyParameter>,
197 key_upgraded: bool,
198 ) -> LoggingInfo {
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000199 Self { sec_level, purpose, op_params, key_upgraded }
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000200 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700201}
202
203struct PruningInfo {
204 last_usage: Instant,
205 owner: u32,
206 index: usize,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800207 forced: bool,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700208}
209
Janis Danisevskis1af91262020-08-10 14:58:08 -0700210// We don't except more than 32KiB of data in `update`, `updateAad`, and `finish`.
211const MAX_RECEIVE_DATA: usize = 0x8000;
212
213impl Operation {
214 /// Constructor
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000215 pub fn new(
216 index: usize,
Stephen Crane221bbb52020-12-16 15:52:10 -0800217 km_op: binder::Strong<dyn IKeyMintOperation>,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000218 owner: u32,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800219 auth_info: AuthInfo,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800220 forced: bool,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000221 logging_info: LoggingInfo,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000222 ) -> Self {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700223 Self {
224 index,
225 km_op: Asp::new(km_op.as_binder()),
226 last_usage: Mutex::new(Instant::now()),
227 outcome: Mutex::new(Outcome::Unknown),
228 owner,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800229 auth_info: Mutex::new(auth_info),
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800230 forced,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000231 logging_info,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700232 }
233 }
234
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700235 fn get_pruning_info(&self) -> Option<PruningInfo> {
236 // An operation may be finalized.
237 if let Ok(guard) = self.outcome.try_lock() {
238 match *guard {
239 Outcome::Unknown => {}
240 // If the outcome is any other than unknown, it has been finalized,
241 // and we can no longer consider it for pruning.
242 _ => return None,
243 }
244 }
245 // Else: If we could not grab the lock, this means that the operation is currently
246 // being used and it may be transitioning to finalized or it was simply updated.
247 // In any case it is fair game to consider it for pruning. If the operation
248 // transitioned to a final state, we will notice when we attempt to prune, and
249 // a subsequent attempt to create a new operation will succeed.
250 Some(PruningInfo {
251 // Expect safety:
252 // `last_usage` is locked only for primitive single line statements.
253 // There is no chance to panic and poison the mutex.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700254 last_usage: *self.last_usage.lock().expect("In get_pruning_info."),
255 owner: self.owner,
256 index: self.index,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800257 forced: self.forced,
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700258 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700259 }
260
261 fn prune(&self, last_usage: Instant) -> Result<(), Error> {
262 let mut locked_outcome = match self.outcome.try_lock() {
263 Ok(guard) => match *guard {
264 Outcome::Unknown => guard,
265 _ => return Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)),
266 },
267 Err(_) => return Err(Error::Rc(ResponseCode::OPERATION_BUSY)),
268 };
269
270 // In `OperationDb::prune`, which is our caller, we first gather the pruning
271 // information including the last usage. When we select a candidate
272 // we call `prune` on that candidate passing the last_usage
273 // that we gathered earlier. If the actual last usage
274 // has changed since than, it means the operation was busy in the
275 // meantime, which means that we have to reevaluate the pruning score.
276 //
277 // Expect safety:
278 // `last_usage` is locked only for primitive single line statements.
279 // There is no chance to panic and poison the mutex.
280 if *self.last_usage.lock().expect("In Operation::prune()") != last_usage {
281 return Err(Error::Rc(ResponseCode::OPERATION_BUSY));
282 }
283 *locked_outcome = Outcome::Pruned;
284
Stephen Crane221bbb52020-12-16 15:52:10 -0800285 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
286 match self.km_op.get_interface() {
287 Ok(km_op) => km_op,
288 Err(e) => {
289 log::error!("In prune: Failed to get KeyMintOperation interface.\n {:?}", e);
290 return Err(Error::sys());
291 }
292 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700293
294 // We abort the operation. If there was an error we log it but ignore it.
295 if let Err(e) = map_km_error(km_op.abort()) {
296 log::error!("In prune: KeyMint::abort failed with {:?}.", e);
297 }
298
299 Ok(())
300 }
301
302 // This function takes a Result from a KeyMint call and inspects it for errors.
303 // If an error was found it updates the given `locked_outcome` accordingly.
304 // It forwards the Result unmodified.
305 // The precondition to this call must be *locked_outcome == Outcome::Unknown.
306 // Ideally the `locked_outcome` came from a successful call to `check_active`
307 // see below.
308 fn update_outcome<T>(
309 &self,
310 locked_outcome: &mut Outcome,
311 err: Result<T, Error>,
312 ) -> Result<T, Error> {
313 match &err {
314 Err(Error::Km(e)) => *locked_outcome = Outcome::ErrorCode(*e),
315 Err(_) => *locked_outcome = Outcome::ErrorCode(ErrorCode::UNKNOWN_ERROR),
316 Ok(_) => (),
317 }
318 err
319 }
320
321 // This function grabs the outcome lock and checks the current outcome state.
322 // If the outcome is still `Outcome::Unknown`, this function returns
323 // the locked outcome for further updates. In any other case it returns
324 // ErrorCode::INVALID_OPERATION_HANDLE indicating that this operation has
325 // been finalized and is no longer active.
326 fn check_active(&self) -> Result<MutexGuard<Outcome>> {
327 let guard = self.outcome.lock().expect("In check_active.");
328 match *guard {
329 Outcome::Unknown => Ok(guard),
330 _ => Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)).context(format!(
331 "In check_active: Call on finalized operation with outcome: {:?}.",
332 *guard
333 )),
334 }
335 }
336
337 // This function checks the amount of input data sent to us. We reject any buffer
338 // exceeding MAX_RECEIVE_DATA bytes as input to `update`, `update_aad`, and `finish`
339 // in order to force clients into using reasonable limits.
340 fn check_input_length(data: &[u8]) -> Result<()> {
341 if data.len() > MAX_RECEIVE_DATA {
342 // This error code is unique, no context required here.
343 return Err(anyhow!(Error::Rc(ResponseCode::TOO_MUCH_DATA)));
344 }
345 Ok(())
346 }
347
348 // Update the last usage to now.
349 fn touch(&self) {
350 // Expect safety:
351 // `last_usage` is locked only for primitive single line statements.
352 // There is no chance to panic and poison the mutex.
353 *self.last_usage.lock().expect("In touch.") = Instant::now();
354 }
355
356 /// Implementation of `IKeystoreOperation::updateAad`.
357 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
358 fn update_aad(&self, aad_input: &[u8]) -> Result<()> {
359 let mut outcome = self.check_active().context("In update_aad")?;
360 Self::check_input_length(aad_input).context("In update_aad")?;
361 self.touch();
362
Stephen Crane221bbb52020-12-16 15:52:10 -0800363 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700364 self.km_op.get_interface().context("In update: Failed to get KeyMintOperation.")?;
365
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800366 let (hat, tst) = self
367 .auth_info
368 .lock()
369 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800370 .before_update()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800371 .context("In update_aad: Trying to get auth tokens.")?;
372
Janis Danisevskis1af91262020-08-10 14:58:08 -0700373 self.update_outcome(
374 &mut *outcome,
Shawn Willden44cc03d2021-02-19 10:53:49 -0700375 map_km_error(km_op.updateAad(aad_input, hat.as_ref(), tst.as_ref())),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700376 )
377 .context("In update_aad: KeyMint::update failed.")?;
378
379 Ok(())
380 }
381
382 /// Implementation of `IKeystoreOperation::update`.
383 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
384 fn update(&self, input: &[u8]) -> Result<Option<Vec<u8>>> {
385 let mut outcome = self.check_active().context("In update")?;
386 Self::check_input_length(input).context("In update")?;
387 self.touch();
388
Stephen Crane221bbb52020-12-16 15:52:10 -0800389 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700390 self.km_op.get_interface().context("In update: Failed to get KeyMintOperation.")?;
391
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800392 let (hat, tst) = self
393 .auth_info
394 .lock()
395 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800396 .before_update()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800397 .context("In update: Trying to get auth tokens.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000398
Shawn Willden44cc03d2021-02-19 10:53:49 -0700399 let output = self
400 .update_outcome(
401 &mut *outcome,
402 map_km_error(km_op.update(input, hat.as_ref(), tst.as_ref())),
403 )
404 .context("In update: KeyMint::update failed.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700405
Shawn Willden44cc03d2021-02-19 10:53:49 -0700406 if output.is_empty() {
407 Ok(None)
408 } else {
409 Ok(Some(output))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700410 }
411 }
412
413 /// Implementation of `IKeystoreOperation::finish`.
414 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
415 fn finish(&self, input: Option<&[u8]>, signature: Option<&[u8]>) -> Result<Option<Vec<u8>>> {
416 let mut outcome = self.check_active().context("In finish")?;
417 if let Some(input) = input {
418 Self::check_input_length(input).context("In finish")?;
419 }
420 self.touch();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700421
Stephen Crane221bbb52020-12-16 15:52:10 -0800422 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700423 self.km_op.get_interface().context("In finish: Failed to get KeyMintOperation.")?;
424
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800425 let (hat, tst, confirmation_token) = self
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800426 .auth_info
427 .lock()
428 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800429 .before_finish()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800430 .context("In finish: Trying to get auth tokens.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000431
Janis Danisevskis85d47932020-10-23 16:12:59 -0700432 let output = self
433 .update_outcome(
434 &mut *outcome,
435 map_km_error(km_op.finish(
Janis Danisevskis85d47932020-10-23 16:12:59 -0700436 input,
437 signature,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800438 hat.as_ref(),
439 tst.as_ref(),
Shawn Willden44cc03d2021-02-19 10:53:49 -0700440 confirmation_token.as_deref(),
Janis Danisevskis85d47932020-10-23 16:12:59 -0700441 )),
442 )
443 .context("In finish: KeyMint::finish failed.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700444
Qi Wub9433b52020-12-01 14:52:46 +0800445 self.auth_info.lock().unwrap().after_finish().context("In finish.")?;
446
Janis Danisevskis1af91262020-08-10 14:58:08 -0700447 // At this point the operation concluded successfully.
448 *outcome = Outcome::Success;
449
450 if output.is_empty() {
451 Ok(None)
452 } else {
453 Ok(Some(output))
454 }
455 }
456
457 /// Aborts the operation if it is active. IFF the operation is aborted the outcome is
458 /// set to `outcome`. `outcome` must reflect the reason for the abort. Since the operation
459 /// gets aborted `outcome` must not be `Operation::Success` or `Operation::Unknown`.
460 fn abort(&self, outcome: Outcome) -> Result<()> {
461 let mut locked_outcome = self.check_active().context("In abort")?;
462 *locked_outcome = outcome;
Stephen Crane221bbb52020-12-16 15:52:10 -0800463 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700464 self.km_op.get_interface().context("In abort: Failed to get KeyMintOperation.")?;
465
466 map_km_error(km_op.abort()).context("In abort: KeyMint::abort failed.")
467 }
468}
469
470impl Drop for Operation {
471 fn drop(&mut self) {
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000472 let guard = self.outcome.lock().expect("In drop.");
473 log_key_operation_event_stats(
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000474 self.logging_info.sec_level,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000475 self.logging_info.purpose,
476 &(self.logging_info.op_params),
477 &guard,
478 self.logging_info.key_upgraded,
479 );
480 if let Outcome::Unknown = *guard {
481 drop(guard);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700482 // If the operation was still active we call abort, setting
483 // the outcome to `Outcome::Dropped`
484 if let Err(e) = self.abort(Outcome::Dropped) {
485 log::error!("While dropping Operation: abort failed:\n {:?}", e);
486 }
487 }
488 }
489}
490
491/// The OperationDb holds weak references to all ongoing operations.
492/// Its main purpose is to facilitate operation pruning.
493#[derive(Debug, Default)]
494pub struct OperationDb {
495 // TODO replace Vec with WeakTable when the weak_table crate becomes
496 // available.
497 operations: Mutex<Vec<Weak<Operation>>>,
498}
499
500impl OperationDb {
501 /// Creates a new OperationDb.
502 pub fn new() -> Self {
503 Self { operations: Mutex::new(Vec::new()) }
504 }
505
506 /// Creates a new operation.
507 /// This function takes a KeyMint operation and an associated
508 /// owner uid and returns a new Operation wrapped in a `std::sync::Arc`.
509 pub fn create_operation(
510 &self,
Stephen Crane221bbb52020-12-16 15:52:10 -0800511 km_op: binder::public_api::Strong<dyn IKeyMintOperation>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700512 owner: u32,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800513 auth_info: AuthInfo,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800514 forced: bool,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000515 logging_info: LoggingInfo,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700516 ) -> Arc<Operation> {
517 // We use unwrap because we don't allow code that can panic while locked.
518 let mut operations = self.operations.lock().expect("In create_operation.");
519
520 let mut index: usize = 0;
521 // First we iterate through the operation slots to try and find an unused
522 // slot. If we don't find one, we append the new entry instead.
523 match (*operations).iter_mut().find(|s| {
524 index += 1;
525 s.upgrade().is_none()
526 }) {
527 Some(free_slot) => {
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000528 let new_op = Arc::new(Operation::new(
529 index - 1,
530 km_op,
531 owner,
532 auth_info,
533 forced,
534 logging_info,
535 ));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700536 *free_slot = Arc::downgrade(&new_op);
537 new_op
538 }
539 None => {
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000540 let new_op = Arc::new(Operation::new(
541 operations.len(),
542 km_op,
543 owner,
544 auth_info,
545 forced,
546 logging_info,
547 ));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700548 operations.push(Arc::downgrade(&new_op));
549 new_op
550 }
551 }
552 }
553
554 fn get(&self, index: usize) -> Option<Arc<Operation>> {
555 self.operations.lock().expect("In OperationDb::get.").get(index).and_then(|op| op.upgrade())
556 }
557
558 /// Attempts to prune an operation.
559 ///
560 /// This function is used during operation creation, i.e., by
561 /// `KeystoreSecurityLevel::create_operation`, to try and free up an operation slot
562 /// if it got `ErrorCode::TOO_MANY_OPERATIONS` from the KeyMint backend. It is not
563 /// guaranteed that an operation slot is available after this call successfully
564 /// returned for various reasons. E.g., another thread may have snatched up the newly
565 /// available slot. Callers may have to call prune multiple times before they get a
566 /// free operation slot. Prune may also return `Err(Error::Rc(ResponseCode::BACKEND_BUSY))`
567 /// which indicates that no prunable operation was found.
568 ///
569 /// To find a suitable candidate we compute the malus for the caller and each existing
570 /// operation. The malus is the inverse of the pruning power (caller) or pruning
571 /// resistance (existing operation).
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700572 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700573 /// The malus is based on the number of sibling operations and age. Sibling
574 /// operations are operations that have the same owner (UID).
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700575 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700576 /// Every operation, existing or new, starts with a malus of 1. Every sibling
577 /// increases the malus by one. The age is the time since an operation was last touched.
578 /// It increases the malus by log6(<age in seconds> + 1) rounded down to the next
579 /// integer. So the malus increases stepwise after 5s, 35s, 215s, ...
580 /// Of two operations with the same malus the least recently used one is considered
581 /// weaker.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700582 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700583 /// For the caller to be able to prune an operation it must find an operation
584 /// with a malus higher than its own.
585 ///
586 /// The malus can be expressed as
587 /// ```
588 /// malus = 1 + no_of_siblings + floor(log6(age_in_seconds + 1))
589 /// ```
590 /// where the constant `1` accounts for the operation under consideration.
591 /// In reality we compute it as
592 /// ```
593 /// caller_malus = 1 + running_siblings
594 /// ```
595 /// because the new operation has no age and is not included in the `running_siblings`,
596 /// and
597 /// ```
598 /// running_malus = running_siblings + floor(log6(age_in_seconds + 1))
599 /// ```
600 /// because a running operation is included in the `running_siblings` and it has
601 /// an age.
602 ///
603 /// ## Example
604 /// A caller with no running operations has a malus of 1. Young (age < 5s) operations
605 /// also with no siblings have a malus of one and cannot be pruned by the caller.
606 /// We have to find an operation that has at least one sibling or is older than 5s.
607 ///
608 /// A caller with one running operation has a malus of 2. Now even young siblings
609 /// or single child aging (5s <= age < 35s) operations are off limit. An aging
610 /// sibling of two, however, would have a malus of 3 and would be fair game.
611 ///
612 /// ## Rationale
613 /// Due to the limitation of KeyMint operation slots, we cannot get around pruning or
614 /// a single app could easily DoS KeyMint.
615 /// Keystore 1.0 used to always prune the least recently used operation. This at least
616 /// guaranteed that new operations can always be started. With the increased usage
617 /// of Keystore we saw increased pruning activity which can lead to a livelock
618 /// situation in the worst case.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700619 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700620 /// With the new pruning strategy we want to provide well behaved clients with
621 /// progress assurances while punishing DoS attempts. As a result of this
622 /// strategy we can be in the situation where no operation can be pruned and the
623 /// creation of a new operation fails. This allows single child operations which
624 /// are frequently updated to complete, thereby breaking up livelock situations
625 /// and facilitating system wide progress.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700626 ///
627 /// ## Update
628 /// We also allow callers to cannibalize their own sibling operations if no other
629 /// slot can be found. In this case the least recently used sibling is pruned.
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800630 pub fn prune(&self, caller: u32, forced: bool) -> Result<(), Error> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700631 loop {
632 // Maps the uid of the owner to the number of operations that owner has
633 // (running_siblings). More operations per owner lowers the pruning
634 // resistance of the operations of that owner. Whereas the number of
635 // ongoing operations of the caller lowers the pruning power of the caller.
636 let mut owners: HashMap<u32, u64> = HashMap::new();
637 let mut pruning_info: Vec<PruningInfo> = Vec::new();
638
639 let now = Instant::now();
640 self.operations
641 .lock()
642 .expect("In OperationDb::prune: Trying to lock self.operations.")
643 .iter()
644 .for_each(|op| {
645 if let Some(op) = op.upgrade() {
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700646 if let Some(p_info) = op.get_pruning_info() {
647 let owner = p_info.owner;
648 pruning_info.push(p_info);
649 // Count operations per owner.
650 *owners.entry(owner).or_insert(0) += 1;
651 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700652 }
653 });
654
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800655 // If the operation is forced, the caller has a malus of 0.
656 let caller_malus = if forced { 0 } else { 1u64 + *owners.entry(caller).or_default() };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700657
658 // We iterate through all operations computing the malus and finding
659 // the candidate with the highest malus which must also be higher
660 // than the caller_malus.
661 struct CandidateInfo {
662 index: usize,
663 malus: u64,
664 last_usage: Instant,
665 age: Duration,
666 }
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700667 let mut oldest_caller_op: Option<CandidateInfo> = None;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700668 let candidate = pruning_info.iter().fold(
669 None,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800670 |acc: Option<CandidateInfo>, &PruningInfo { last_usage, owner, index, forced }| {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700671 // Compute the age of the current operation.
672 let age = now
673 .checked_duration_since(last_usage)
674 .unwrap_or_else(|| Duration::new(0, 0));
675
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700676 // Find the least recently used sibling as an alternative pruning candidate.
677 if owner == caller {
678 if let Some(CandidateInfo { age: a, .. }) = oldest_caller_op {
679 if age > a {
680 oldest_caller_op =
681 Some(CandidateInfo { index, malus: 0, last_usage, age });
682 }
683 } else {
684 oldest_caller_op =
685 Some(CandidateInfo { index, malus: 0, last_usage, age });
686 }
687 }
688
Janis Danisevskis1af91262020-08-10 14:58:08 -0700689 // Compute the malus of the current operation.
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800690 let malus = if forced {
691 // Forced operations have a malus of 0. And cannot even be pruned
692 // by other forced operations.
693 0
694 } else {
695 // Expect safety: Every owner in pruning_info was counted in
696 // the owners map. So this unwrap cannot panic.
697 *owners.get(&owner).expect(
698 "This is odd. We should have counted every owner in pruning_info.",
699 ) + ((age.as_secs() + 1) as f64).log(6.0).floor() as u64
700 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700701
702 // Now check if the current operation is a viable/better candidate
703 // the one currently stored in the accumulator.
704 match acc {
705 // First we have to find any operation that is prunable by the caller.
706 None => {
707 if caller_malus < malus {
708 Some(CandidateInfo { index, malus, last_usage, age })
709 } else {
710 None
711 }
712 }
713 // If we have found one we look for the operation with the worst score.
714 // If there is a tie, the older operation is considered weaker.
715 Some(CandidateInfo { index: i, malus: m, last_usage: l, age: a }) => {
716 if malus > m || (malus == m && age > a) {
717 Some(CandidateInfo { index, malus, last_usage, age })
718 } else {
719 Some(CandidateInfo { index: i, malus: m, last_usage: l, age: a })
720 }
721 }
722 }
723 },
724 );
725
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700726 // If we did not find a suitable candidate we may cannibalize our oldest sibling.
727 let candidate = candidate.or(oldest_caller_op);
728
Janis Danisevskis1af91262020-08-10 14:58:08 -0700729 match candidate {
730 Some(CandidateInfo { index, malus: _, last_usage, age: _ }) => {
731 match self.get(index) {
732 Some(op) => {
733 match op.prune(last_usage) {
734 // We successfully freed up a slot.
735 Ok(()) => break Ok(()),
736 // This means the operation we tried to prune was on its way
737 // out. It also means that the slot it had occupied was freed up.
738 Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)) => break Ok(()),
739 // This means the operation we tried to prune was currently
740 // servicing a request. There are two options.
741 // * Assume that it was touched, which means that its
742 // pruning resistance increased. In that case we have
743 // to start over and find another candidate.
744 // * Assume that the operation is transitioning to end-of-life.
745 // which means that we got a free slot for free.
746 // If we assume the first but the second is true, we prune
747 // a good operation without need (aggressive approach).
748 // If we assume the second but the first is true, our
749 // caller will attempt to create a new KeyMint operation,
750 // fail with `ErrorCode::TOO_MANY_OPERATIONS`, and call
751 // us again (conservative approach).
752 Err(Error::Rc(ResponseCode::OPERATION_BUSY)) => {
753 // We choose the conservative approach, because
754 // every needlessly pruned operation can impact
755 // the user experience.
756 // To switch to the aggressive approach replace
757 // the following line with `continue`.
758 break Ok(());
759 }
760
761 // The candidate may have been touched so the score
762 // has changed since our evaluation.
763 _ => continue,
764 }
765 }
766 // This index does not exist any more. The operation
767 // in this slot was dropped. Good news, a slot
768 // has freed up.
769 None => break Ok(()),
770 }
771 }
772 // We did not get a pruning candidate.
773 None => break Err(Error::Rc(ResponseCode::BACKEND_BUSY)),
774 }
775 }
776 }
777}
778
779/// Implementation of IKeystoreOperation.
780pub struct KeystoreOperation {
781 operation: Mutex<Option<Arc<Operation>>>,
782}
783
784impl KeystoreOperation {
785 /// Creates a new operation instance wrapped in a
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000786 /// BnKeystoreOperation proxy object. It also enables
787 /// `BinderFeatures::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -0700788 /// we need it for checking Keystore permissions.
Stephen Crane221bbb52020-12-16 15:52:10 -0800789 pub fn new_native_binder(
790 operation: Arc<Operation>,
791 ) -> binder::public_api::Strong<dyn IKeystoreOperation> {
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000792 BnKeystoreOperation::new_binder(
793 Self { operation: Mutex::new(Some(operation)) },
794 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
795 )
Janis Danisevskis1af91262020-08-10 14:58:08 -0700796 }
797
798 /// Grabs the outer operation mutex and calls `f` on the locked operation.
799 /// The function also deletes the operation if it returns with an error or if
800 /// `delete_op` is true.
801 fn with_locked_operation<T, F>(&self, f: F, delete_op: bool) -> Result<T>
802 where
803 for<'a> F: FnOnce(&'a Operation) -> Result<T>,
804 {
805 let mut delete_op: bool = delete_op;
806 match self.operation.try_lock() {
807 Ok(mut mutex_guard) => {
808 let result = match &*mutex_guard {
809 Some(op) => {
810 let result = f(&*op);
811 // Any error here means we can discard the operation.
812 if result.is_err() {
813 delete_op = true;
814 }
815 result
816 }
817 None => Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE))
818 .context("In KeystoreOperation::with_locked_operation"),
819 };
820
821 if delete_op {
822 // We give up our reference to the Operation, thereby freeing up our
823 // internal resources and ending the wrapped KeyMint operation.
824 // This KeystoreOperation object will still be owned by an SpIBinder
825 // until the client drops its remote reference.
826 *mutex_guard = None;
827 }
828 result
829 }
830 Err(_) => Err(Error::Rc(ResponseCode::OPERATION_BUSY))
831 .context("In KeystoreOperation::with_locked_operation"),
832 }
833 }
834}
835
836impl binder::Interface for KeystoreOperation {}
837
838impl IKeystoreOperation for KeystoreOperation {
839 fn updateAad(&self, aad_input: &[u8]) -> binder::public_api::Result<()> {
840 map_or_log_err(
841 self.with_locked_operation(
842 |op| op.update_aad(aad_input).context("In KeystoreOperation::updateAad"),
843 false,
844 ),
845 Ok,
846 )
847 }
848
849 fn update(&self, input: &[u8]) -> binder::public_api::Result<Option<Vec<u8>>> {
850 map_or_log_err(
851 self.with_locked_operation(
852 |op| op.update(input).context("In KeystoreOperation::update"),
853 false,
854 ),
855 Ok,
856 )
857 }
858 fn finish(
859 &self,
860 input: Option<&[u8]>,
861 signature: Option<&[u8]>,
862 ) -> binder::public_api::Result<Option<Vec<u8>>> {
863 map_or_log_err(
864 self.with_locked_operation(
865 |op| op.finish(input, signature).context("In KeystoreOperation::finish"),
866 true,
867 ),
868 Ok,
869 )
870 }
871
872 fn abort(&self) -> binder::public_api::Result<()> {
Janis Danisevskis778245c2021-03-04 15:40:23 -0800873 map_err_with(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700874 self.with_locked_operation(
875 |op| op.abort(Outcome::Abort).context("In KeystoreOperation::abort"),
876 true,
877 ),
Janis Danisevskis778245c2021-03-04 15:40:23 -0800878 |e| {
879 match e.root_cause().downcast_ref::<Error>() {
880 // Calling abort on expired operations is something very common.
881 // There is no reason to clutter the log with it. It is never the cause
882 // for a true problem.
883 Some(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)) => {}
884 _ => log::error!("{:?}", e),
885 };
886 e
887 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700888 Ok,
889 )
890 }
891}