blob: 5cc38cc6ee9712ab9a6250c82a220eee61b7e4d9 [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 Gunasinghe888dd352020-11-17 23:08:39 +0000130use crate::utils::Asp;
131use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Shawn Willden44cc03d2021-02-19 10:53:49 -0700132 IKeyMintOperation::IKeyMintOperation,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000133};
134use android_system_keystore2::aidl::android::system::keystore2::{
135 IKeystoreOperation::BnKeystoreOperation, IKeystoreOperation::IKeystoreOperation,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000136};
137use anyhow::{anyhow, Context, Result};
Andrew Walbran808e8602021-03-16 13:58:28 +0000138use binder::IBinderInternal;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700139use std::{
140 collections::HashMap,
141 sync::{Arc, Mutex, MutexGuard, Weak},
142 time::Duration,
143 time::Instant,
144};
145
Janis Danisevskis1af91262020-08-10 14:58:08 -0700146/// Operations have `Outcome::Unknown` as long as they are active. They transition
147/// to one of the other variants exactly once. The distinction in outcome is mainly
148/// for the statistic.
149#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
150enum Outcome {
151 Unknown,
152 Success,
153 Abort,
154 Dropped,
155 Pruned,
156 ErrorCode(ErrorCode),
157}
158
159/// Operation bundles all of the operation related resources and tracks the operation's
160/// outcome.
161#[derive(Debug)]
162pub struct Operation {
163 // The index of this operation in the OperationDb.
164 index: usize,
165 km_op: Asp,
166 last_usage: Mutex<Instant>,
167 outcome: Mutex<Outcome>,
168 owner: u32, // Uid of the operation's owner.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800169 auth_info: Mutex<AuthInfo>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700170}
171
172struct PruningInfo {
173 last_usage: Instant,
174 owner: u32,
175 index: usize,
176}
177
Janis Danisevskis1af91262020-08-10 14:58:08 -0700178// We don't except more than 32KiB of data in `update`, `updateAad`, and `finish`.
179const MAX_RECEIVE_DATA: usize = 0x8000;
180
181impl Operation {
182 /// Constructor
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000183 pub fn new(
184 index: usize,
Stephen Crane221bbb52020-12-16 15:52:10 -0800185 km_op: binder::Strong<dyn IKeyMintOperation>,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000186 owner: u32,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800187 auth_info: AuthInfo,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000188 ) -> Self {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700189 Self {
190 index,
191 km_op: Asp::new(km_op.as_binder()),
192 last_usage: Mutex::new(Instant::now()),
193 outcome: Mutex::new(Outcome::Unknown),
194 owner,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800195 auth_info: Mutex::new(auth_info),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700196 }
197 }
198
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700199 fn get_pruning_info(&self) -> Option<PruningInfo> {
200 // An operation may be finalized.
201 if let Ok(guard) = self.outcome.try_lock() {
202 match *guard {
203 Outcome::Unknown => {}
204 // If the outcome is any other than unknown, it has been finalized,
205 // and we can no longer consider it for pruning.
206 _ => return None,
207 }
208 }
209 // Else: If we could not grab the lock, this means that the operation is currently
210 // being used and it may be transitioning to finalized or it was simply updated.
211 // In any case it is fair game to consider it for pruning. If the operation
212 // transitioned to a final state, we will notice when we attempt to prune, and
213 // a subsequent attempt to create a new operation will succeed.
214 Some(PruningInfo {
215 // Expect safety:
216 // `last_usage` is locked only for primitive single line statements.
217 // There is no chance to panic and poison the mutex.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700218 last_usage: *self.last_usage.lock().expect("In get_pruning_info."),
219 owner: self.owner,
220 index: self.index,
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700221 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700222 }
223
224 fn prune(&self, last_usage: Instant) -> Result<(), Error> {
225 let mut locked_outcome = match self.outcome.try_lock() {
226 Ok(guard) => match *guard {
227 Outcome::Unknown => guard,
228 _ => return Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)),
229 },
230 Err(_) => return Err(Error::Rc(ResponseCode::OPERATION_BUSY)),
231 };
232
233 // In `OperationDb::prune`, which is our caller, we first gather the pruning
234 // information including the last usage. When we select a candidate
235 // we call `prune` on that candidate passing the last_usage
236 // that we gathered earlier. If the actual last usage
237 // has changed since than, it means the operation was busy in the
238 // meantime, which means that we have to reevaluate the pruning score.
239 //
240 // Expect safety:
241 // `last_usage` is locked only for primitive single line statements.
242 // There is no chance to panic and poison the mutex.
243 if *self.last_usage.lock().expect("In Operation::prune()") != last_usage {
244 return Err(Error::Rc(ResponseCode::OPERATION_BUSY));
245 }
246 *locked_outcome = Outcome::Pruned;
247
Stephen Crane221bbb52020-12-16 15:52:10 -0800248 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
249 match self.km_op.get_interface() {
250 Ok(km_op) => km_op,
251 Err(e) => {
252 log::error!("In prune: Failed to get KeyMintOperation interface.\n {:?}", e);
253 return Err(Error::sys());
254 }
255 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700256
257 // We abort the operation. If there was an error we log it but ignore it.
258 if let Err(e) = map_km_error(km_op.abort()) {
259 log::error!("In prune: KeyMint::abort failed with {:?}.", e);
260 }
261
262 Ok(())
263 }
264
265 // This function takes a Result from a KeyMint call and inspects it for errors.
266 // If an error was found it updates the given `locked_outcome` accordingly.
267 // It forwards the Result unmodified.
268 // The precondition to this call must be *locked_outcome == Outcome::Unknown.
269 // Ideally the `locked_outcome` came from a successful call to `check_active`
270 // see below.
271 fn update_outcome<T>(
272 &self,
273 locked_outcome: &mut Outcome,
274 err: Result<T, Error>,
275 ) -> Result<T, Error> {
276 match &err {
277 Err(Error::Km(e)) => *locked_outcome = Outcome::ErrorCode(*e),
278 Err(_) => *locked_outcome = Outcome::ErrorCode(ErrorCode::UNKNOWN_ERROR),
279 Ok(_) => (),
280 }
281 err
282 }
283
284 // This function grabs the outcome lock and checks the current outcome state.
285 // If the outcome is still `Outcome::Unknown`, this function returns
286 // the locked outcome for further updates. In any other case it returns
287 // ErrorCode::INVALID_OPERATION_HANDLE indicating that this operation has
288 // been finalized and is no longer active.
289 fn check_active(&self) -> Result<MutexGuard<Outcome>> {
290 let guard = self.outcome.lock().expect("In check_active.");
291 match *guard {
292 Outcome::Unknown => Ok(guard),
293 _ => Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)).context(format!(
294 "In check_active: Call on finalized operation with outcome: {:?}.",
295 *guard
296 )),
297 }
298 }
299
300 // This function checks the amount of input data sent to us. We reject any buffer
301 // exceeding MAX_RECEIVE_DATA bytes as input to `update`, `update_aad`, and `finish`
302 // in order to force clients into using reasonable limits.
303 fn check_input_length(data: &[u8]) -> Result<()> {
304 if data.len() > MAX_RECEIVE_DATA {
305 // This error code is unique, no context required here.
306 return Err(anyhow!(Error::Rc(ResponseCode::TOO_MUCH_DATA)));
307 }
308 Ok(())
309 }
310
311 // Update the last usage to now.
312 fn touch(&self) {
313 // Expect safety:
314 // `last_usage` is locked only for primitive single line statements.
315 // There is no chance to panic and poison the mutex.
316 *self.last_usage.lock().expect("In touch.") = Instant::now();
317 }
318
319 /// Implementation of `IKeystoreOperation::updateAad`.
320 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
321 fn update_aad(&self, aad_input: &[u8]) -> Result<()> {
322 let mut outcome = self.check_active().context("In update_aad")?;
323 Self::check_input_length(aad_input).context("In update_aad")?;
324 self.touch();
325
Stephen Crane221bbb52020-12-16 15:52:10 -0800326 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700327 self.km_op.get_interface().context("In update: Failed to get KeyMintOperation.")?;
328
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800329 let (hat, tst) = self
330 .auth_info
331 .lock()
332 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800333 .before_update()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800334 .context("In update_aad: Trying to get auth tokens.")?;
335
Janis Danisevskis1af91262020-08-10 14:58:08 -0700336 self.update_outcome(
337 &mut *outcome,
Shawn Willden44cc03d2021-02-19 10:53:49 -0700338 map_km_error(km_op.updateAad(aad_input, hat.as_ref(), tst.as_ref())),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700339 )
340 .context("In update_aad: KeyMint::update failed.")?;
341
342 Ok(())
343 }
344
345 /// Implementation of `IKeystoreOperation::update`.
346 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
347 fn update(&self, input: &[u8]) -> Result<Option<Vec<u8>>> {
348 let mut outcome = self.check_active().context("In update")?;
349 Self::check_input_length(input).context("In update")?;
350 self.touch();
351
Stephen Crane221bbb52020-12-16 15:52:10 -0800352 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700353 self.km_op.get_interface().context("In update: Failed to get KeyMintOperation.")?;
354
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800355 let (hat, tst) = self
356 .auth_info
357 .lock()
358 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800359 .before_update()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800360 .context("In update: Trying to get auth tokens.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000361
Shawn Willden44cc03d2021-02-19 10:53:49 -0700362 let output = self
363 .update_outcome(
364 &mut *outcome,
365 map_km_error(km_op.update(input, hat.as_ref(), tst.as_ref())),
366 )
367 .context("In update: KeyMint::update failed.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700368
Shawn Willden44cc03d2021-02-19 10:53:49 -0700369 if output.is_empty() {
370 Ok(None)
371 } else {
372 Ok(Some(output))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700373 }
374 }
375
376 /// Implementation of `IKeystoreOperation::finish`.
377 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
378 fn finish(&self, input: Option<&[u8]>, signature: Option<&[u8]>) -> Result<Option<Vec<u8>>> {
379 let mut outcome = self.check_active().context("In finish")?;
380 if let Some(input) = input {
381 Self::check_input_length(input).context("In finish")?;
382 }
383 self.touch();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700384
Stephen Crane221bbb52020-12-16 15:52:10 -0800385 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700386 self.km_op.get_interface().context("In finish: Failed to get KeyMintOperation.")?;
387
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800388 let (hat, tst, confirmation_token) = self
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800389 .auth_info
390 .lock()
391 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800392 .before_finish()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800393 .context("In finish: Trying to get auth tokens.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000394
Janis Danisevskis85d47932020-10-23 16:12:59 -0700395 let output = self
396 .update_outcome(
397 &mut *outcome,
398 map_km_error(km_op.finish(
Janis Danisevskis85d47932020-10-23 16:12:59 -0700399 input,
400 signature,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800401 hat.as_ref(),
402 tst.as_ref(),
Shawn Willden44cc03d2021-02-19 10:53:49 -0700403 confirmation_token.as_deref(),
Janis Danisevskis85d47932020-10-23 16:12:59 -0700404 )),
405 )
406 .context("In finish: KeyMint::finish failed.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700407
Qi Wub9433b52020-12-01 14:52:46 +0800408 self.auth_info.lock().unwrap().after_finish().context("In finish.")?;
409
Janis Danisevskis1af91262020-08-10 14:58:08 -0700410 // At this point the operation concluded successfully.
411 *outcome = Outcome::Success;
412
413 if output.is_empty() {
414 Ok(None)
415 } else {
416 Ok(Some(output))
417 }
418 }
419
420 /// Aborts the operation if it is active. IFF the operation is aborted the outcome is
421 /// set to `outcome`. `outcome` must reflect the reason for the abort. Since the operation
422 /// gets aborted `outcome` must not be `Operation::Success` or `Operation::Unknown`.
423 fn abort(&self, outcome: Outcome) -> Result<()> {
424 let mut locked_outcome = self.check_active().context("In abort")?;
425 *locked_outcome = outcome;
Stephen Crane221bbb52020-12-16 15:52:10 -0800426 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700427 self.km_op.get_interface().context("In abort: Failed to get KeyMintOperation.")?;
428
429 map_km_error(km_op.abort()).context("In abort: KeyMint::abort failed.")
430 }
431}
432
433impl Drop for Operation {
434 fn drop(&mut self) {
435 if let Ok(Outcome::Unknown) = self.outcome.get_mut() {
436 // If the operation was still active we call abort, setting
437 // the outcome to `Outcome::Dropped`
438 if let Err(e) = self.abort(Outcome::Dropped) {
439 log::error!("While dropping Operation: abort failed:\n {:?}", e);
440 }
441 }
442 }
443}
444
445/// The OperationDb holds weak references to all ongoing operations.
446/// Its main purpose is to facilitate operation pruning.
447#[derive(Debug, Default)]
448pub struct OperationDb {
449 // TODO replace Vec with WeakTable when the weak_table crate becomes
450 // available.
451 operations: Mutex<Vec<Weak<Operation>>>,
452}
453
454impl OperationDb {
455 /// Creates a new OperationDb.
456 pub fn new() -> Self {
457 Self { operations: Mutex::new(Vec::new()) }
458 }
459
460 /// Creates a new operation.
461 /// This function takes a KeyMint operation and an associated
462 /// owner uid and returns a new Operation wrapped in a `std::sync::Arc`.
463 pub fn create_operation(
464 &self,
Stephen Crane221bbb52020-12-16 15:52:10 -0800465 km_op: binder::public_api::Strong<dyn IKeyMintOperation>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700466 owner: u32,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800467 auth_info: AuthInfo,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700468 ) -> Arc<Operation> {
469 // We use unwrap because we don't allow code that can panic while locked.
470 let mut operations = self.operations.lock().expect("In create_operation.");
471
472 let mut index: usize = 0;
473 // First we iterate through the operation slots to try and find an unused
474 // slot. If we don't find one, we append the new entry instead.
475 match (*operations).iter_mut().find(|s| {
476 index += 1;
477 s.upgrade().is_none()
478 }) {
479 Some(free_slot) => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800480 let new_op = Arc::new(Operation::new(index - 1, km_op, owner, auth_info));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700481 *free_slot = Arc::downgrade(&new_op);
482 new_op
483 }
484 None => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800485 let new_op = Arc::new(Operation::new(operations.len(), km_op, owner, auth_info));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700486 operations.push(Arc::downgrade(&new_op));
487 new_op
488 }
489 }
490 }
491
492 fn get(&self, index: usize) -> Option<Arc<Operation>> {
493 self.operations.lock().expect("In OperationDb::get.").get(index).and_then(|op| op.upgrade())
494 }
495
496 /// Attempts to prune an operation.
497 ///
498 /// This function is used during operation creation, i.e., by
499 /// `KeystoreSecurityLevel::create_operation`, to try and free up an operation slot
500 /// if it got `ErrorCode::TOO_MANY_OPERATIONS` from the KeyMint backend. It is not
501 /// guaranteed that an operation slot is available after this call successfully
502 /// returned for various reasons. E.g., another thread may have snatched up the newly
503 /// available slot. Callers may have to call prune multiple times before they get a
504 /// free operation slot. Prune may also return `Err(Error::Rc(ResponseCode::BACKEND_BUSY))`
505 /// which indicates that no prunable operation was found.
506 ///
507 /// To find a suitable candidate we compute the malus for the caller and each existing
508 /// operation. The malus is the inverse of the pruning power (caller) or pruning
509 /// resistance (existing operation).
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700510 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700511 /// The malus is based on the number of sibling operations and age. Sibling
512 /// operations are operations that have the same owner (UID).
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700513 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700514 /// Every operation, existing or new, starts with a malus of 1. Every sibling
515 /// increases the malus by one. The age is the time since an operation was last touched.
516 /// It increases the malus by log6(<age in seconds> + 1) rounded down to the next
517 /// integer. So the malus increases stepwise after 5s, 35s, 215s, ...
518 /// Of two operations with the same malus the least recently used one is considered
519 /// weaker.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700520 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700521 /// For the caller to be able to prune an operation it must find an operation
522 /// with a malus higher than its own.
523 ///
524 /// The malus can be expressed as
525 /// ```
526 /// malus = 1 + no_of_siblings + floor(log6(age_in_seconds + 1))
527 /// ```
528 /// where the constant `1` accounts for the operation under consideration.
529 /// In reality we compute it as
530 /// ```
531 /// caller_malus = 1 + running_siblings
532 /// ```
533 /// because the new operation has no age and is not included in the `running_siblings`,
534 /// and
535 /// ```
536 /// running_malus = running_siblings + floor(log6(age_in_seconds + 1))
537 /// ```
538 /// because a running operation is included in the `running_siblings` and it has
539 /// an age.
540 ///
541 /// ## Example
542 /// A caller with no running operations has a malus of 1. Young (age < 5s) operations
543 /// also with no siblings have a malus of one and cannot be pruned by the caller.
544 /// We have to find an operation that has at least one sibling or is older than 5s.
545 ///
546 /// A caller with one running operation has a malus of 2. Now even young siblings
547 /// or single child aging (5s <= age < 35s) operations are off limit. An aging
548 /// sibling of two, however, would have a malus of 3 and would be fair game.
549 ///
550 /// ## Rationale
551 /// Due to the limitation of KeyMint operation slots, we cannot get around pruning or
552 /// a single app could easily DoS KeyMint.
553 /// Keystore 1.0 used to always prune the least recently used operation. This at least
554 /// guaranteed that new operations can always be started. With the increased usage
555 /// of Keystore we saw increased pruning activity which can lead to a livelock
556 /// situation in the worst case.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700557 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700558 /// With the new pruning strategy we want to provide well behaved clients with
559 /// progress assurances while punishing DoS attempts. As a result of this
560 /// strategy we can be in the situation where no operation can be pruned and the
561 /// creation of a new operation fails. This allows single child operations which
562 /// are frequently updated to complete, thereby breaking up livelock situations
563 /// and facilitating system wide progress.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700564 ///
565 /// ## Update
566 /// We also allow callers to cannibalize their own sibling operations if no other
567 /// slot can be found. In this case the least recently used sibling is pruned.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700568 pub fn prune(&self, caller: u32) -> Result<(), Error> {
569 loop {
570 // Maps the uid of the owner to the number of operations that owner has
571 // (running_siblings). More operations per owner lowers the pruning
572 // resistance of the operations of that owner. Whereas the number of
573 // ongoing operations of the caller lowers the pruning power of the caller.
574 let mut owners: HashMap<u32, u64> = HashMap::new();
575 let mut pruning_info: Vec<PruningInfo> = Vec::new();
576
577 let now = Instant::now();
578 self.operations
579 .lock()
580 .expect("In OperationDb::prune: Trying to lock self.operations.")
581 .iter()
582 .for_each(|op| {
583 if let Some(op) = op.upgrade() {
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700584 if let Some(p_info) = op.get_pruning_info() {
585 let owner = p_info.owner;
586 pruning_info.push(p_info);
587 // Count operations per owner.
588 *owners.entry(owner).or_insert(0) += 1;
589 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700590 }
591 });
592
593 let caller_malus = 1u64 + *owners.entry(caller).or_default();
594
595 // We iterate through all operations computing the malus and finding
596 // the candidate with the highest malus which must also be higher
597 // than the caller_malus.
598 struct CandidateInfo {
599 index: usize,
600 malus: u64,
601 last_usage: Instant,
602 age: Duration,
603 }
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700604 let mut oldest_caller_op: Option<CandidateInfo> = None;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700605 let candidate = pruning_info.iter().fold(
606 None,
607 |acc: Option<CandidateInfo>, &PruningInfo { last_usage, owner, index }| {
608 // Compute the age of the current operation.
609 let age = now
610 .checked_duration_since(last_usage)
611 .unwrap_or_else(|| Duration::new(0, 0));
612
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700613 // Find the least recently used sibling as an alternative pruning candidate.
614 if owner == caller {
615 if let Some(CandidateInfo { age: a, .. }) = oldest_caller_op {
616 if age > a {
617 oldest_caller_op =
618 Some(CandidateInfo { index, malus: 0, last_usage, age });
619 }
620 } else {
621 oldest_caller_op =
622 Some(CandidateInfo { index, malus: 0, last_usage, age });
623 }
624 }
625
Janis Danisevskis1af91262020-08-10 14:58:08 -0700626 // Compute the malus of the current operation.
627 // Expect safety: Every owner in pruning_info was counted in
628 // the owners map. So this unwrap cannot panic.
629 let malus = *owners
630 .get(&owner)
631 .expect("This is odd. We should have counted every owner in pruning_info.")
632 + ((age.as_secs() + 1) as f64).log(6.0).floor() as u64;
633
634 // Now check if the current operation is a viable/better candidate
635 // the one currently stored in the accumulator.
636 match acc {
637 // First we have to find any operation that is prunable by the caller.
638 None => {
639 if caller_malus < malus {
640 Some(CandidateInfo { index, malus, last_usage, age })
641 } else {
642 None
643 }
644 }
645 // If we have found one we look for the operation with the worst score.
646 // If there is a tie, the older operation is considered weaker.
647 Some(CandidateInfo { index: i, malus: m, last_usage: l, age: a }) => {
648 if malus > m || (malus == m && age > a) {
649 Some(CandidateInfo { index, malus, last_usage, age })
650 } else {
651 Some(CandidateInfo { index: i, malus: m, last_usage: l, age: a })
652 }
653 }
654 }
655 },
656 );
657
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700658 // If we did not find a suitable candidate we may cannibalize our oldest sibling.
659 let candidate = candidate.or(oldest_caller_op);
660
Janis Danisevskis1af91262020-08-10 14:58:08 -0700661 match candidate {
662 Some(CandidateInfo { index, malus: _, last_usage, age: _ }) => {
663 match self.get(index) {
664 Some(op) => {
665 match op.prune(last_usage) {
666 // We successfully freed up a slot.
667 Ok(()) => break Ok(()),
668 // This means the operation we tried to prune was on its way
669 // out. It also means that the slot it had occupied was freed up.
670 Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)) => break Ok(()),
671 // This means the operation we tried to prune was currently
672 // servicing a request. There are two options.
673 // * Assume that it was touched, which means that its
674 // pruning resistance increased. In that case we have
675 // to start over and find another candidate.
676 // * Assume that the operation is transitioning to end-of-life.
677 // which means that we got a free slot for free.
678 // If we assume the first but the second is true, we prune
679 // a good operation without need (aggressive approach).
680 // If we assume the second but the first is true, our
681 // caller will attempt to create a new KeyMint operation,
682 // fail with `ErrorCode::TOO_MANY_OPERATIONS`, and call
683 // us again (conservative approach).
684 Err(Error::Rc(ResponseCode::OPERATION_BUSY)) => {
685 // We choose the conservative approach, because
686 // every needlessly pruned operation can impact
687 // the user experience.
688 // To switch to the aggressive approach replace
689 // the following line with `continue`.
690 break Ok(());
691 }
692
693 // The candidate may have been touched so the score
694 // has changed since our evaluation.
695 _ => continue,
696 }
697 }
698 // This index does not exist any more. The operation
699 // in this slot was dropped. Good news, a slot
700 // has freed up.
701 None => break Ok(()),
702 }
703 }
704 // We did not get a pruning candidate.
705 None => break Err(Error::Rc(ResponseCode::BACKEND_BUSY)),
706 }
707 }
708 }
709}
710
711/// Implementation of IKeystoreOperation.
712pub struct KeystoreOperation {
713 operation: Mutex<Option<Arc<Operation>>>,
714}
715
716impl KeystoreOperation {
717 /// Creates a new operation instance wrapped in a
718 /// BnKeystoreOperation proxy object. It also
Andrew Walbran808e8602021-03-16 13:58:28 +0000719 /// calls `IBinderInternal::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -0700720 /// we need it for checking Keystore permissions.
Stephen Crane221bbb52020-12-16 15:52:10 -0800721 pub fn new_native_binder(
722 operation: Arc<Operation>,
723 ) -> binder::public_api::Strong<dyn IKeystoreOperation> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700724 let result =
725 BnKeystoreOperation::new_binder(Self { operation: Mutex::new(Some(operation)) });
726 result.as_binder().set_requesting_sid(true);
727 result
728 }
729
730 /// Grabs the outer operation mutex and calls `f` on the locked operation.
731 /// The function also deletes the operation if it returns with an error or if
732 /// `delete_op` is true.
733 fn with_locked_operation<T, F>(&self, f: F, delete_op: bool) -> Result<T>
734 where
735 for<'a> F: FnOnce(&'a Operation) -> Result<T>,
736 {
737 let mut delete_op: bool = delete_op;
738 match self.operation.try_lock() {
739 Ok(mut mutex_guard) => {
740 let result = match &*mutex_guard {
741 Some(op) => {
742 let result = f(&*op);
743 // Any error here means we can discard the operation.
744 if result.is_err() {
745 delete_op = true;
746 }
747 result
748 }
749 None => Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE))
750 .context("In KeystoreOperation::with_locked_operation"),
751 };
752
753 if delete_op {
754 // We give up our reference to the Operation, thereby freeing up our
755 // internal resources and ending the wrapped KeyMint operation.
756 // This KeystoreOperation object will still be owned by an SpIBinder
757 // until the client drops its remote reference.
758 *mutex_guard = None;
759 }
760 result
761 }
762 Err(_) => Err(Error::Rc(ResponseCode::OPERATION_BUSY))
763 .context("In KeystoreOperation::with_locked_operation"),
764 }
765 }
766}
767
768impl binder::Interface for KeystoreOperation {}
769
770impl IKeystoreOperation for KeystoreOperation {
771 fn updateAad(&self, aad_input: &[u8]) -> binder::public_api::Result<()> {
772 map_or_log_err(
773 self.with_locked_operation(
774 |op| op.update_aad(aad_input).context("In KeystoreOperation::updateAad"),
775 false,
776 ),
777 Ok,
778 )
779 }
780
781 fn update(&self, input: &[u8]) -> binder::public_api::Result<Option<Vec<u8>>> {
782 map_or_log_err(
783 self.with_locked_operation(
784 |op| op.update(input).context("In KeystoreOperation::update"),
785 false,
786 ),
787 Ok,
788 )
789 }
790 fn finish(
791 &self,
792 input: Option<&[u8]>,
793 signature: Option<&[u8]>,
794 ) -> binder::public_api::Result<Option<Vec<u8>>> {
795 map_or_log_err(
796 self.with_locked_operation(
797 |op| op.finish(input, signature).context("In KeystoreOperation::finish"),
798 true,
799 ),
800 Ok,
801 )
802 }
803
804 fn abort(&self) -> binder::public_api::Result<()> {
Janis Danisevskis778245c2021-03-04 15:40:23 -0800805 map_err_with(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700806 self.with_locked_operation(
807 |op| op.abort(Outcome::Abort).context("In KeystoreOperation::abort"),
808 true,
809 ),
Janis Danisevskis778245c2021-03-04 15:40:23 -0800810 |e| {
811 match e.root_cause().downcast_ref::<Error>() {
812 // Calling abort on expired operations is something very common.
813 // There is no reason to clutter the log with it. It is never the cause
814 // for a true problem.
815 Some(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)) => {}
816 _ => log::error!("{:?}", e),
817 };
818 e
819 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700820 Ok,
821 )
822 }
823}