blob: 0f5bcaf5de4818b61ee8e3a54169872d2d1bb2ef [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 Danisevskis186d9f42021-03-03 14:40:52 -0800170 forced: bool,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700171}
172
173struct PruningInfo {
174 last_usage: Instant,
175 owner: u32,
176 index: usize,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800177 forced: bool,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700178}
179
Janis Danisevskis1af91262020-08-10 14:58:08 -0700180// We don't except more than 32KiB of data in `update`, `updateAad`, and `finish`.
181const MAX_RECEIVE_DATA: usize = 0x8000;
182
183impl Operation {
184 /// Constructor
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000185 pub fn new(
186 index: usize,
Stephen Crane221bbb52020-12-16 15:52:10 -0800187 km_op: binder::Strong<dyn IKeyMintOperation>,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000188 owner: u32,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800189 auth_info: AuthInfo,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800190 forced: bool,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000191 ) -> Self {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700192 Self {
193 index,
194 km_op: Asp::new(km_op.as_binder()),
195 last_usage: Mutex::new(Instant::now()),
196 outcome: Mutex::new(Outcome::Unknown),
197 owner,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800198 auth_info: Mutex::new(auth_info),
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800199 forced,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700200 }
201 }
202
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700203 fn get_pruning_info(&self) -> Option<PruningInfo> {
204 // An operation may be finalized.
205 if let Ok(guard) = self.outcome.try_lock() {
206 match *guard {
207 Outcome::Unknown => {}
208 // If the outcome is any other than unknown, it has been finalized,
209 // and we can no longer consider it for pruning.
210 _ => return None,
211 }
212 }
213 // Else: If we could not grab the lock, this means that the operation is currently
214 // being used and it may be transitioning to finalized or it was simply updated.
215 // In any case it is fair game to consider it for pruning. If the operation
216 // transitioned to a final state, we will notice when we attempt to prune, and
217 // a subsequent attempt to create a new operation will succeed.
218 Some(PruningInfo {
219 // Expect safety:
220 // `last_usage` is locked only for primitive single line statements.
221 // There is no chance to panic and poison the mutex.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700222 last_usage: *self.last_usage.lock().expect("In get_pruning_info."),
223 owner: self.owner,
224 index: self.index,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800225 forced: self.forced,
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700226 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700227 }
228
229 fn prune(&self, last_usage: Instant) -> Result<(), Error> {
230 let mut locked_outcome = match self.outcome.try_lock() {
231 Ok(guard) => match *guard {
232 Outcome::Unknown => guard,
233 _ => return Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)),
234 },
235 Err(_) => return Err(Error::Rc(ResponseCode::OPERATION_BUSY)),
236 };
237
238 // In `OperationDb::prune`, which is our caller, we first gather the pruning
239 // information including the last usage. When we select a candidate
240 // we call `prune` on that candidate passing the last_usage
241 // that we gathered earlier. If the actual last usage
242 // has changed since than, it means the operation was busy in the
243 // meantime, which means that we have to reevaluate the pruning score.
244 //
245 // Expect safety:
246 // `last_usage` is locked only for primitive single line statements.
247 // There is no chance to panic and poison the mutex.
248 if *self.last_usage.lock().expect("In Operation::prune()") != last_usage {
249 return Err(Error::Rc(ResponseCode::OPERATION_BUSY));
250 }
251 *locked_outcome = Outcome::Pruned;
252
Stephen Crane221bbb52020-12-16 15:52:10 -0800253 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
254 match self.km_op.get_interface() {
255 Ok(km_op) => km_op,
256 Err(e) => {
257 log::error!("In prune: Failed to get KeyMintOperation interface.\n {:?}", e);
258 return Err(Error::sys());
259 }
260 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700261
262 // We abort the operation. If there was an error we log it but ignore it.
263 if let Err(e) = map_km_error(km_op.abort()) {
264 log::error!("In prune: KeyMint::abort failed with {:?}.", e);
265 }
266
267 Ok(())
268 }
269
270 // This function takes a Result from a KeyMint call and inspects it for errors.
271 // If an error was found it updates the given `locked_outcome` accordingly.
272 // It forwards the Result unmodified.
273 // The precondition to this call must be *locked_outcome == Outcome::Unknown.
274 // Ideally the `locked_outcome` came from a successful call to `check_active`
275 // see below.
276 fn update_outcome<T>(
277 &self,
278 locked_outcome: &mut Outcome,
279 err: Result<T, Error>,
280 ) -> Result<T, Error> {
281 match &err {
282 Err(Error::Km(e)) => *locked_outcome = Outcome::ErrorCode(*e),
283 Err(_) => *locked_outcome = Outcome::ErrorCode(ErrorCode::UNKNOWN_ERROR),
284 Ok(_) => (),
285 }
286 err
287 }
288
289 // This function grabs the outcome lock and checks the current outcome state.
290 // If the outcome is still `Outcome::Unknown`, this function returns
291 // the locked outcome for further updates. In any other case it returns
292 // ErrorCode::INVALID_OPERATION_HANDLE indicating that this operation has
293 // been finalized and is no longer active.
294 fn check_active(&self) -> Result<MutexGuard<Outcome>> {
295 let guard = self.outcome.lock().expect("In check_active.");
296 match *guard {
297 Outcome::Unknown => Ok(guard),
298 _ => Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)).context(format!(
299 "In check_active: Call on finalized operation with outcome: {:?}.",
300 *guard
301 )),
302 }
303 }
304
305 // This function checks the amount of input data sent to us. We reject any buffer
306 // exceeding MAX_RECEIVE_DATA bytes as input to `update`, `update_aad`, and `finish`
307 // in order to force clients into using reasonable limits.
308 fn check_input_length(data: &[u8]) -> Result<()> {
309 if data.len() > MAX_RECEIVE_DATA {
310 // This error code is unique, no context required here.
311 return Err(anyhow!(Error::Rc(ResponseCode::TOO_MUCH_DATA)));
312 }
313 Ok(())
314 }
315
316 // Update the last usage to now.
317 fn touch(&self) {
318 // Expect safety:
319 // `last_usage` is locked only for primitive single line statements.
320 // There is no chance to panic and poison the mutex.
321 *self.last_usage.lock().expect("In touch.") = Instant::now();
322 }
323
324 /// Implementation of `IKeystoreOperation::updateAad`.
325 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
326 fn update_aad(&self, aad_input: &[u8]) -> Result<()> {
327 let mut outcome = self.check_active().context("In update_aad")?;
328 Self::check_input_length(aad_input).context("In update_aad")?;
329 self.touch();
330
Stephen Crane221bbb52020-12-16 15:52:10 -0800331 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700332 self.km_op.get_interface().context("In update: Failed to get KeyMintOperation.")?;
333
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800334 let (hat, tst) = self
335 .auth_info
336 .lock()
337 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800338 .before_update()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800339 .context("In update_aad: Trying to get auth tokens.")?;
340
Janis Danisevskis1af91262020-08-10 14:58:08 -0700341 self.update_outcome(
342 &mut *outcome,
Shawn Willden44cc03d2021-02-19 10:53:49 -0700343 map_km_error(km_op.updateAad(aad_input, hat.as_ref(), tst.as_ref())),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700344 )
345 .context("In update_aad: KeyMint::update failed.")?;
346
347 Ok(())
348 }
349
350 /// Implementation of `IKeystoreOperation::update`.
351 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
352 fn update(&self, input: &[u8]) -> Result<Option<Vec<u8>>> {
353 let mut outcome = self.check_active().context("In update")?;
354 Self::check_input_length(input).context("In update")?;
355 self.touch();
356
Stephen Crane221bbb52020-12-16 15:52:10 -0800357 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700358 self.km_op.get_interface().context("In update: Failed to get KeyMintOperation.")?;
359
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800360 let (hat, tst) = self
361 .auth_info
362 .lock()
363 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800364 .before_update()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800365 .context("In update: Trying to get auth tokens.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000366
Shawn Willden44cc03d2021-02-19 10:53:49 -0700367 let output = self
368 .update_outcome(
369 &mut *outcome,
370 map_km_error(km_op.update(input, hat.as_ref(), tst.as_ref())),
371 )
372 .context("In update: KeyMint::update failed.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700373
Shawn Willden44cc03d2021-02-19 10:53:49 -0700374 if output.is_empty() {
375 Ok(None)
376 } else {
377 Ok(Some(output))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700378 }
379 }
380
381 /// Implementation of `IKeystoreOperation::finish`.
382 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
383 fn finish(&self, input: Option<&[u8]>, signature: Option<&[u8]>) -> Result<Option<Vec<u8>>> {
384 let mut outcome = self.check_active().context("In finish")?;
385 if let Some(input) = input {
386 Self::check_input_length(input).context("In finish")?;
387 }
388 self.touch();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700389
Stephen Crane221bbb52020-12-16 15:52:10 -0800390 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700391 self.km_op.get_interface().context("In finish: Failed to get KeyMintOperation.")?;
392
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800393 let (hat, tst, confirmation_token) = self
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800394 .auth_info
395 .lock()
396 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800397 .before_finish()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800398 .context("In finish: Trying to get auth tokens.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000399
Janis Danisevskis85d47932020-10-23 16:12:59 -0700400 let output = self
401 .update_outcome(
402 &mut *outcome,
403 map_km_error(km_op.finish(
Janis Danisevskis85d47932020-10-23 16:12:59 -0700404 input,
405 signature,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800406 hat.as_ref(),
407 tst.as_ref(),
Shawn Willden44cc03d2021-02-19 10:53:49 -0700408 confirmation_token.as_deref(),
Janis Danisevskis85d47932020-10-23 16:12:59 -0700409 )),
410 )
411 .context("In finish: KeyMint::finish failed.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700412
Qi Wub9433b52020-12-01 14:52:46 +0800413 self.auth_info.lock().unwrap().after_finish().context("In finish.")?;
414
Janis Danisevskis1af91262020-08-10 14:58:08 -0700415 // At this point the operation concluded successfully.
416 *outcome = Outcome::Success;
417
418 if output.is_empty() {
419 Ok(None)
420 } else {
421 Ok(Some(output))
422 }
423 }
424
425 /// Aborts the operation if it is active. IFF the operation is aborted the outcome is
426 /// set to `outcome`. `outcome` must reflect the reason for the abort. Since the operation
427 /// gets aborted `outcome` must not be `Operation::Success` or `Operation::Unknown`.
428 fn abort(&self, outcome: Outcome) -> Result<()> {
429 let mut locked_outcome = self.check_active().context("In abort")?;
430 *locked_outcome = outcome;
Stephen Crane221bbb52020-12-16 15:52:10 -0800431 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700432 self.km_op.get_interface().context("In abort: Failed to get KeyMintOperation.")?;
433
434 map_km_error(km_op.abort()).context("In abort: KeyMint::abort failed.")
435 }
436}
437
438impl Drop for Operation {
439 fn drop(&mut self) {
440 if let Ok(Outcome::Unknown) = self.outcome.get_mut() {
441 // If the operation was still active we call abort, setting
442 // the outcome to `Outcome::Dropped`
443 if let Err(e) = self.abort(Outcome::Dropped) {
444 log::error!("While dropping Operation: abort failed:\n {:?}", e);
445 }
446 }
447 }
448}
449
450/// The OperationDb holds weak references to all ongoing operations.
451/// Its main purpose is to facilitate operation pruning.
452#[derive(Debug, Default)]
453pub struct OperationDb {
454 // TODO replace Vec with WeakTable when the weak_table crate becomes
455 // available.
456 operations: Mutex<Vec<Weak<Operation>>>,
457}
458
459impl OperationDb {
460 /// Creates a new OperationDb.
461 pub fn new() -> Self {
462 Self { operations: Mutex::new(Vec::new()) }
463 }
464
465 /// Creates a new operation.
466 /// This function takes a KeyMint operation and an associated
467 /// owner uid and returns a new Operation wrapped in a `std::sync::Arc`.
468 pub fn create_operation(
469 &self,
Stephen Crane221bbb52020-12-16 15:52:10 -0800470 km_op: binder::public_api::Strong<dyn IKeyMintOperation>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700471 owner: u32,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800472 auth_info: AuthInfo,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800473 forced: bool,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700474 ) -> Arc<Operation> {
475 // We use unwrap because we don't allow code that can panic while locked.
476 let mut operations = self.operations.lock().expect("In create_operation.");
477
478 let mut index: usize = 0;
479 // First we iterate through the operation slots to try and find an unused
480 // slot. If we don't find one, we append the new entry instead.
481 match (*operations).iter_mut().find(|s| {
482 index += 1;
483 s.upgrade().is_none()
484 }) {
485 Some(free_slot) => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800486 let new_op = Arc::new(Operation::new(index - 1, km_op, owner, auth_info, forced));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700487 *free_slot = Arc::downgrade(&new_op);
488 new_op
489 }
490 None => {
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800491 let new_op =
492 Arc::new(Operation::new(operations.len(), km_op, owner, auth_info, forced));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700493 operations.push(Arc::downgrade(&new_op));
494 new_op
495 }
496 }
497 }
498
499 fn get(&self, index: usize) -> Option<Arc<Operation>> {
500 self.operations.lock().expect("In OperationDb::get.").get(index).and_then(|op| op.upgrade())
501 }
502
503 /// Attempts to prune an operation.
504 ///
505 /// This function is used during operation creation, i.e., by
506 /// `KeystoreSecurityLevel::create_operation`, to try and free up an operation slot
507 /// if it got `ErrorCode::TOO_MANY_OPERATIONS` from the KeyMint backend. It is not
508 /// guaranteed that an operation slot is available after this call successfully
509 /// returned for various reasons. E.g., another thread may have snatched up the newly
510 /// available slot. Callers may have to call prune multiple times before they get a
511 /// free operation slot. Prune may also return `Err(Error::Rc(ResponseCode::BACKEND_BUSY))`
512 /// which indicates that no prunable operation was found.
513 ///
514 /// To find a suitable candidate we compute the malus for the caller and each existing
515 /// operation. The malus is the inverse of the pruning power (caller) or pruning
516 /// resistance (existing operation).
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700517 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700518 /// The malus is based on the number of sibling operations and age. Sibling
519 /// operations are operations that have the same owner (UID).
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700520 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700521 /// Every operation, existing or new, starts with a malus of 1. Every sibling
522 /// increases the malus by one. The age is the time since an operation was last touched.
523 /// It increases the malus by log6(<age in seconds> + 1) rounded down to the next
524 /// integer. So the malus increases stepwise after 5s, 35s, 215s, ...
525 /// Of two operations with the same malus the least recently used one is considered
526 /// weaker.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700527 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700528 /// For the caller to be able to prune an operation it must find an operation
529 /// with a malus higher than its own.
530 ///
531 /// The malus can be expressed as
532 /// ```
533 /// malus = 1 + no_of_siblings + floor(log6(age_in_seconds + 1))
534 /// ```
535 /// where the constant `1` accounts for the operation under consideration.
536 /// In reality we compute it as
537 /// ```
538 /// caller_malus = 1 + running_siblings
539 /// ```
540 /// because the new operation has no age and is not included in the `running_siblings`,
541 /// and
542 /// ```
543 /// running_malus = running_siblings + floor(log6(age_in_seconds + 1))
544 /// ```
545 /// because a running operation is included in the `running_siblings` and it has
546 /// an age.
547 ///
548 /// ## Example
549 /// A caller with no running operations has a malus of 1. Young (age < 5s) operations
550 /// also with no siblings have a malus of one and cannot be pruned by the caller.
551 /// We have to find an operation that has at least one sibling or is older than 5s.
552 ///
553 /// A caller with one running operation has a malus of 2. Now even young siblings
554 /// or single child aging (5s <= age < 35s) operations are off limit. An aging
555 /// sibling of two, however, would have a malus of 3 and would be fair game.
556 ///
557 /// ## Rationale
558 /// Due to the limitation of KeyMint operation slots, we cannot get around pruning or
559 /// a single app could easily DoS KeyMint.
560 /// Keystore 1.0 used to always prune the least recently used operation. This at least
561 /// guaranteed that new operations can always be started. With the increased usage
562 /// of Keystore we saw increased pruning activity which can lead to a livelock
563 /// situation in the worst case.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700564 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700565 /// With the new pruning strategy we want to provide well behaved clients with
566 /// progress assurances while punishing DoS attempts. As a result of this
567 /// strategy we can be in the situation where no operation can be pruned and the
568 /// creation of a new operation fails. This allows single child operations which
569 /// are frequently updated to complete, thereby breaking up livelock situations
570 /// and facilitating system wide progress.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700571 ///
572 /// ## Update
573 /// We also allow callers to cannibalize their own sibling operations if no other
574 /// slot can be found. In this case the least recently used sibling is pruned.
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800575 pub fn prune(&self, caller: u32, forced: bool) -> Result<(), Error> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700576 loop {
577 // Maps the uid of the owner to the number of operations that owner has
578 // (running_siblings). More operations per owner lowers the pruning
579 // resistance of the operations of that owner. Whereas the number of
580 // ongoing operations of the caller lowers the pruning power of the caller.
581 let mut owners: HashMap<u32, u64> = HashMap::new();
582 let mut pruning_info: Vec<PruningInfo> = Vec::new();
583
584 let now = Instant::now();
585 self.operations
586 .lock()
587 .expect("In OperationDb::prune: Trying to lock self.operations.")
588 .iter()
589 .for_each(|op| {
590 if let Some(op) = op.upgrade() {
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700591 if let Some(p_info) = op.get_pruning_info() {
592 let owner = p_info.owner;
593 pruning_info.push(p_info);
594 // Count operations per owner.
595 *owners.entry(owner).or_insert(0) += 1;
596 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700597 }
598 });
599
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800600 // If the operation is forced, the caller has a malus of 0.
601 let caller_malus = if forced { 0 } else { 1u64 + *owners.entry(caller).or_default() };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700602
603 // We iterate through all operations computing the malus and finding
604 // the candidate with the highest malus which must also be higher
605 // than the caller_malus.
606 struct CandidateInfo {
607 index: usize,
608 malus: u64,
609 last_usage: Instant,
610 age: Duration,
611 }
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700612 let mut oldest_caller_op: Option<CandidateInfo> = None;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700613 let candidate = pruning_info.iter().fold(
614 None,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800615 |acc: Option<CandidateInfo>, &PruningInfo { last_usage, owner, index, forced }| {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700616 // Compute the age of the current operation.
617 let age = now
618 .checked_duration_since(last_usage)
619 .unwrap_or_else(|| Duration::new(0, 0));
620
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700621 // Find the least recently used sibling as an alternative pruning candidate.
622 if owner == caller {
623 if let Some(CandidateInfo { age: a, .. }) = oldest_caller_op {
624 if age > a {
625 oldest_caller_op =
626 Some(CandidateInfo { index, malus: 0, last_usage, age });
627 }
628 } else {
629 oldest_caller_op =
630 Some(CandidateInfo { index, malus: 0, last_usage, age });
631 }
632 }
633
Janis Danisevskis1af91262020-08-10 14:58:08 -0700634 // Compute the malus of the current operation.
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800635 let malus = if forced {
636 // Forced operations have a malus of 0. And cannot even be pruned
637 // by other forced operations.
638 0
639 } else {
640 // Expect safety: Every owner in pruning_info was counted in
641 // the owners map. So this unwrap cannot panic.
642 *owners.get(&owner).expect(
643 "This is odd. We should have counted every owner in pruning_info.",
644 ) + ((age.as_secs() + 1) as f64).log(6.0).floor() as u64
645 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700646
647 // Now check if the current operation is a viable/better candidate
648 // the one currently stored in the accumulator.
649 match acc {
650 // First we have to find any operation that is prunable by the caller.
651 None => {
652 if caller_malus < malus {
653 Some(CandidateInfo { index, malus, last_usage, age })
654 } else {
655 None
656 }
657 }
658 // If we have found one we look for the operation with the worst score.
659 // If there is a tie, the older operation is considered weaker.
660 Some(CandidateInfo { index: i, malus: m, last_usage: l, age: a }) => {
661 if malus > m || (malus == m && age > a) {
662 Some(CandidateInfo { index, malus, last_usage, age })
663 } else {
664 Some(CandidateInfo { index: i, malus: m, last_usage: l, age: a })
665 }
666 }
667 }
668 },
669 );
670
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700671 // If we did not find a suitable candidate we may cannibalize our oldest sibling.
672 let candidate = candidate.or(oldest_caller_op);
673
Janis Danisevskis1af91262020-08-10 14:58:08 -0700674 match candidate {
675 Some(CandidateInfo { index, malus: _, last_usage, age: _ }) => {
676 match self.get(index) {
677 Some(op) => {
678 match op.prune(last_usage) {
679 // We successfully freed up a slot.
680 Ok(()) => break Ok(()),
681 // This means the operation we tried to prune was on its way
682 // out. It also means that the slot it had occupied was freed up.
683 Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)) => break Ok(()),
684 // This means the operation we tried to prune was currently
685 // servicing a request. There are two options.
686 // * Assume that it was touched, which means that its
687 // pruning resistance increased. In that case we have
688 // to start over and find another candidate.
689 // * Assume that the operation is transitioning to end-of-life.
690 // which means that we got a free slot for free.
691 // If we assume the first but the second is true, we prune
692 // a good operation without need (aggressive approach).
693 // If we assume the second but the first is true, our
694 // caller will attempt to create a new KeyMint operation,
695 // fail with `ErrorCode::TOO_MANY_OPERATIONS`, and call
696 // us again (conservative approach).
697 Err(Error::Rc(ResponseCode::OPERATION_BUSY)) => {
698 // We choose the conservative approach, because
699 // every needlessly pruned operation can impact
700 // the user experience.
701 // To switch to the aggressive approach replace
702 // the following line with `continue`.
703 break Ok(());
704 }
705
706 // The candidate may have been touched so the score
707 // has changed since our evaluation.
708 _ => continue,
709 }
710 }
711 // This index does not exist any more. The operation
712 // in this slot was dropped. Good news, a slot
713 // has freed up.
714 None => break Ok(()),
715 }
716 }
717 // We did not get a pruning candidate.
718 None => break Err(Error::Rc(ResponseCode::BACKEND_BUSY)),
719 }
720 }
721 }
722}
723
724/// Implementation of IKeystoreOperation.
725pub struct KeystoreOperation {
726 operation: Mutex<Option<Arc<Operation>>>,
727}
728
729impl KeystoreOperation {
730 /// Creates a new operation instance wrapped in a
731 /// BnKeystoreOperation proxy object. It also
Andrew Walbran808e8602021-03-16 13:58:28 +0000732 /// calls `IBinderInternal::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -0700733 /// we need it for checking Keystore permissions.
Stephen Crane221bbb52020-12-16 15:52:10 -0800734 pub fn new_native_binder(
735 operation: Arc<Operation>,
736 ) -> binder::public_api::Strong<dyn IKeystoreOperation> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700737 let result =
738 BnKeystoreOperation::new_binder(Self { operation: Mutex::new(Some(operation)) });
739 result.as_binder().set_requesting_sid(true);
740 result
741 }
742
743 /// Grabs the outer operation mutex and calls `f` on the locked operation.
744 /// The function also deletes the operation if it returns with an error or if
745 /// `delete_op` is true.
746 fn with_locked_operation<T, F>(&self, f: F, delete_op: bool) -> Result<T>
747 where
748 for<'a> F: FnOnce(&'a Operation) -> Result<T>,
749 {
750 let mut delete_op: bool = delete_op;
751 match self.operation.try_lock() {
752 Ok(mut mutex_guard) => {
753 let result = match &*mutex_guard {
754 Some(op) => {
755 let result = f(&*op);
756 // Any error here means we can discard the operation.
757 if result.is_err() {
758 delete_op = true;
759 }
760 result
761 }
762 None => Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE))
763 .context("In KeystoreOperation::with_locked_operation"),
764 };
765
766 if delete_op {
767 // We give up our reference to the Operation, thereby freeing up our
768 // internal resources and ending the wrapped KeyMint operation.
769 // This KeystoreOperation object will still be owned by an SpIBinder
770 // until the client drops its remote reference.
771 *mutex_guard = None;
772 }
773 result
774 }
775 Err(_) => Err(Error::Rc(ResponseCode::OPERATION_BUSY))
776 .context("In KeystoreOperation::with_locked_operation"),
777 }
778 }
779}
780
781impl binder::Interface for KeystoreOperation {}
782
783impl IKeystoreOperation for KeystoreOperation {
784 fn updateAad(&self, aad_input: &[u8]) -> binder::public_api::Result<()> {
785 map_or_log_err(
786 self.with_locked_operation(
787 |op| op.update_aad(aad_input).context("In KeystoreOperation::updateAad"),
788 false,
789 ),
790 Ok,
791 )
792 }
793
794 fn update(&self, input: &[u8]) -> binder::public_api::Result<Option<Vec<u8>>> {
795 map_or_log_err(
796 self.with_locked_operation(
797 |op| op.update(input).context("In KeystoreOperation::update"),
798 false,
799 ),
800 Ok,
801 )
802 }
803 fn finish(
804 &self,
805 input: Option<&[u8]>,
806 signature: Option<&[u8]>,
807 ) -> binder::public_api::Result<Option<Vec<u8>>> {
808 map_or_log_err(
809 self.with_locked_operation(
810 |op| op.finish(input, signature).context("In KeystoreOperation::finish"),
811 true,
812 ),
813 Ok,
814 )
815 }
816
817 fn abort(&self) -> binder::public_api::Result<()> {
Janis Danisevskis778245c2021-03-04 15:40:23 -0800818 map_err_with(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700819 self.with_locked_operation(
820 |op| op.abort(Outcome::Abort).context("In KeystoreOperation::abort"),
821 true,
822 ),
Janis Danisevskis778245c2021-03-04 15:40:23 -0800823 |e| {
824 match e.root_cause().downcast_ref::<Error>() {
825 // Calling abort on expired operations is something very common.
826 // There is no reason to clutter the log with it. It is never the cause
827 // for a true problem.
828 Some(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)) => {}
829 _ => log::error!("{:?}", e),
830 };
831 e
832 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700833 Ok,
834 )
835 }
836}