• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // 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 
128 use crate::enforcements::AuthInfo;
129 use crate::error::{
130     error_to_serialized_error, into_binder, into_logged_binder, map_km_error, Error, ErrorCode,
131     ResponseCode, SerializedError,
132 };
133 use crate::ks_err;
134 use crate::metrics_store::log_key_operation_event_stats;
135 use crate::utils::watchdog as wd;
136 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
137     IKeyMintOperation::IKeyMintOperation, KeyParameter::KeyParameter, KeyPurpose::KeyPurpose,
138     SecurityLevel::SecurityLevel,
139 };
140 use android_hardware_security_keymint::binder::{BinderFeatures, Strong};
141 use android_system_keystore2::aidl::android::system::keystore2::{
142     IKeystoreOperation::BnKeystoreOperation, IKeystoreOperation::IKeystoreOperation,
143 };
144 use anyhow::{anyhow, Context, Result};
145 use std::{
146     collections::HashMap,
147     sync::{Arc, Mutex, MutexGuard, Weak},
148     time::Duration,
149     time::Instant,
150 };
151 
152 /// Operations have `Outcome::Unknown` as long as they are active. They transition
153 /// to one of the other variants exactly once. The distinction in outcome is mainly
154 /// for the statistic.
155 #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
156 pub enum Outcome {
157     /// Operations have `Outcome::Unknown` as long as they are active.
158     Unknown,
159     /// Operation is successful.
160     Success,
161     /// Operation is aborted.
162     Abort,
163     /// Operation is dropped.
164     Dropped,
165     /// Operation is pruned.
166     Pruned,
167     /// Operation is failed with the error code.
168     ErrorCode(SerializedError),
169 }
170 
171 /// Operation bundles all of the operation related resources and tracks the operation's
172 /// outcome.
173 #[derive(Debug)]
174 pub struct Operation {
175     // The index of this operation in the OperationDb.
176     index: usize,
177     km_op: Strong<dyn IKeyMintOperation>,
178     last_usage: Mutex<Instant>,
179     outcome: Mutex<Outcome>,
180     owner: u32, // Uid of the operation's owner.
181     auth_info: Mutex<AuthInfo>,
182     forced: bool,
183     logging_info: LoggingInfo,
184 }
185 
186 /// Keeps track of the information required for logging operations.
187 #[derive(Debug)]
188 pub struct LoggingInfo {
189     sec_level: SecurityLevel,
190     purpose: KeyPurpose,
191     op_params: Vec<KeyParameter>,
192     key_upgraded: bool,
193 }
194 
195 impl LoggingInfo {
196     /// Constructor
new( sec_level: SecurityLevel, purpose: KeyPurpose, op_params: Vec<KeyParameter>, key_upgraded: bool, ) -> LoggingInfo197     pub fn new(
198         sec_level: SecurityLevel,
199         purpose: KeyPurpose,
200         op_params: Vec<KeyParameter>,
201         key_upgraded: bool,
202     ) -> LoggingInfo {
203         Self { sec_level, purpose, op_params, key_upgraded }
204     }
205 }
206 
207 struct PruningInfo {
208     last_usage: Instant,
209     owner: u32,
210     index: usize,
211     forced: bool,
212 }
213 
214 // We don't except more than 32KiB of data in `update`, `updateAad`, and `finish`.
215 const MAX_RECEIVE_DATA: usize = 0x8000;
216 
217 impl Operation {
218     /// Constructor
new( index: usize, km_op: binder::Strong<dyn IKeyMintOperation>, owner: u32, auth_info: AuthInfo, forced: bool, logging_info: LoggingInfo, ) -> Self219     pub fn new(
220         index: usize,
221         km_op: binder::Strong<dyn IKeyMintOperation>,
222         owner: u32,
223         auth_info: AuthInfo,
224         forced: bool,
225         logging_info: LoggingInfo,
226     ) -> Self {
227         Self {
228             index,
229             km_op,
230             last_usage: Mutex::new(Instant::now()),
231             outcome: Mutex::new(Outcome::Unknown),
232             owner,
233             auth_info: Mutex::new(auth_info),
234             forced,
235             logging_info,
236         }
237     }
238 
get_pruning_info(&self) -> Option<PruningInfo>239     fn get_pruning_info(&self) -> Option<PruningInfo> {
240         // An operation may be finalized.
241         if let Ok(guard) = self.outcome.try_lock() {
242             match *guard {
243                 Outcome::Unknown => {}
244                 // If the outcome is any other than unknown, it has been finalized,
245                 // and we can no longer consider it for pruning.
246                 _ => return None,
247             }
248         }
249         // Else: If we could not grab the lock, this means that the operation is currently
250         //       being used and it may be transitioning to finalized or it was simply updated.
251         //       In any case it is fair game to consider it for pruning. If the operation
252         //       transitioned to a final state, we will notice when we attempt to prune, and
253         //       a subsequent attempt to create a new operation will succeed.
254         Some(PruningInfo {
255             // Expect safety:
256             // `last_usage` is locked only for primitive single line statements.
257             // There is no chance to panic and poison the mutex.
258             last_usage: *self.last_usage.lock().expect("In get_pruning_info."),
259             owner: self.owner,
260             index: self.index,
261             forced: self.forced,
262         })
263     }
264 
prune(&self, last_usage: Instant) -> Result<(), Error>265     fn prune(&self, last_usage: Instant) -> Result<(), Error> {
266         let mut locked_outcome = match self.outcome.try_lock() {
267             Ok(guard) => match *guard {
268                 Outcome::Unknown => guard,
269                 _ => return Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)),
270             },
271             Err(_) => return Err(Error::Rc(ResponseCode::OPERATION_BUSY)),
272         };
273 
274         // In `OperationDb::prune`, which is our caller, we first gather the pruning
275         // information including the last usage. When we select a candidate
276         // we call `prune` on that candidate passing the last_usage
277         // that we gathered earlier. If the actual last usage
278         // has changed since than, it means the operation was busy in the
279         // meantime, which means that we have to reevaluate the pruning score.
280         //
281         // Expect safety:
282         // `last_usage` is locked only for primitive single line statements.
283         // There is no chance to panic and poison the mutex.
284         if *self.last_usage.lock().expect("In Operation::prune()") != last_usage {
285             return Err(Error::Rc(ResponseCode::OPERATION_BUSY));
286         }
287         *locked_outcome = Outcome::Pruned;
288 
289         let _wp = wd::watch("In Operation::prune: calling abort()");
290 
291         // We abort the operation. If there was an error we log it but ignore it.
292         if let Err(e) = map_km_error(self.km_op.abort()) {
293             log::warn!("In prune: KeyMint::abort failed with {:?}.", e);
294         }
295 
296         Ok(())
297     }
298 
299     // This function takes a Result from a KeyMint call and inspects it for errors.
300     // If an error was found it updates the given `locked_outcome` accordingly.
301     // It forwards the Result unmodified.
302     // The precondition to this call must be *locked_outcome == Outcome::Unknown.
303     // Ideally the `locked_outcome` came from a successful call to `check_active`
304     // see below.
update_outcome<T>( &self, locked_outcome: &mut Outcome, err: Result<T, Error>, ) -> Result<T, Error>305     fn update_outcome<T>(
306         &self,
307         locked_outcome: &mut Outcome,
308         err: Result<T, Error>,
309     ) -> Result<T, Error> {
310         match &err {
311             Err(e) => *locked_outcome = Outcome::ErrorCode(error_to_serialized_error(e)),
312             Ok(_) => (),
313         }
314         err
315     }
316 
317     // This function grabs the outcome lock and checks the current outcome state.
318     // If the outcome is still `Outcome::Unknown`, this function returns
319     // the locked outcome for further updates. In any other case it returns
320     // ErrorCode::INVALID_OPERATION_HANDLE indicating that this operation has
321     // been finalized and is no longer active.
check_active(&self) -> Result<MutexGuard<Outcome>>322     fn check_active(&self) -> Result<MutexGuard<Outcome>> {
323         let guard = self.outcome.lock().expect("In check_active.");
324         match *guard {
325             Outcome::Unknown => Ok(guard),
326             _ => Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE))
327                 .context(ks_err!("Call on finalized operation with outcome: {:?}.", *guard)),
328         }
329     }
330 
331     // This function checks the amount of input data sent to us. We reject any buffer
332     // exceeding MAX_RECEIVE_DATA bytes as input to `update`, `update_aad`, and `finish`
333     // in order to force clients into using reasonable limits.
check_input_length(data: &[u8]) -> Result<()>334     fn check_input_length(data: &[u8]) -> Result<()> {
335         if data.len() > MAX_RECEIVE_DATA {
336             // This error code is unique, no context required here.
337             return Err(anyhow!(Error::Rc(ResponseCode::TOO_MUCH_DATA)));
338         }
339         Ok(())
340     }
341 
342     // Update the last usage to now.
touch(&self)343     fn touch(&self) {
344         // Expect safety:
345         // `last_usage` is locked only for primitive single line statements.
346         // There is no chance to panic and poison the mutex.
347         *self.last_usage.lock().expect("In touch.") = Instant::now();
348     }
349 
350     /// Implementation of `IKeystoreOperation::updateAad`.
351     /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
update_aad(&self, aad_input: &[u8]) -> Result<()>352     fn update_aad(&self, aad_input: &[u8]) -> Result<()> {
353         let mut outcome = self.check_active().context("In update_aad")?;
354         Self::check_input_length(aad_input).context("In update_aad")?;
355         self.touch();
356 
357         let (hat, tst) = self
358             .auth_info
359             .lock()
360             .unwrap()
361             .before_update()
362             .context(ks_err!("Trying to get auth tokens."))?;
363 
364         self.update_outcome(&mut outcome, {
365             let _wp = wd::watch("Operation::update_aad: calling updateAad");
366             map_km_error(self.km_op.updateAad(aad_input, hat.as_ref(), tst.as_ref()))
367         })
368         .context(ks_err!("Update failed."))?;
369 
370         Ok(())
371     }
372 
373     /// Implementation of `IKeystoreOperation::update`.
374     /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
update(&self, input: &[u8]) -> Result<Option<Vec<u8>>>375     fn update(&self, input: &[u8]) -> Result<Option<Vec<u8>>> {
376         let mut outcome = self.check_active().context("In update")?;
377         Self::check_input_length(input).context("In update")?;
378         self.touch();
379 
380         let (hat, tst) = self
381             .auth_info
382             .lock()
383             .unwrap()
384             .before_update()
385             .context(ks_err!("Trying to get auth tokens."))?;
386 
387         let output = self
388             .update_outcome(&mut outcome, {
389                 let _wp = wd::watch("Operation::update: calling update");
390                 map_km_error(self.km_op.update(input, hat.as_ref(), tst.as_ref()))
391             })
392             .context(ks_err!("Update failed."))?;
393 
394         if output.is_empty() {
395             Ok(None)
396         } else {
397             Ok(Some(output))
398         }
399     }
400 
401     /// Implementation of `IKeystoreOperation::finish`.
402     /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
finish(&self, input: Option<&[u8]>, signature: Option<&[u8]>) -> Result<Option<Vec<u8>>>403     fn finish(&self, input: Option<&[u8]>, signature: Option<&[u8]>) -> Result<Option<Vec<u8>>> {
404         let mut outcome = self.check_active().context("In finish")?;
405         if let Some(input) = input {
406             Self::check_input_length(input).context("In finish")?;
407         }
408         self.touch();
409 
410         let (hat, tst, confirmation_token) = self
411             .auth_info
412             .lock()
413             .unwrap()
414             .before_finish()
415             .context(ks_err!("Trying to get auth tokens."))?;
416 
417         let output = self
418             .update_outcome(&mut outcome, {
419                 let _wp = wd::watch("Operation::finish: calling finish");
420                 map_km_error(self.km_op.finish(
421                     input,
422                     signature,
423                     hat.as_ref(),
424                     tst.as_ref(),
425                     confirmation_token.as_deref(),
426                 ))
427             })
428             .context(ks_err!("Finish failed."))?;
429 
430         self.auth_info.lock().unwrap().after_finish().context("In finish.")?;
431 
432         // At this point the operation concluded successfully.
433         *outcome = Outcome::Success;
434 
435         if output.is_empty() {
436             Ok(None)
437         } else {
438             Ok(Some(output))
439         }
440     }
441 
442     /// Aborts the operation if it is active. IFF the operation is aborted the outcome is
443     /// set to `outcome`. `outcome` must reflect the reason for the abort. Since the operation
444     /// gets aborted `outcome` must not be `Operation::Success` or `Operation::Unknown`.
abort(&self, outcome: Outcome) -> Result<()>445     fn abort(&self, outcome: Outcome) -> Result<()> {
446         let mut locked_outcome = self.check_active().context("In abort")?;
447         *locked_outcome = outcome;
448 
449         {
450             let _wp = wd::watch("Operation::abort: calling abort");
451             map_km_error(self.km_op.abort()).context(ks_err!("KeyMint::abort failed."))
452         }
453     }
454 }
455 
456 impl Drop for Operation {
drop(&mut self)457     fn drop(&mut self) {
458         let guard = self.outcome.lock().expect("In drop.");
459         log_key_operation_event_stats(
460             self.logging_info.sec_level,
461             self.logging_info.purpose,
462             &(self.logging_info.op_params),
463             &guard,
464             self.logging_info.key_upgraded,
465         );
466         if let Outcome::Unknown = *guard {
467             drop(guard);
468             // If the operation was still active we call abort, setting
469             // the outcome to `Outcome::Dropped`
470             if let Err(e) = self.abort(Outcome::Dropped) {
471                 log::error!("While dropping Operation: abort failed:\n    {:?}", e);
472             }
473         }
474     }
475 }
476 
477 /// The OperationDb holds weak references to all ongoing operations.
478 /// Its main purpose is to facilitate operation pruning.
479 #[derive(Debug, Default)]
480 pub struct OperationDb {
481     // TODO replace Vec with WeakTable when the weak_table crate becomes
482     // available.
483     operations: Mutex<Vec<Weak<Operation>>>,
484 }
485 
486 impl OperationDb {
487     /// Creates a new OperationDb.
new() -> Self488     pub fn new() -> Self {
489         Self { operations: Mutex::new(Vec::new()) }
490     }
491 
492     /// Creates a new operation.
493     /// This function takes a KeyMint operation and an associated
494     /// owner uid and returns a new Operation wrapped in a `std::sync::Arc`.
create_operation( &self, km_op: binder::Strong<dyn IKeyMintOperation>, owner: u32, auth_info: AuthInfo, forced: bool, logging_info: LoggingInfo, ) -> Arc<Operation>495     pub fn create_operation(
496         &self,
497         km_op: binder::Strong<dyn IKeyMintOperation>,
498         owner: u32,
499         auth_info: AuthInfo,
500         forced: bool,
501         logging_info: LoggingInfo,
502     ) -> Arc<Operation> {
503         // We use unwrap because we don't allow code that can panic while locked.
504         let mut operations = self.operations.lock().expect("In create_operation.");
505 
506         let mut index: usize = 0;
507         // First we iterate through the operation slots to try and find an unused
508         // slot. If we don't find one, we append the new entry instead.
509         match (*operations).iter_mut().find(|s| {
510             index += 1;
511             s.upgrade().is_none()
512         }) {
513             Some(free_slot) => {
514                 let new_op = Arc::new(Operation::new(
515                     index - 1,
516                     km_op,
517                     owner,
518                     auth_info,
519                     forced,
520                     logging_info,
521                 ));
522                 *free_slot = Arc::downgrade(&new_op);
523                 new_op
524             }
525             None => {
526                 let new_op = Arc::new(Operation::new(
527                     operations.len(),
528                     km_op,
529                     owner,
530                     auth_info,
531                     forced,
532                     logging_info,
533                 ));
534                 operations.push(Arc::downgrade(&new_op));
535                 new_op
536             }
537         }
538     }
539 
get(&self, index: usize) -> Option<Arc<Operation>>540     fn get(&self, index: usize) -> Option<Arc<Operation>> {
541         self.operations.lock().expect("In OperationDb::get.").get(index).and_then(|op| op.upgrade())
542     }
543 
544     /// Attempts to prune an operation.
545     ///
546     /// This function is used during operation creation, i.e., by
547     /// `KeystoreSecurityLevel::create_operation`, to try and free up an operation slot
548     /// if it got `ErrorCode::TOO_MANY_OPERATIONS` from the KeyMint backend. It is not
549     /// guaranteed that an operation slot is available after this call successfully
550     /// returned for various reasons. E.g., another thread may have snatched up the newly
551     /// available slot. Callers may have to call prune multiple times before they get a
552     /// free operation slot. Prune may also return `Err(Error::Rc(ResponseCode::BACKEND_BUSY))`
553     /// which indicates that no prunable operation was found.
554     ///
555     /// To find a suitable candidate we compute the malus for the caller and each existing
556     /// operation. The malus is the inverse of the pruning power (caller) or pruning
557     /// resistance (existing operation).
558     ///
559     /// The malus is based on the number of sibling operations and age. Sibling
560     /// operations are operations that have the same owner (UID).
561     ///
562     /// Every operation, existing or new, starts with a malus of 1. Every sibling
563     /// increases the malus by one. The age is the time since an operation was last touched.
564     /// It increases the malus by log6(<age in seconds> + 1) rounded down to the next
565     /// integer. So the malus increases stepwise after 5s, 35s, 215s, ...
566     /// Of two operations with the same malus the least recently used one is considered
567     /// weaker.
568     ///
569     /// For the caller to be able to prune an operation it must find an operation
570     /// with a malus higher than its own.
571     ///
572     /// The malus can be expressed as
573     /// ```
574     /// malus = 1 + no_of_siblings + floor(log6(age_in_seconds + 1))
575     /// ```
576     /// where the constant `1` accounts for the operation under consideration.
577     /// In reality we compute it as
578     /// ```
579     /// caller_malus = 1 + running_siblings
580     /// ```
581     /// because the new operation has no age and is not included in the `running_siblings`,
582     /// and
583     /// ```
584     /// running_malus = running_siblings + floor(log6(age_in_seconds + 1))
585     /// ```
586     /// because a running operation is included in the `running_siblings` and it has
587     /// an age.
588     ///
589     /// ## Example
590     /// A caller with no running operations has a malus of 1. Young (age < 5s) operations
591     /// also with no siblings have a malus of one and cannot be pruned by the caller.
592     /// We have to find an operation that has at least one sibling or is older than 5s.
593     ///
594     /// A caller with one running operation has a malus of 2. Now even young siblings
595     /// or single child aging (5s <= age < 35s) operations are off limit. An aging
596     /// sibling of two, however, would have a malus of 3 and would be fair game.
597     ///
598     /// ## Rationale
599     /// Due to the limitation of KeyMint operation slots, we cannot get around pruning or
600     /// a single app could easily DoS KeyMint.
601     /// Keystore 1.0 used to always prune the least recently used operation. This at least
602     /// guaranteed that new operations can always be started. With the increased usage
603     /// of Keystore we saw increased pruning activity which can lead to a livelock
604     /// situation in the worst case.
605     ///
606     /// With the new pruning strategy we want to provide well behaved clients with
607     /// progress assurances while punishing DoS attempts. As a result of this
608     /// strategy we can be in the situation where no operation can be pruned and the
609     /// creation of a new operation fails. This allows single child operations which
610     /// are frequently updated to complete, thereby breaking up livelock situations
611     /// and facilitating system wide progress.
612     ///
613     /// ## Update
614     /// We also allow callers to cannibalize their own sibling operations if no other
615     /// slot can be found. In this case the least recently used sibling is pruned.
prune(&self, caller: u32, forced: bool) -> Result<(), Error>616     pub fn prune(&self, caller: u32, forced: bool) -> Result<(), Error> {
617         loop {
618             // Maps the uid of the owner to the number of operations that owner has
619             // (running_siblings). More operations per owner lowers the pruning
620             // resistance of the operations of that owner. Whereas the number of
621             // ongoing operations of the caller lowers the pruning power of the caller.
622             let mut owners: HashMap<u32, u64> = HashMap::new();
623             let mut pruning_info: Vec<PruningInfo> = Vec::new();
624 
625             let now = Instant::now();
626             self.operations
627                 .lock()
628                 .expect("In OperationDb::prune: Trying to lock self.operations.")
629                 .iter()
630                 .for_each(|op| {
631                     if let Some(op) = op.upgrade() {
632                         if let Some(p_info) = op.get_pruning_info() {
633                             let owner = p_info.owner;
634                             pruning_info.push(p_info);
635                             // Count operations per owner.
636                             *owners.entry(owner).or_insert(0) += 1;
637                         }
638                     }
639                 });
640 
641             // If the operation is forced, the caller has a malus of 0.
642             let caller_malus = if forced { 0 } else { 1u64 + *owners.entry(caller).or_default() };
643 
644             // We iterate through all operations computing the malus and finding
645             // the candidate with the highest malus which must also be higher
646             // than the caller_malus.
647             struct CandidateInfo {
648                 index: usize,
649                 malus: u64,
650                 last_usage: Instant,
651                 age: Duration,
652             }
653             let mut oldest_caller_op: Option<CandidateInfo> = None;
654             let candidate = pruning_info.iter().fold(
655                 None,
656                 |acc: Option<CandidateInfo>, &PruningInfo { last_usage, owner, index, forced }| {
657                     // Compute the age of the current operation.
658                     let age = now
659                         .checked_duration_since(last_usage)
660                         .unwrap_or_else(|| Duration::new(0, 0));
661 
662                     // Find the least recently used sibling as an alternative pruning candidate.
663                     if owner == caller {
664                         if let Some(CandidateInfo { age: a, .. }) = oldest_caller_op {
665                             if age > a {
666                                 oldest_caller_op =
667                                     Some(CandidateInfo { index, malus: 0, last_usage, age });
668                             }
669                         } else {
670                             oldest_caller_op =
671                                 Some(CandidateInfo { index, malus: 0, last_usage, age });
672                         }
673                     }
674 
675                     // Compute the malus of the current operation.
676                     let malus = if forced {
677                         // Forced operations have a malus of 0. And cannot even be pruned
678                         // by other forced operations.
679                         0
680                     } else {
681                         // Expect safety: Every owner in pruning_info was counted in
682                         // the owners map. So this unwrap cannot panic.
683                         *owners.get(&owner).expect(
684                             "This is odd. We should have counted every owner in pruning_info.",
685                         ) + ((age.as_secs() + 1) as f64).log(6.0).floor() as u64
686                     };
687 
688                     // Now check if the current operation is a viable/better candidate
689                     // the one currently stored in the accumulator.
690                     match acc {
691                         // First we have to find any operation that is prunable by the caller.
692                         None => {
693                             if caller_malus < malus {
694                                 Some(CandidateInfo { index, malus, last_usage, age })
695                             } else {
696                                 None
697                             }
698                         }
699                         // If we have found one we look for the operation with the worst score.
700                         // If there is a tie, the older operation is considered weaker.
701                         Some(CandidateInfo { index: i, malus: m, last_usage: l, age: a }) => {
702                             if malus > m || (malus == m && age > a) {
703                                 Some(CandidateInfo { index, malus, last_usage, age })
704                             } else {
705                                 Some(CandidateInfo { index: i, malus: m, last_usage: l, age: a })
706                             }
707                         }
708                     }
709                 },
710             );
711 
712             // If we did not find a suitable candidate we may cannibalize our oldest sibling.
713             let candidate = candidate.or(oldest_caller_op);
714 
715             match candidate {
716                 Some(CandidateInfo { index, malus: _, last_usage, age: _ }) => {
717                     match self.get(index) {
718                         Some(op) => {
719                             match op.prune(last_usage) {
720                                 // We successfully freed up a slot.
721                                 Ok(()) => break Ok(()),
722                                 // This means the operation we tried to prune was on its way
723                                 // out. It also means that the slot it had occupied was freed up.
724                                 Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)) => break Ok(()),
725                                 // This means the operation we tried to prune was currently
726                                 // servicing a request. There are two options.
727                                 // * Assume that it was touched, which means that its
728                                 //   pruning resistance increased. In that case we have
729                                 //   to start over and find another candidate.
730                                 // * Assume that the operation is transitioning to end-of-life.
731                                 //   which means that we got a free slot for free.
732                                 // If we assume the first but the second is true, we prune
733                                 // a good operation without need (aggressive approach).
734                                 // If we assume the second but the first is true, our
735                                 // caller will attempt to create a new KeyMint operation,
736                                 // fail with `ErrorCode::TOO_MANY_OPERATIONS`, and call
737                                 // us again (conservative approach).
738                                 Err(Error::Rc(ResponseCode::OPERATION_BUSY)) => {
739                                     // We choose the conservative approach, because
740                                     // every needlessly pruned operation can impact
741                                     // the user experience.
742                                     // To switch to the aggressive approach replace
743                                     // the following line with `continue`.
744                                     break Ok(());
745                                 }
746 
747                                 // The candidate may have been touched so the score
748                                 // has changed since our evaluation.
749                                 _ => continue,
750                             }
751                         }
752                         // This index does not exist any more. The operation
753                         // in this slot was dropped. Good news, a slot
754                         // has freed up.
755                         None => break Ok(()),
756                     }
757                 }
758                 // We did not get a pruning candidate.
759                 None => break Err(Error::Rc(ResponseCode::BACKEND_BUSY)),
760             }
761         }
762     }
763 }
764 
765 /// Implementation of IKeystoreOperation.
766 pub struct KeystoreOperation {
767     operation: Mutex<Option<Arc<Operation>>>,
768 }
769 
770 impl KeystoreOperation {
771     /// Creates a new operation instance wrapped in a
772     /// BnKeystoreOperation proxy object. It also enables
773     /// `BinderFeatures::set_requesting_sid` on the new interface, because
774     /// we need it for checking Keystore permissions.
new_native_binder(operation: Arc<Operation>) -> binder::Strong<dyn IKeystoreOperation>775     pub fn new_native_binder(operation: Arc<Operation>) -> binder::Strong<dyn IKeystoreOperation> {
776         BnKeystoreOperation::new_binder(
777             Self { operation: Mutex::new(Some(operation)) },
778             BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
779         )
780     }
781 
782     /// Grabs the outer operation mutex and calls `f` on the locked operation.
783     /// The function also deletes the operation if it returns with an error or if
784     /// `delete_op` is true.
with_locked_operation<T, F>(&self, f: F, delete_op: bool) -> Result<T> where for<'a> F: FnOnce(&'a Operation) -> Result<T>,785     fn with_locked_operation<T, F>(&self, f: F, delete_op: bool) -> Result<T>
786     where
787         for<'a> F: FnOnce(&'a Operation) -> Result<T>,
788     {
789         let mut delete_op: bool = delete_op;
790         match self.operation.try_lock() {
791             Ok(mut mutex_guard) => {
792                 let result = match &*mutex_guard {
793                     Some(op) => {
794                         let result = f(op);
795                         // Any error here means we can discard the operation.
796                         if result.is_err() {
797                             delete_op = true;
798                         }
799                         result
800                     }
801                     None => Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE))
802                         .context(ks_err!("KeystoreOperation::with_locked_operation")),
803                 };
804 
805                 if delete_op {
806                     // We give up our reference to the Operation, thereby freeing up our
807                     // internal resources and ending the wrapped KeyMint operation.
808                     // This KeystoreOperation object will still be owned by an SpIBinder
809                     // until the client drops its remote reference.
810                     *mutex_guard = None;
811                 }
812                 result
813             }
814             Err(_) => Err(Error::Rc(ResponseCode::OPERATION_BUSY))
815                 .context(ks_err!("KeystoreOperation::with_locked_operation")),
816         }
817     }
818 }
819 
820 impl binder::Interface for KeystoreOperation {}
821 
822 impl IKeystoreOperation for KeystoreOperation {
updateAad(&self, aad_input: &[u8]) -> binder::Result<()>823     fn updateAad(&self, aad_input: &[u8]) -> binder::Result<()> {
824         let _wp = wd::watch("IKeystoreOperation::updateAad");
825         self.with_locked_operation(
826             |op| op.update_aad(aad_input).context(ks_err!("KeystoreOperation::updateAad")),
827             false,
828         )
829         .map_err(into_logged_binder)
830     }
831 
update(&self, input: &[u8]) -> binder::Result<Option<Vec<u8>>>832     fn update(&self, input: &[u8]) -> binder::Result<Option<Vec<u8>>> {
833         let _wp = wd::watch("IKeystoreOperation::update");
834         self.with_locked_operation(
835             |op| op.update(input).context(ks_err!("KeystoreOperation::update")),
836             false,
837         )
838         .map_err(into_logged_binder)
839     }
finish( &self, input: Option<&[u8]>, signature: Option<&[u8]>, ) -> binder::Result<Option<Vec<u8>>>840     fn finish(
841         &self,
842         input: Option<&[u8]>,
843         signature: Option<&[u8]>,
844     ) -> binder::Result<Option<Vec<u8>>> {
845         let _wp = wd::watch("IKeystoreOperation::finish");
846         self.with_locked_operation(
847             |op| op.finish(input, signature).context(ks_err!("KeystoreOperation::finish")),
848             true,
849         )
850         .map_err(into_logged_binder)
851     }
852 
abort(&self) -> binder::Result<()>853     fn abort(&self) -> binder::Result<()> {
854         let _wp = wd::watch("IKeystoreOperation::abort");
855         let result = self.with_locked_operation(
856             |op| op.abort(Outcome::Abort).context(ks_err!("KeystoreOperation::abort")),
857             true,
858         );
859         result.map_err(|e| {
860             match e.root_cause().downcast_ref::<Error>() {
861                 // Calling abort on expired operations is something very common.
862                 // There is no reason to clutter the log with it. It is never the cause
863                 // for a true problem.
864                 Some(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)) => {}
865                 _ => log::error!("{:?}", e),
866             };
867             into_binder(e)
868         })
869     }
870 }
871