blob: 18ea19f963b873a49342b71788891f02e95b9368 [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;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000129use crate::error::{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::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800132 ByteArray::ByteArray, IKeyMintOperation::IKeyMintOperation,
133 KeyParameter::KeyParameter as KmParam, KeyParameterArray::KeyParameterArray,
134 KeyParameterValue::KeyParameterValue as KmParamValue, Tag::Tag,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000135};
136use android_system_keystore2::aidl::android::system::keystore2::{
137 IKeystoreOperation::BnKeystoreOperation, IKeystoreOperation::IKeystoreOperation,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000138};
139use anyhow::{anyhow, Context, Result};
140use binder::{IBinder, Interface};
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)]
152enum Outcome {
153 Unknown,
154 Success,
155 Abort,
156 Dropped,
157 Pruned,
158 ErrorCode(ErrorCode),
159}
160
161/// Operation bundles all of the operation related resources and tracks the operation's
162/// outcome.
163#[derive(Debug)]
164pub struct Operation {
165 // The index of this operation in the OperationDb.
166 index: usize,
167 km_op: Asp,
168 last_usage: Mutex<Instant>,
169 outcome: Mutex<Outcome>,
170 owner: u32, // Uid of the operation's owner.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800171 auth_info: Mutex<AuthInfo>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700172}
173
174struct PruningInfo {
175 last_usage: Instant,
176 owner: u32,
177 index: usize,
178}
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,
187 km_op: Box<dyn IKeyMintOperation>,
188 owner: u32,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800189 auth_info: AuthInfo,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000190 ) -> Self {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700191 Self {
192 index,
193 km_op: Asp::new(km_op.as_binder()),
194 last_usage: Mutex::new(Instant::now()),
195 outcome: Mutex::new(Outcome::Unknown),
196 owner,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800197 auth_info: Mutex::new(auth_info),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700198 }
199 }
200
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700201 fn get_pruning_info(&self) -> Option<PruningInfo> {
202 // An operation may be finalized.
203 if let Ok(guard) = self.outcome.try_lock() {
204 match *guard {
205 Outcome::Unknown => {}
206 // If the outcome is any other than unknown, it has been finalized,
207 // and we can no longer consider it for pruning.
208 _ => return None,
209 }
210 }
211 // Else: If we could not grab the lock, this means that the operation is currently
212 // being used and it may be transitioning to finalized or it was simply updated.
213 // In any case it is fair game to consider it for pruning. If the operation
214 // transitioned to a final state, we will notice when we attempt to prune, and
215 // a subsequent attempt to create a new operation will succeed.
216 Some(PruningInfo {
217 // Expect safety:
218 // `last_usage` is locked only for primitive single line statements.
219 // There is no chance to panic and poison the mutex.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700220 last_usage: *self.last_usage.lock().expect("In get_pruning_info."),
221 owner: self.owner,
222 index: self.index,
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700223 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700224 }
225
226 fn prune(&self, last_usage: Instant) -> Result<(), Error> {
227 let mut locked_outcome = match self.outcome.try_lock() {
228 Ok(guard) => match *guard {
229 Outcome::Unknown => guard,
230 _ => return Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)),
231 },
232 Err(_) => return Err(Error::Rc(ResponseCode::OPERATION_BUSY)),
233 };
234
235 // In `OperationDb::prune`, which is our caller, we first gather the pruning
236 // information including the last usage. When we select a candidate
237 // we call `prune` on that candidate passing the last_usage
238 // that we gathered earlier. If the actual last usage
239 // has changed since than, it means the operation was busy in the
240 // meantime, which means that we have to reevaluate the pruning score.
241 //
242 // Expect safety:
243 // `last_usage` is locked only for primitive single line statements.
244 // There is no chance to panic and poison the mutex.
245 if *self.last_usage.lock().expect("In Operation::prune()") != last_usage {
246 return Err(Error::Rc(ResponseCode::OPERATION_BUSY));
247 }
248 *locked_outcome = Outcome::Pruned;
249
250 let km_op: Box<dyn IKeyMintOperation> = match self.km_op.get_interface() {
251 Ok(km_op) => km_op,
252 Err(e) => {
253 log::error!("In prune: Failed to get KeyMintOperation interface.\n {:?}", e);
254 return Err(Error::sys());
255 }
256 };
257
258 // We abort the operation. If there was an error we log it but ignore it.
259 if let Err(e) = map_km_error(km_op.abort()) {
260 log::error!("In prune: KeyMint::abort failed with {:?}.", e);
261 }
262
263 Ok(())
264 }
265
266 // This function takes a Result from a KeyMint call and inspects it for errors.
267 // If an error was found it updates the given `locked_outcome` accordingly.
268 // It forwards the Result unmodified.
269 // The precondition to this call must be *locked_outcome == Outcome::Unknown.
270 // Ideally the `locked_outcome` came from a successful call to `check_active`
271 // see below.
272 fn update_outcome<T>(
273 &self,
274 locked_outcome: &mut Outcome,
275 err: Result<T, Error>,
276 ) -> Result<T, Error> {
277 match &err {
278 Err(Error::Km(e)) => *locked_outcome = Outcome::ErrorCode(*e),
279 Err(_) => *locked_outcome = Outcome::ErrorCode(ErrorCode::UNKNOWN_ERROR),
280 Ok(_) => (),
281 }
282 err
283 }
284
285 // This function grabs the outcome lock and checks the current outcome state.
286 // If the outcome is still `Outcome::Unknown`, this function returns
287 // the locked outcome for further updates. In any other case it returns
288 // ErrorCode::INVALID_OPERATION_HANDLE indicating that this operation has
289 // been finalized and is no longer active.
290 fn check_active(&self) -> Result<MutexGuard<Outcome>> {
291 let guard = self.outcome.lock().expect("In check_active.");
292 match *guard {
293 Outcome::Unknown => Ok(guard),
294 _ => Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)).context(format!(
295 "In check_active: Call on finalized operation with outcome: {:?}.",
296 *guard
297 )),
298 }
299 }
300
301 // This function checks the amount of input data sent to us. We reject any buffer
302 // exceeding MAX_RECEIVE_DATA bytes as input to `update`, `update_aad`, and `finish`
303 // in order to force clients into using reasonable limits.
304 fn check_input_length(data: &[u8]) -> Result<()> {
305 if data.len() > MAX_RECEIVE_DATA {
306 // This error code is unique, no context required here.
307 return Err(anyhow!(Error::Rc(ResponseCode::TOO_MUCH_DATA)));
308 }
309 Ok(())
310 }
311
312 // Update the last usage to now.
313 fn touch(&self) {
314 // Expect safety:
315 // `last_usage` is locked only for primitive single line statements.
316 // There is no chance to panic and poison the mutex.
317 *self.last_usage.lock().expect("In touch.") = Instant::now();
318 }
319
320 /// Implementation of `IKeystoreOperation::updateAad`.
321 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
322 fn update_aad(&self, aad_input: &[u8]) -> Result<()> {
323 let mut outcome = self.check_active().context("In update_aad")?;
324 Self::check_input_length(aad_input).context("In update_aad")?;
325 self.touch();
326
Janis Danisevskis85d47932020-10-23 16:12:59 -0700327 let params = KeyParameterArray {
328 params: vec![KmParam {
329 tag: Tag::ASSOCIATED_DATA,
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800330 value: KmParamValue::Blob(aad_input.into()),
Janis Danisevskis85d47932020-10-23 16:12:59 -0700331 }],
332 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700333
Janis Danisevskis85d47932020-10-23 16:12:59 -0700334 let mut out_params: Option<KeyParameterArray> = None;
335 let mut output: Option<ByteArray> = None;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700336
337 let km_op: Box<dyn IKeyMintOperation> =
338 self.km_op.get_interface().context("In update: Failed to get KeyMintOperation.")?;
339
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800340 let (hat, tst) = self
341 .auth_info
342 .lock()
343 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800344 .before_update()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800345 .context("In update_aad: Trying to get auth tokens.")?;
346
Janis Danisevskis1af91262020-08-10 14:58:08 -0700347 self.update_outcome(
348 &mut *outcome,
349 map_km_error(km_op.update(
Janis Danisevskis85d47932020-10-23 16:12:59 -0700350 Some(&params),
351 None,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800352 hat.as_ref(),
353 tst.as_ref(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700354 &mut out_params,
355 &mut output,
356 )),
357 )
358 .context("In update_aad: KeyMint::update failed.")?;
359
360 Ok(())
361 }
362
363 /// Implementation of `IKeystoreOperation::update`.
364 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
365 fn update(&self, input: &[u8]) -> Result<Option<Vec<u8>>> {
366 let mut outcome = self.check_active().context("In update")?;
367 Self::check_input_length(input).context("In update")?;
368 self.touch();
369
Janis Danisevskis85d47932020-10-23 16:12:59 -0700370 let mut out_params: Option<KeyParameterArray> = None;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700371
372 let km_op: Box<dyn IKeyMintOperation> =
373 self.km_op.get_interface().context("In update: Failed to get KeyMintOperation.")?;
374
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800375 let (hat, tst) = self
376 .auth_info
377 .lock()
378 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800379 .before_update()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800380 .context("In update: Trying to get auth tokens.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000381
Janis Danisevskis002891c2021-01-31 13:07:02 -0800382 let mut result: Option<Vec<u8>> = None;
383 let mut consumed = 0usize;
384 loop {
385 let mut output: Option<ByteArray> = None;
386 consumed += self
387 .update_outcome(
388 &mut *outcome,
389 map_km_error(km_op.update(
390 None,
391 Some(&input[consumed..]),
392 hat.as_ref(),
393 tst.as_ref(),
394 &mut out_params,
395 &mut output,
396 )),
397 )
398 .context("In update: KeyMint::update failed.")? as usize;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700399
Janis Danisevskis002891c2021-01-31 13:07:02 -0800400 match (output, &mut result) {
401 (Some(blob), None) => {
402 if !blob.data.is_empty() {
403 result = Some(blob.data)
404 }
Janis Danisevskis3cfd4a42020-11-23 13:42:38 -0800405 }
Janis Danisevskis002891c2021-01-31 13:07:02 -0800406 (Some(mut blob), Some(ref mut result)) => {
407 result.append(&mut blob.data);
408 }
409 (None, _) => {}
Janis Danisevskis3cfd4a42020-11-23 13:42:38 -0800410 }
Janis Danisevskis002891c2021-01-31 13:07:02 -0800411
412 if consumed == input.len() {
413 return Ok(result);
414 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700415 }
416 }
417
418 /// Implementation of `IKeystoreOperation::finish`.
419 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
420 fn finish(&self, input: Option<&[u8]>, signature: Option<&[u8]>) -> Result<Option<Vec<u8>>> {
421 let mut outcome = self.check_active().context("In finish")?;
422 if let Some(input) = input {
423 Self::check_input_length(input).context("In finish")?;
424 }
425 self.touch();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700426
Janis Danisevskis85d47932020-10-23 16:12:59 -0700427 let mut out_params: Option<KeyParameterArray> = None;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700428
429 let km_op: Box<dyn IKeyMintOperation> =
430 self.km_op.get_interface().context("In finish: Failed to get KeyMintOperation.")?;
431
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800432 let (hat, tst, confirmation_token) = self
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800433 .auth_info
434 .lock()
435 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800436 .before_finish()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800437 .context("In finish: Trying to get auth tokens.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000438
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800439 let in_params = confirmation_token.map(|token| KeyParameterArray {
440 params: vec![KmParam {
441 tag: Tag::CONFIRMATION_TOKEN,
442 value: KmParamValue::Blob(token),
443 }],
444 });
445
Janis Danisevskis85d47932020-10-23 16:12:59 -0700446 let output = self
447 .update_outcome(
448 &mut *outcome,
449 map_km_error(km_op.finish(
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800450 in_params.as_ref(),
Janis Danisevskis85d47932020-10-23 16:12:59 -0700451 input,
452 signature,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800453 hat.as_ref(),
454 tst.as_ref(),
Janis Danisevskis85d47932020-10-23 16:12:59 -0700455 &mut out_params,
456 )),
457 )
458 .context("In finish: KeyMint::finish failed.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700459
Qi Wub9433b52020-12-01 14:52:46 +0800460 self.auth_info.lock().unwrap().after_finish().context("In finish.")?;
461
Janis Danisevskis1af91262020-08-10 14:58:08 -0700462 // At this point the operation concluded successfully.
463 *outcome = Outcome::Success;
464
465 if output.is_empty() {
466 Ok(None)
467 } else {
468 Ok(Some(output))
469 }
470 }
471
472 /// Aborts the operation if it is active. IFF the operation is aborted the outcome is
473 /// set to `outcome`. `outcome` must reflect the reason for the abort. Since the operation
474 /// gets aborted `outcome` must not be `Operation::Success` or `Operation::Unknown`.
475 fn abort(&self, outcome: Outcome) -> Result<()> {
476 let mut locked_outcome = self.check_active().context("In abort")?;
477 *locked_outcome = outcome;
478 let km_op: Box<dyn IKeyMintOperation> =
479 self.km_op.get_interface().context("In abort: Failed to get KeyMintOperation.")?;
480
481 map_km_error(km_op.abort()).context("In abort: KeyMint::abort failed.")
482 }
483}
484
485impl Drop for Operation {
486 fn drop(&mut self) {
487 if let Ok(Outcome::Unknown) = self.outcome.get_mut() {
488 // If the operation was still active we call abort, setting
489 // the outcome to `Outcome::Dropped`
490 if let Err(e) = self.abort(Outcome::Dropped) {
491 log::error!("While dropping Operation: abort failed:\n {:?}", e);
492 }
493 }
494 }
495}
496
497/// The OperationDb holds weak references to all ongoing operations.
498/// Its main purpose is to facilitate operation pruning.
499#[derive(Debug, Default)]
500pub struct OperationDb {
501 // TODO replace Vec with WeakTable when the weak_table crate becomes
502 // available.
503 operations: Mutex<Vec<Weak<Operation>>>,
504}
505
506impl OperationDb {
507 /// Creates a new OperationDb.
508 pub fn new() -> Self {
509 Self { operations: Mutex::new(Vec::new()) }
510 }
511
512 /// Creates a new operation.
513 /// This function takes a KeyMint operation and an associated
514 /// owner uid and returns a new Operation wrapped in a `std::sync::Arc`.
515 pub fn create_operation(
516 &self,
517 km_op: Box<dyn IKeyMintOperation>,
518 owner: u32,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800519 auth_info: AuthInfo,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700520 ) -> Arc<Operation> {
521 // We use unwrap because we don't allow code that can panic while locked.
522 let mut operations = self.operations.lock().expect("In create_operation.");
523
524 let mut index: usize = 0;
525 // First we iterate through the operation slots to try and find an unused
526 // slot. If we don't find one, we append the new entry instead.
527 match (*operations).iter_mut().find(|s| {
528 index += 1;
529 s.upgrade().is_none()
530 }) {
531 Some(free_slot) => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800532 let new_op = Arc::new(Operation::new(index - 1, km_op, owner, auth_info));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700533 *free_slot = Arc::downgrade(&new_op);
534 new_op
535 }
536 None => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800537 let new_op = Arc::new(Operation::new(operations.len(), km_op, owner, auth_info));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700538 operations.push(Arc::downgrade(&new_op));
539 new_op
540 }
541 }
542 }
543
544 fn get(&self, index: usize) -> Option<Arc<Operation>> {
545 self.operations.lock().expect("In OperationDb::get.").get(index).and_then(|op| op.upgrade())
546 }
547
548 /// Attempts to prune an operation.
549 ///
550 /// This function is used during operation creation, i.e., by
551 /// `KeystoreSecurityLevel::create_operation`, to try and free up an operation slot
552 /// if it got `ErrorCode::TOO_MANY_OPERATIONS` from the KeyMint backend. It is not
553 /// guaranteed that an operation slot is available after this call successfully
554 /// returned for various reasons. E.g., another thread may have snatched up the newly
555 /// available slot. Callers may have to call prune multiple times before they get a
556 /// free operation slot. Prune may also return `Err(Error::Rc(ResponseCode::BACKEND_BUSY))`
557 /// which indicates that no prunable operation was found.
558 ///
559 /// To find a suitable candidate we compute the malus for the caller and each existing
560 /// operation. The malus is the inverse of the pruning power (caller) or pruning
561 /// resistance (existing operation).
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700562 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700563 /// The malus is based on the number of sibling operations and age. Sibling
564 /// operations are operations that have the same owner (UID).
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700565 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700566 /// Every operation, existing or new, starts with a malus of 1. Every sibling
567 /// increases the malus by one. The age is the time since an operation was last touched.
568 /// It increases the malus by log6(<age in seconds> + 1) rounded down to the next
569 /// integer. So the malus increases stepwise after 5s, 35s, 215s, ...
570 /// Of two operations with the same malus the least recently used one is considered
571 /// weaker.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700572 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700573 /// For the caller to be able to prune an operation it must find an operation
574 /// with a malus higher than its own.
575 ///
576 /// The malus can be expressed as
577 /// ```
578 /// malus = 1 + no_of_siblings + floor(log6(age_in_seconds + 1))
579 /// ```
580 /// where the constant `1` accounts for the operation under consideration.
581 /// In reality we compute it as
582 /// ```
583 /// caller_malus = 1 + running_siblings
584 /// ```
585 /// because the new operation has no age and is not included in the `running_siblings`,
586 /// and
587 /// ```
588 /// running_malus = running_siblings + floor(log6(age_in_seconds + 1))
589 /// ```
590 /// because a running operation is included in the `running_siblings` and it has
591 /// an age.
592 ///
593 /// ## Example
594 /// A caller with no running operations has a malus of 1. Young (age < 5s) operations
595 /// also with no siblings have a malus of one and cannot be pruned by the caller.
596 /// We have to find an operation that has at least one sibling or is older than 5s.
597 ///
598 /// A caller with one running operation has a malus of 2. Now even young siblings
599 /// or single child aging (5s <= age < 35s) operations are off limit. An aging
600 /// sibling of two, however, would have a malus of 3 and would be fair game.
601 ///
602 /// ## Rationale
603 /// Due to the limitation of KeyMint operation slots, we cannot get around pruning or
604 /// a single app could easily DoS KeyMint.
605 /// Keystore 1.0 used to always prune the least recently used operation. This at least
606 /// guaranteed that new operations can always be started. With the increased usage
607 /// of Keystore we saw increased pruning activity which can lead to a livelock
608 /// situation in the worst case.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700609 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700610 /// With the new pruning strategy we want to provide well behaved clients with
611 /// progress assurances while punishing DoS attempts. As a result of this
612 /// strategy we can be in the situation where no operation can be pruned and the
613 /// creation of a new operation fails. This allows single child operations which
614 /// are frequently updated to complete, thereby breaking up livelock situations
615 /// and facilitating system wide progress.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700616 ///
617 /// ## Update
618 /// We also allow callers to cannibalize their own sibling operations if no other
619 /// slot can be found. In this case the least recently used sibling is pruned.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700620 pub fn prune(&self, caller: u32) -> Result<(), Error> {
621 loop {
622 // Maps the uid of the owner to the number of operations that owner has
623 // (running_siblings). More operations per owner lowers the pruning
624 // resistance of the operations of that owner. Whereas the number of
625 // ongoing operations of the caller lowers the pruning power of the caller.
626 let mut owners: HashMap<u32, u64> = HashMap::new();
627 let mut pruning_info: Vec<PruningInfo> = Vec::new();
628
629 let now = Instant::now();
630 self.operations
631 .lock()
632 .expect("In OperationDb::prune: Trying to lock self.operations.")
633 .iter()
634 .for_each(|op| {
635 if let Some(op) = op.upgrade() {
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700636 if let Some(p_info) = op.get_pruning_info() {
637 let owner = p_info.owner;
638 pruning_info.push(p_info);
639 // Count operations per owner.
640 *owners.entry(owner).or_insert(0) += 1;
641 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700642 }
643 });
644
645 let caller_malus = 1u64 + *owners.entry(caller).or_default();
646
647 // We iterate through all operations computing the malus and finding
648 // the candidate with the highest malus which must also be higher
649 // than the caller_malus.
650 struct CandidateInfo {
651 index: usize,
652 malus: u64,
653 last_usage: Instant,
654 age: Duration,
655 }
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700656 let mut oldest_caller_op: Option<CandidateInfo> = None;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700657 let candidate = pruning_info.iter().fold(
658 None,
659 |acc: Option<CandidateInfo>, &PruningInfo { last_usage, owner, index }| {
660 // Compute the age of the current operation.
661 let age = now
662 .checked_duration_since(last_usage)
663 .unwrap_or_else(|| Duration::new(0, 0));
664
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700665 // Find the least recently used sibling as an alternative pruning candidate.
666 if owner == caller {
667 if let Some(CandidateInfo { age: a, .. }) = oldest_caller_op {
668 if age > a {
669 oldest_caller_op =
670 Some(CandidateInfo { index, malus: 0, last_usage, age });
671 }
672 } else {
673 oldest_caller_op =
674 Some(CandidateInfo { index, malus: 0, last_usage, age });
675 }
676 }
677
Janis Danisevskis1af91262020-08-10 14:58:08 -0700678 // Compute the malus of the current operation.
679 // Expect safety: Every owner in pruning_info was counted in
680 // the owners map. So this unwrap cannot panic.
681 let malus = *owners
682 .get(&owner)
683 .expect("This is odd. We should have counted every owner in pruning_info.")
684 + ((age.as_secs() + 1) as f64).log(6.0).floor() as u64;
685
686 // Now check if the current operation is a viable/better candidate
687 // the one currently stored in the accumulator.
688 match acc {
689 // First we have to find any operation that is prunable by the caller.
690 None => {
691 if caller_malus < malus {
692 Some(CandidateInfo { index, malus, last_usage, age })
693 } else {
694 None
695 }
696 }
697 // If we have found one we look for the operation with the worst score.
698 // If there is a tie, the older operation is considered weaker.
699 Some(CandidateInfo { index: i, malus: m, last_usage: l, age: a }) => {
700 if malus > m || (malus == m && age > a) {
701 Some(CandidateInfo { index, malus, last_usage, age })
702 } else {
703 Some(CandidateInfo { index: i, malus: m, last_usage: l, age: a })
704 }
705 }
706 }
707 },
708 );
709
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700710 // If we did not find a suitable candidate we may cannibalize our oldest sibling.
711 let candidate = candidate.or(oldest_caller_op);
712
Janis Danisevskis1af91262020-08-10 14:58:08 -0700713 match candidate {
714 Some(CandidateInfo { index, malus: _, last_usage, age: _ }) => {
715 match self.get(index) {
716 Some(op) => {
717 match op.prune(last_usage) {
718 // We successfully freed up a slot.
719 Ok(()) => break Ok(()),
720 // This means the operation we tried to prune was on its way
721 // out. It also means that the slot it had occupied was freed up.
722 Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)) => break Ok(()),
723 // This means the operation we tried to prune was currently
724 // servicing a request. There are two options.
725 // * Assume that it was touched, which means that its
726 // pruning resistance increased. In that case we have
727 // to start over and find another candidate.
728 // * Assume that the operation is transitioning to end-of-life.
729 // which means that we got a free slot for free.
730 // If we assume the first but the second is true, we prune
731 // a good operation without need (aggressive approach).
732 // If we assume the second but the first is true, our
733 // caller will attempt to create a new KeyMint operation,
734 // fail with `ErrorCode::TOO_MANY_OPERATIONS`, and call
735 // us again (conservative approach).
736 Err(Error::Rc(ResponseCode::OPERATION_BUSY)) => {
737 // We choose the conservative approach, because
738 // every needlessly pruned operation can impact
739 // the user experience.
740 // To switch to the aggressive approach replace
741 // the following line with `continue`.
742 break Ok(());
743 }
744
745 // The candidate may have been touched so the score
746 // has changed since our evaluation.
747 _ => continue,
748 }
749 }
750 // This index does not exist any more. The operation
751 // in this slot was dropped. Good news, a slot
752 // has freed up.
753 None => break Ok(()),
754 }
755 }
756 // We did not get a pruning candidate.
757 None => break Err(Error::Rc(ResponseCode::BACKEND_BUSY)),
758 }
759 }
760 }
761}
762
763/// Implementation of IKeystoreOperation.
764pub struct KeystoreOperation {
765 operation: Mutex<Option<Arc<Operation>>>,
766}
767
768impl KeystoreOperation {
769 /// Creates a new operation instance wrapped in a
770 /// BnKeystoreOperation proxy object. It also
771 /// calls `IBinder::set_requesting_sid` on the new interface, because
772 /// we need it for checking Keystore permissions.
773 pub fn new_native_binder(operation: Arc<Operation>) -> impl IKeystoreOperation + Send {
774 let result =
775 BnKeystoreOperation::new_binder(Self { operation: Mutex::new(Some(operation)) });
776 result.as_binder().set_requesting_sid(true);
777 result
778 }
779
780 /// Grabs the outer operation mutex and calls `f` on the locked operation.
781 /// The function also deletes the operation if it returns with an error or if
782 /// `delete_op` is true.
783 fn with_locked_operation<T, F>(&self, f: F, delete_op: bool) -> Result<T>
784 where
785 for<'a> F: FnOnce(&'a Operation) -> Result<T>,
786 {
787 let mut delete_op: bool = delete_op;
788 match self.operation.try_lock() {
789 Ok(mut mutex_guard) => {
790 let result = match &*mutex_guard {
791 Some(op) => {
792 let result = f(&*op);
793 // Any error here means we can discard the operation.
794 if result.is_err() {
795 delete_op = true;
796 }
797 result
798 }
799 None => Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE))
800 .context("In KeystoreOperation::with_locked_operation"),
801 };
802
803 if delete_op {
804 // We give up our reference to the Operation, thereby freeing up our
805 // internal resources and ending the wrapped KeyMint operation.
806 // This KeystoreOperation object will still be owned by an SpIBinder
807 // until the client drops its remote reference.
808 *mutex_guard = None;
809 }
810 result
811 }
812 Err(_) => Err(Error::Rc(ResponseCode::OPERATION_BUSY))
813 .context("In KeystoreOperation::with_locked_operation"),
814 }
815 }
816}
817
818impl binder::Interface for KeystoreOperation {}
819
820impl IKeystoreOperation for KeystoreOperation {
821 fn updateAad(&self, aad_input: &[u8]) -> binder::public_api::Result<()> {
822 map_or_log_err(
823 self.with_locked_operation(
824 |op| op.update_aad(aad_input).context("In KeystoreOperation::updateAad"),
825 false,
826 ),
827 Ok,
828 )
829 }
830
831 fn update(&self, input: &[u8]) -> binder::public_api::Result<Option<Vec<u8>>> {
832 map_or_log_err(
833 self.with_locked_operation(
834 |op| op.update(input).context("In KeystoreOperation::update"),
835 false,
836 ),
837 Ok,
838 )
839 }
840 fn finish(
841 &self,
842 input: Option<&[u8]>,
843 signature: Option<&[u8]>,
844 ) -> binder::public_api::Result<Option<Vec<u8>>> {
845 map_or_log_err(
846 self.with_locked_operation(
847 |op| op.finish(input, signature).context("In KeystoreOperation::finish"),
848 true,
849 ),
850 Ok,
851 )
852 }
853
854 fn abort(&self) -> binder::public_api::Result<()> {
855 map_or_log_err(
856 self.with_locked_operation(
857 |op| op.abort(Outcome::Abort).context("In KeystoreOperation::abort"),
858 true,
859 ),
860 Ok,
861 )
862 }
863}