blob: f71577b2a8dcb0a3c60a6eec08b7910353860e50 [file] [log] [blame]
Janis Danisevskis1af91262020-08-10 14:58:08 -07001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! This crate implements the `IKeystoreOperation` AIDL interface, which represents
16//! an ongoing key operation, as well as the operation database, which is mainly
17//! required for tracking operations for the purpose of pruning.
18//! This crate also implements an operation pruning strategy.
19//!
20//! Operations implement the API calls update, finish, and abort.
21//! Additionally, an operation can be dropped and pruned. The former
22//! happens if the client deletes a binder to the operation object.
23//! An existing operation may get pruned when running out of operation
24//! slots and a new operation takes precedence.
25//!
26//! ## Operation Lifecycle
27//! An operation gets created when the client calls `IKeystoreSecurityLevel::create`.
28//! It may receive zero or more update request. The lifecycle ends when:
29//! * `update` yields an error.
30//! * `finish` is called.
31//! * `abort` is called.
32//! * The operation gets dropped.
33//! * The operation gets pruned.
34//! `Operation` has an `Outcome` member. While the outcome is `Outcome::Unknown`,
35//! the operation is active and in a good state. Any of the above conditions may
36//! change the outcome to one of the defined outcomes Success, Abort, Dropped,
37//! Pruned, or ErrorCode. The latter is chosen in the case of an unexpected error, during
38//! `update` or `finish`. `Success` is chosen iff `finish` completes without error.
39//! Note that all operations get dropped eventually in the sense that they lose
40//! their last reference and get destroyed. At that point, the fate of the operation
41//! gets logged. However, an operation will transition to `Outcome::Dropped` iff
42//! the operation was still active (`Outcome::Unknown`) at that time.
43//!
44//! ## Operation Dropping
45//! To observe the dropping of an operation, we have to make sure that there
46//! are no strong references to the IBinder representing this operation.
47//! This would be simple enough if the operation object would need to be accessed
48//! only by transactions. But to perform pruning, we have to retain a reference to the
49//! original operation object.
50//!
51//! ## Operation Pruning
52//! Pruning an operation happens during the creation of a new operation.
53//! We have to iterate through the operation database to find a suitable
54//! candidate. Then we abort and finalize this operation setting its outcome to
55//! `Outcome::Pruned`. The corresponding KeyMint operation slot will have been freed
56//! up at this point, but the `Operation` object lingers. When the client
57//! attempts to use the operation again they will receive
58//! ErrorCode::INVALID_OPERATION_HANDLE indicating that the operation no longer
59//! exits. This should be the cue for the client to destroy its binder.
60//! At that point the operation gets dropped.
61//!
62//! ## Architecture
63//! The `IKeystoreOperation` trait is implemented by `KeystoreOperation`.
64//! This acts as a proxy object holding a strong reference to actual operation
65//! implementation `Operation`.
66//!
67//! ```
68//! struct KeystoreOperation {
69//! operation: Mutex<Option<Arc<Operation>>>,
70//! }
71//! ```
72//!
73//! The `Mutex` serves two purposes. It provides interior mutability allowing
74//! us to set the Option to None. We do this when the life cycle ends during
75//! a call to `update`, `finish`, or `abort`. As a result most of the Operation
76//! related resources are freed. The `KeystoreOperation` proxy object still
77//! lingers until dropped by the client.
78//! The second purpose is to protect operations against concurrent usage.
79//! Failing to lock this mutex yields `ResponseCode::OPERATION_BUSY` and indicates
80//! a programming error in the client.
81//!
82//! Note that the Mutex only protects the operation against concurrent client calls.
83//! We still retain weak references to the operation in the operation database:
84//!
85//! ```
86//! struct OperationDb {
87//! operations: Mutex<Vec<Weak<Operation>>>
88//! }
89//! ```
90//!
91//! This allows us to access the operations for the purpose of pruning.
92//! We do this in three phases.
93//! 1. We gather the pruning information. Besides non mutable information,
94//! we access `last_usage` which is protected by a mutex.
95//! We only lock this mutex for single statements at a time. During
96//! this phase we hold the operation db lock.
97//! 2. We choose a pruning candidate by computing the pruning resistance
98//! of each operation. We do this entirely with information we now
99//! have on the stack without holding any locks.
100//! (See `OperationDb::prune` for more details on the pruning strategy.)
101//! 3. During pruning we briefly lock the operation database again to get the
102//! the pruning candidate by index. We then attempt to abort the candidate.
103//! If the candidate was touched in the meantime or is currently fulfilling
104//! a request (i.e., the client calls update, finish, or abort),
105//! we go back to 1 and try again.
106//!
107//! So the outer Mutex in `KeystoreOperation::operation` only protects
108//! operations against concurrent client calls but not against concurrent
109//! pruning attempts. This is what the `Operation::outcome` mutex is used for.
110//!
111//! ```
112//! struct Operation {
113//! ...
114//! outcome: Mutex<Outcome>,
115//! ...
116//! }
117//! ```
118//!
119//! Any request that can change the outcome, i.e., `update`, `finish`, `abort`,
120//! `drop`, and `prune` has to take the outcome lock and check if the outcome
121//! is still `Outcome::Unknown` before entering. `prune` is special in that
122//! it will `try_lock`, because we don't want to be blocked on a potentially
123//! long running request at another operation. If it fails to get the lock
124//! the operation is either being touched, which changes its pruning resistance,
125//! or it transitions to its end-of-life, which means we may get a free slot.
126//! Either way, we have to revaluate the pruning scores.
127
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800128use crate::enforcements::AuthInfo;
Janis Danisevskis778245c2021-03-04 15:40:23 -0800129use crate::error::{map_err_with, map_km_error, map_or_log_err, Error, ErrorCode, ResponseCode};
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000130use crate::metrics::log_key_operation_event_stats;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000131use crate::utils::Asp;
132use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000133 IKeyMintOperation::IKeyMintOperation, KeyParameter::KeyParameter, KeyPurpose::KeyPurpose,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000134};
135use android_system_keystore2::aidl::android::system::keystore2::{
136 IKeystoreOperation::BnKeystoreOperation, IKeystoreOperation::IKeystoreOperation,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000137};
138use anyhow::{anyhow, Context, Result};
Andrew Walbran808e8602021-03-16 13:58:28 +0000139use binder::IBinderInternal;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700140use std::{
141 collections::HashMap,
142 sync::{Arc, Mutex, MutexGuard, Weak},
143 time::Duration,
144 time::Instant,
145};
146
Janis Danisevskis1af91262020-08-10 14:58:08 -0700147/// Operations have `Outcome::Unknown` as long as they are active. They transition
148/// to one of the other variants exactly once. The distinction in outcome is mainly
149/// for the statistic.
150#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000151pub enum Outcome {
152 /// Operations have `Outcome::Unknown` as long as they are active.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700153 Unknown,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000154 /// Operation is successful.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700155 Success,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000156 /// Operation is aborted.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700157 Abort,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000158 /// Operation is dropped.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700159 Dropped,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000160 /// Operation is pruned.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700161 Pruned,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000162 /// Operation is failed with the error code.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700163 ErrorCode(ErrorCode),
164}
165
166/// Operation bundles all of the operation related resources and tracks the operation's
167/// outcome.
168#[derive(Debug)]
169pub struct Operation {
170 // The index of this operation in the OperationDb.
171 index: usize,
172 km_op: Asp,
173 last_usage: Mutex<Instant>,
174 outcome: Mutex<Outcome>,
175 owner: u32, // Uid of the operation's owner.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800176 auth_info: Mutex<AuthInfo>,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800177 forced: bool,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000178 logging_info: LoggingInfo,
179}
180
181/// Keeps track of the information required for logging operations.
182#[derive(Debug)]
183pub struct LoggingInfo {
184 purpose: KeyPurpose,
185 op_params: Vec<KeyParameter>,
186 key_upgraded: bool,
187}
188
189impl LoggingInfo {
190 /// Constructor
191 pub fn new(
192 purpose: KeyPurpose,
193 op_params: Vec<KeyParameter>,
194 key_upgraded: bool,
195 ) -> LoggingInfo {
196 Self { purpose, op_params, key_upgraded }
197 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700198}
199
200struct PruningInfo {
201 last_usage: Instant,
202 owner: u32,
203 index: usize,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800204 forced: bool,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700205}
206
Janis Danisevskis1af91262020-08-10 14:58:08 -0700207// We don't except more than 32KiB of data in `update`, `updateAad`, and `finish`.
208const MAX_RECEIVE_DATA: usize = 0x8000;
209
210impl Operation {
211 /// Constructor
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000212 pub fn new(
213 index: usize,
Stephen Crane221bbb52020-12-16 15:52:10 -0800214 km_op: binder::Strong<dyn IKeyMintOperation>,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000215 owner: u32,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800216 auth_info: AuthInfo,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800217 forced: bool,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000218 logging_info: LoggingInfo,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000219 ) -> Self {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700220 Self {
221 index,
222 km_op: Asp::new(km_op.as_binder()),
223 last_usage: Mutex::new(Instant::now()),
224 outcome: Mutex::new(Outcome::Unknown),
225 owner,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800226 auth_info: Mutex::new(auth_info),
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800227 forced,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000228 logging_info,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700229 }
230 }
231
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700232 fn get_pruning_info(&self) -> Option<PruningInfo> {
233 // An operation may be finalized.
234 if let Ok(guard) = self.outcome.try_lock() {
235 match *guard {
236 Outcome::Unknown => {}
237 // If the outcome is any other than unknown, it has been finalized,
238 // and we can no longer consider it for pruning.
239 _ => return None,
240 }
241 }
242 // Else: If we could not grab the lock, this means that the operation is currently
243 // being used and it may be transitioning to finalized or it was simply updated.
244 // In any case it is fair game to consider it for pruning. If the operation
245 // transitioned to a final state, we will notice when we attempt to prune, and
246 // a subsequent attempt to create a new operation will succeed.
247 Some(PruningInfo {
248 // Expect safety:
249 // `last_usage` is locked only for primitive single line statements.
250 // There is no chance to panic and poison the mutex.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700251 last_usage: *self.last_usage.lock().expect("In get_pruning_info."),
252 owner: self.owner,
253 index: self.index,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800254 forced: self.forced,
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700255 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700256 }
257
258 fn prune(&self, last_usage: Instant) -> Result<(), Error> {
259 let mut locked_outcome = match self.outcome.try_lock() {
260 Ok(guard) => match *guard {
261 Outcome::Unknown => guard,
262 _ => return Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)),
263 },
264 Err(_) => return Err(Error::Rc(ResponseCode::OPERATION_BUSY)),
265 };
266
267 // In `OperationDb::prune`, which is our caller, we first gather the pruning
268 // information including the last usage. When we select a candidate
269 // we call `prune` on that candidate passing the last_usage
270 // that we gathered earlier. If the actual last usage
271 // has changed since than, it means the operation was busy in the
272 // meantime, which means that we have to reevaluate the pruning score.
273 //
274 // Expect safety:
275 // `last_usage` is locked only for primitive single line statements.
276 // There is no chance to panic and poison the mutex.
277 if *self.last_usage.lock().expect("In Operation::prune()") != last_usage {
278 return Err(Error::Rc(ResponseCode::OPERATION_BUSY));
279 }
280 *locked_outcome = Outcome::Pruned;
281
Stephen Crane221bbb52020-12-16 15:52:10 -0800282 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
283 match self.km_op.get_interface() {
284 Ok(km_op) => km_op,
285 Err(e) => {
286 log::error!("In prune: Failed to get KeyMintOperation interface.\n {:?}", e);
287 return Err(Error::sys());
288 }
289 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700290
291 // We abort the operation. If there was an error we log it but ignore it.
292 if let Err(e) = map_km_error(km_op.abort()) {
293 log::error!("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.
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(Error::Km(e)) => *locked_outcome = Outcome::ErrorCode(*e),
312 Err(_) => *locked_outcome = Outcome::ErrorCode(ErrorCode::UNKNOWN_ERROR),
313 Ok(_) => (),
314 }
315 err
316 }
317
318 // This function grabs the outcome lock and checks the current outcome state.
319 // If the outcome is still `Outcome::Unknown`, this function returns
320 // the locked outcome for further updates. In any other case it returns
321 // ErrorCode::INVALID_OPERATION_HANDLE indicating that this operation has
322 // been finalized and is no longer active.
323 fn check_active(&self) -> Result<MutexGuard<Outcome>> {
324 let guard = self.outcome.lock().expect("In check_active.");
325 match *guard {
326 Outcome::Unknown => Ok(guard),
327 _ => Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)).context(format!(
328 "In check_active: Call on finalized operation with outcome: {:?}.",
329 *guard
330 )),
331 }
332 }
333
334 // This function checks the amount of input data sent to us. We reject any buffer
335 // exceeding MAX_RECEIVE_DATA bytes as input to `update`, `update_aad`, and `finish`
336 // in order to force clients into using reasonable limits.
337 fn check_input_length(data: &[u8]) -> Result<()> {
338 if data.len() > MAX_RECEIVE_DATA {
339 // This error code is unique, no context required here.
340 return Err(anyhow!(Error::Rc(ResponseCode::TOO_MUCH_DATA)));
341 }
342 Ok(())
343 }
344
345 // Update the last usage to now.
346 fn touch(&self) {
347 // Expect safety:
348 // `last_usage` is locked only for primitive single line statements.
349 // There is no chance to panic and poison the mutex.
350 *self.last_usage.lock().expect("In touch.") = Instant::now();
351 }
352
353 /// Implementation of `IKeystoreOperation::updateAad`.
354 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
355 fn update_aad(&self, aad_input: &[u8]) -> Result<()> {
356 let mut outcome = self.check_active().context("In update_aad")?;
357 Self::check_input_length(aad_input).context("In update_aad")?;
358 self.touch();
359
Stephen Crane221bbb52020-12-16 15:52:10 -0800360 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700361 self.km_op.get_interface().context("In update: Failed to get KeyMintOperation.")?;
362
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800363 let (hat, tst) = self
364 .auth_info
365 .lock()
366 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800367 .before_update()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800368 .context("In update_aad: Trying to get auth tokens.")?;
369
Janis Danisevskis1af91262020-08-10 14:58:08 -0700370 self.update_outcome(
371 &mut *outcome,
Shawn Willden44cc03d2021-02-19 10:53:49 -0700372 map_km_error(km_op.updateAad(aad_input, hat.as_ref(), tst.as_ref())),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700373 )
374 .context("In update_aad: KeyMint::update failed.")?;
375
376 Ok(())
377 }
378
379 /// Implementation of `IKeystoreOperation::update`.
380 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
381 fn update(&self, input: &[u8]) -> Result<Option<Vec<u8>>> {
382 let mut outcome = self.check_active().context("In update")?;
383 Self::check_input_length(input).context("In update")?;
384 self.touch();
385
Stephen Crane221bbb52020-12-16 15:52:10 -0800386 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700387 self.km_op.get_interface().context("In update: Failed to get KeyMintOperation.")?;
388
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800389 let (hat, tst) = self
390 .auth_info
391 .lock()
392 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800393 .before_update()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800394 .context("In update: Trying to get auth tokens.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000395
Shawn Willden44cc03d2021-02-19 10:53:49 -0700396 let output = self
397 .update_outcome(
398 &mut *outcome,
399 map_km_error(km_op.update(input, hat.as_ref(), tst.as_ref())),
400 )
401 .context("In update: KeyMint::update failed.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700402
Shawn Willden44cc03d2021-02-19 10:53:49 -0700403 if output.is_empty() {
404 Ok(None)
405 } else {
406 Ok(Some(output))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700407 }
408 }
409
410 /// Implementation of `IKeystoreOperation::finish`.
411 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
412 fn finish(&self, input: Option<&[u8]>, signature: Option<&[u8]>) -> Result<Option<Vec<u8>>> {
413 let mut outcome = self.check_active().context("In finish")?;
414 if let Some(input) = input {
415 Self::check_input_length(input).context("In finish")?;
416 }
417 self.touch();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700418
Stephen Crane221bbb52020-12-16 15:52:10 -0800419 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700420 self.km_op.get_interface().context("In finish: Failed to get KeyMintOperation.")?;
421
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800422 let (hat, tst, confirmation_token) = self
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800423 .auth_info
424 .lock()
425 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800426 .before_finish()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800427 .context("In finish: Trying to get auth tokens.")?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000428
Janis Danisevskis85d47932020-10-23 16:12:59 -0700429 let output = self
430 .update_outcome(
431 &mut *outcome,
432 map_km_error(km_op.finish(
Janis Danisevskis85d47932020-10-23 16:12:59 -0700433 input,
434 signature,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800435 hat.as_ref(),
436 tst.as_ref(),
Shawn Willden44cc03d2021-02-19 10:53:49 -0700437 confirmation_token.as_deref(),
Janis Danisevskis85d47932020-10-23 16:12:59 -0700438 )),
439 )
440 .context("In finish: KeyMint::finish failed.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700441
Qi Wub9433b52020-12-01 14:52:46 +0800442 self.auth_info.lock().unwrap().after_finish().context("In finish.")?;
443
Janis Danisevskis1af91262020-08-10 14:58:08 -0700444 // At this point the operation concluded successfully.
445 *outcome = Outcome::Success;
446
447 if output.is_empty() {
448 Ok(None)
449 } else {
450 Ok(Some(output))
451 }
452 }
453
454 /// Aborts the operation if it is active. IFF the operation is aborted the outcome is
455 /// set to `outcome`. `outcome` must reflect the reason for the abort. Since the operation
456 /// gets aborted `outcome` must not be `Operation::Success` or `Operation::Unknown`.
457 fn abort(&self, outcome: Outcome) -> Result<()> {
458 let mut locked_outcome = self.check_active().context("In abort")?;
459 *locked_outcome = outcome;
Stephen Crane221bbb52020-12-16 15:52:10 -0800460 let km_op: binder::public_api::Strong<dyn IKeyMintOperation> =
Janis Danisevskis1af91262020-08-10 14:58:08 -0700461 self.km_op.get_interface().context("In abort: Failed to get KeyMintOperation.")?;
462
463 map_km_error(km_op.abort()).context("In abort: KeyMint::abort failed.")
464 }
465}
466
467impl Drop for Operation {
468 fn drop(&mut self) {
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000469 let guard = self.outcome.lock().expect("In drop.");
470 log_key_operation_event_stats(
471 self.logging_info.purpose,
472 &(self.logging_info.op_params),
473 &guard,
474 self.logging_info.key_upgraded,
475 );
476 if let Outcome::Unknown = *guard {
477 drop(guard);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700478 // If the operation was still active we call abort, setting
479 // the outcome to `Outcome::Dropped`
480 if let Err(e) = self.abort(Outcome::Dropped) {
481 log::error!("While dropping Operation: abort failed:\n {:?}", e);
482 }
483 }
484 }
485}
486
487/// The OperationDb holds weak references to all ongoing operations.
488/// Its main purpose is to facilitate operation pruning.
489#[derive(Debug, Default)]
490pub struct OperationDb {
491 // TODO replace Vec with WeakTable when the weak_table crate becomes
492 // available.
493 operations: Mutex<Vec<Weak<Operation>>>,
494}
495
496impl OperationDb {
497 /// Creates a new OperationDb.
498 pub fn new() -> Self {
499 Self { operations: Mutex::new(Vec::new()) }
500 }
501
502 /// Creates a new operation.
503 /// This function takes a KeyMint operation and an associated
504 /// owner uid and returns a new Operation wrapped in a `std::sync::Arc`.
505 pub fn create_operation(
506 &self,
Stephen Crane221bbb52020-12-16 15:52:10 -0800507 km_op: binder::public_api::Strong<dyn IKeyMintOperation>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700508 owner: u32,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800509 auth_info: AuthInfo,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800510 forced: bool,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000511 logging_info: LoggingInfo,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700512 ) -> Arc<Operation> {
513 // We use unwrap because we don't allow code that can panic while locked.
514 let mut operations = self.operations.lock().expect("In create_operation.");
515
516 let mut index: usize = 0;
517 // First we iterate through the operation slots to try and find an unused
518 // slot. If we don't find one, we append the new entry instead.
519 match (*operations).iter_mut().find(|s| {
520 index += 1;
521 s.upgrade().is_none()
522 }) {
523 Some(free_slot) => {
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000524 let new_op = Arc::new(Operation::new(
525 index - 1,
526 km_op,
527 owner,
528 auth_info,
529 forced,
530 logging_info,
531 ));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700532 *free_slot = Arc::downgrade(&new_op);
533 new_op
534 }
535 None => {
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000536 let new_op = Arc::new(Operation::new(
537 operations.len(),
538 km_op,
539 owner,
540 auth_info,
541 forced,
542 logging_info,
543 ));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700544 operations.push(Arc::downgrade(&new_op));
545 new_op
546 }
547 }
548 }
549
550 fn get(&self, index: usize) -> Option<Arc<Operation>> {
551 self.operations.lock().expect("In OperationDb::get.").get(index).and_then(|op| op.upgrade())
552 }
553
554 /// Attempts to prune an operation.
555 ///
556 /// This function is used during operation creation, i.e., by
557 /// `KeystoreSecurityLevel::create_operation`, to try and free up an operation slot
558 /// if it got `ErrorCode::TOO_MANY_OPERATIONS` from the KeyMint backend. It is not
559 /// guaranteed that an operation slot is available after this call successfully
560 /// returned for various reasons. E.g., another thread may have snatched up the newly
561 /// available slot. Callers may have to call prune multiple times before they get a
562 /// free operation slot. Prune may also return `Err(Error::Rc(ResponseCode::BACKEND_BUSY))`
563 /// which indicates that no prunable operation was found.
564 ///
565 /// To find a suitable candidate we compute the malus for the caller and each existing
566 /// operation. The malus is the inverse of the pruning power (caller) or pruning
567 /// resistance (existing operation).
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700568 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700569 /// The malus is based on the number of sibling operations and age. Sibling
570 /// operations are operations that have the same owner (UID).
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700571 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700572 /// Every operation, existing or new, starts with a malus of 1. Every sibling
573 /// increases the malus by one. The age is the time since an operation was last touched.
574 /// It increases the malus by log6(<age in seconds> + 1) rounded down to the next
575 /// integer. So the malus increases stepwise after 5s, 35s, 215s, ...
576 /// Of two operations with the same malus the least recently used one is considered
577 /// weaker.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700578 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700579 /// For the caller to be able to prune an operation it must find an operation
580 /// with a malus higher than its own.
581 ///
582 /// The malus can be expressed as
583 /// ```
584 /// malus = 1 + no_of_siblings + floor(log6(age_in_seconds + 1))
585 /// ```
586 /// where the constant `1` accounts for the operation under consideration.
587 /// In reality we compute it as
588 /// ```
589 /// caller_malus = 1 + running_siblings
590 /// ```
591 /// because the new operation has no age and is not included in the `running_siblings`,
592 /// and
593 /// ```
594 /// running_malus = running_siblings + floor(log6(age_in_seconds + 1))
595 /// ```
596 /// because a running operation is included in the `running_siblings` and it has
597 /// an age.
598 ///
599 /// ## Example
600 /// A caller with no running operations has a malus of 1. Young (age < 5s) operations
601 /// also with no siblings have a malus of one and cannot be pruned by the caller.
602 /// We have to find an operation that has at least one sibling or is older than 5s.
603 ///
604 /// A caller with one running operation has a malus of 2. Now even young siblings
605 /// or single child aging (5s <= age < 35s) operations are off limit. An aging
606 /// sibling of two, however, would have a malus of 3 and would be fair game.
607 ///
608 /// ## Rationale
609 /// Due to the limitation of KeyMint operation slots, we cannot get around pruning or
610 /// a single app could easily DoS KeyMint.
611 /// Keystore 1.0 used to always prune the least recently used operation. This at least
612 /// guaranteed that new operations can always be started. With the increased usage
613 /// of Keystore we saw increased pruning activity which can lead to a livelock
614 /// situation in the worst case.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700615 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700616 /// With the new pruning strategy we want to provide well behaved clients with
617 /// progress assurances while punishing DoS attempts. As a result of this
618 /// strategy we can be in the situation where no operation can be pruned and the
619 /// creation of a new operation fails. This allows single child operations which
620 /// are frequently updated to complete, thereby breaking up livelock situations
621 /// and facilitating system wide progress.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700622 ///
623 /// ## Update
624 /// We also allow callers to cannibalize their own sibling operations if no other
625 /// slot can be found. In this case the least recently used sibling is pruned.
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800626 pub fn prune(&self, caller: u32, forced: bool) -> Result<(), Error> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700627 loop {
628 // Maps the uid of the owner to the number of operations that owner has
629 // (running_siblings). More operations per owner lowers the pruning
630 // resistance of the operations of that owner. Whereas the number of
631 // ongoing operations of the caller lowers the pruning power of the caller.
632 let mut owners: HashMap<u32, u64> = HashMap::new();
633 let mut pruning_info: Vec<PruningInfo> = Vec::new();
634
635 let now = Instant::now();
636 self.operations
637 .lock()
638 .expect("In OperationDb::prune: Trying to lock self.operations.")
639 .iter()
640 .for_each(|op| {
641 if let Some(op) = op.upgrade() {
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700642 if let Some(p_info) = op.get_pruning_info() {
643 let owner = p_info.owner;
644 pruning_info.push(p_info);
645 // Count operations per owner.
646 *owners.entry(owner).or_insert(0) += 1;
647 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700648 }
649 });
650
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800651 // If the operation is forced, the caller has a malus of 0.
652 let caller_malus = if forced { 0 } else { 1u64 + *owners.entry(caller).or_default() };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700653
654 // We iterate through all operations computing the malus and finding
655 // the candidate with the highest malus which must also be higher
656 // than the caller_malus.
657 struct CandidateInfo {
658 index: usize,
659 malus: u64,
660 last_usage: Instant,
661 age: Duration,
662 }
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700663 let mut oldest_caller_op: Option<CandidateInfo> = None;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700664 let candidate = pruning_info.iter().fold(
665 None,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800666 |acc: Option<CandidateInfo>, &PruningInfo { last_usage, owner, index, forced }| {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700667 // Compute the age of the current operation.
668 let age = now
669 .checked_duration_since(last_usage)
670 .unwrap_or_else(|| Duration::new(0, 0));
671
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700672 // Find the least recently used sibling as an alternative pruning candidate.
673 if owner == caller {
674 if let Some(CandidateInfo { age: a, .. }) = oldest_caller_op {
675 if age > a {
676 oldest_caller_op =
677 Some(CandidateInfo { index, malus: 0, last_usage, age });
678 }
679 } else {
680 oldest_caller_op =
681 Some(CandidateInfo { index, malus: 0, last_usage, age });
682 }
683 }
684
Janis Danisevskis1af91262020-08-10 14:58:08 -0700685 // Compute the malus of the current operation.
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800686 let malus = if forced {
687 // Forced operations have a malus of 0. And cannot even be pruned
688 // by other forced operations.
689 0
690 } else {
691 // Expect safety: Every owner in pruning_info was counted in
692 // the owners map. So this unwrap cannot panic.
693 *owners.get(&owner).expect(
694 "This is odd. We should have counted every owner in pruning_info.",
695 ) + ((age.as_secs() + 1) as f64).log(6.0).floor() as u64
696 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700697
698 // Now check if the current operation is a viable/better candidate
699 // the one currently stored in the accumulator.
700 match acc {
701 // First we have to find any operation that is prunable by the caller.
702 None => {
703 if caller_malus < malus {
704 Some(CandidateInfo { index, malus, last_usage, age })
705 } else {
706 None
707 }
708 }
709 // If we have found one we look for the operation with the worst score.
710 // If there is a tie, the older operation is considered weaker.
711 Some(CandidateInfo { index: i, malus: m, last_usage: l, age: a }) => {
712 if malus > m || (malus == m && age > a) {
713 Some(CandidateInfo { index, malus, last_usage, age })
714 } else {
715 Some(CandidateInfo { index: i, malus: m, last_usage: l, age: a })
716 }
717 }
718 }
719 },
720 );
721
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700722 // If we did not find a suitable candidate we may cannibalize our oldest sibling.
723 let candidate = candidate.or(oldest_caller_op);
724
Janis Danisevskis1af91262020-08-10 14:58:08 -0700725 match candidate {
726 Some(CandidateInfo { index, malus: _, last_usage, age: _ }) => {
727 match self.get(index) {
728 Some(op) => {
729 match op.prune(last_usage) {
730 // We successfully freed up a slot.
731 Ok(()) => break Ok(()),
732 // This means the operation we tried to prune was on its way
733 // out. It also means that the slot it had occupied was freed up.
734 Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)) => break Ok(()),
735 // This means the operation we tried to prune was currently
736 // servicing a request. There are two options.
737 // * Assume that it was touched, which means that its
738 // pruning resistance increased. In that case we have
739 // to start over and find another candidate.
740 // * Assume that the operation is transitioning to end-of-life.
741 // which means that we got a free slot for free.
742 // If we assume the first but the second is true, we prune
743 // a good operation without need (aggressive approach).
744 // If we assume the second but the first is true, our
745 // caller will attempt to create a new KeyMint operation,
746 // fail with `ErrorCode::TOO_MANY_OPERATIONS`, and call
747 // us again (conservative approach).
748 Err(Error::Rc(ResponseCode::OPERATION_BUSY)) => {
749 // We choose the conservative approach, because
750 // every needlessly pruned operation can impact
751 // the user experience.
752 // To switch to the aggressive approach replace
753 // the following line with `continue`.
754 break Ok(());
755 }
756
757 // The candidate may have been touched so the score
758 // has changed since our evaluation.
759 _ => continue,
760 }
761 }
762 // This index does not exist any more. The operation
763 // in this slot was dropped. Good news, a slot
764 // has freed up.
765 None => break Ok(()),
766 }
767 }
768 // We did not get a pruning candidate.
769 None => break Err(Error::Rc(ResponseCode::BACKEND_BUSY)),
770 }
771 }
772 }
773}
774
775/// Implementation of IKeystoreOperation.
776pub struct KeystoreOperation {
777 operation: Mutex<Option<Arc<Operation>>>,
778}
779
780impl KeystoreOperation {
781 /// Creates a new operation instance wrapped in a
782 /// BnKeystoreOperation proxy object. It also
Andrew Walbran808e8602021-03-16 13:58:28 +0000783 /// calls `IBinderInternal::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -0700784 /// we need it for checking Keystore permissions.
Stephen Crane221bbb52020-12-16 15:52:10 -0800785 pub fn new_native_binder(
786 operation: Arc<Operation>,
787 ) -> binder::public_api::Strong<dyn IKeystoreOperation> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700788 let result =
789 BnKeystoreOperation::new_binder(Self { operation: Mutex::new(Some(operation)) });
790 result.as_binder().set_requesting_sid(true);
791 result
792 }
793
794 /// Grabs the outer operation mutex and calls `f` on the locked operation.
795 /// The function also deletes the operation if it returns with an error or if
796 /// `delete_op` is true.
797 fn with_locked_operation<T, F>(&self, f: F, delete_op: bool) -> Result<T>
798 where
799 for<'a> F: FnOnce(&'a Operation) -> Result<T>,
800 {
801 let mut delete_op: bool = delete_op;
802 match self.operation.try_lock() {
803 Ok(mut mutex_guard) => {
804 let result = match &*mutex_guard {
805 Some(op) => {
806 let result = f(&*op);
807 // Any error here means we can discard the operation.
808 if result.is_err() {
809 delete_op = true;
810 }
811 result
812 }
813 None => Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE))
814 .context("In KeystoreOperation::with_locked_operation"),
815 };
816
817 if delete_op {
818 // We give up our reference to the Operation, thereby freeing up our
819 // internal resources and ending the wrapped KeyMint operation.
820 // This KeystoreOperation object will still be owned by an SpIBinder
821 // until the client drops its remote reference.
822 *mutex_guard = None;
823 }
824 result
825 }
826 Err(_) => Err(Error::Rc(ResponseCode::OPERATION_BUSY))
827 .context("In KeystoreOperation::with_locked_operation"),
828 }
829 }
830}
831
832impl binder::Interface for KeystoreOperation {}
833
834impl IKeystoreOperation for KeystoreOperation {
835 fn updateAad(&self, aad_input: &[u8]) -> binder::public_api::Result<()> {
836 map_or_log_err(
837 self.with_locked_operation(
838 |op| op.update_aad(aad_input).context("In KeystoreOperation::updateAad"),
839 false,
840 ),
841 Ok,
842 )
843 }
844
845 fn update(&self, input: &[u8]) -> binder::public_api::Result<Option<Vec<u8>>> {
846 map_or_log_err(
847 self.with_locked_operation(
848 |op| op.update(input).context("In KeystoreOperation::update"),
849 false,
850 ),
851 Ok,
852 )
853 }
854 fn finish(
855 &self,
856 input: Option<&[u8]>,
857 signature: Option<&[u8]>,
858 ) -> binder::public_api::Result<Option<Vec<u8>>> {
859 map_or_log_err(
860 self.with_locked_operation(
861 |op| op.finish(input, signature).context("In KeystoreOperation::finish"),
862 true,
863 ),
864 Ok,
865 )
866 }
867
868 fn abort(&self) -> binder::public_api::Result<()> {
Janis Danisevskis778245c2021-03-04 15:40:23 -0800869 map_err_with(
Janis Danisevskis1af91262020-08-10 14:58:08 -0700870 self.with_locked_operation(
871 |op| op.abort(Outcome::Abort).context("In KeystoreOperation::abort"),
872 true,
873 ),
Janis Danisevskis778245c2021-03-04 15:40:23 -0800874 |e| {
875 match e.root_cause().downcast_ref::<Error>() {
876 // Calling abort on expired operations is something very common.
877 // There is no reason to clutter the log with it. It is never the cause
878 // for a true problem.
879 Some(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)) => {}
880 _ => log::error!("{:?}", e),
881 };
882 e
883 },
Janis Danisevskis1af91262020-08-10 14:58:08 -0700884 Ok,
885 )
886 }
887}