blob: f306df41292bdefa3b44e3b90340d83163b0376f [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
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000128use crate::auth_token_handler::AuthTokenHandler;
129use crate::error::{map_km_error, map_or_log_err, Error, ErrorCode, ResponseCode};
130use crate::globals::ENFORCEMENTS;
131use crate::key_parameter::KeyParameter;
132use crate::utils::Asp;
133use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
134 ByteArray::ByteArray, HardwareAuthToken::HardwareAuthToken,
135 IKeyMintOperation::IKeyMintOperation, KeyParameter::KeyParameter as KmParam,
136 KeyParameterArray::KeyParameterArray, KeyParameterValue::KeyParameterValue as KmParamValue,
137 Tag::Tag, VerificationToken::VerificationToken,
138};
139use android_system_keystore2::aidl::android::system::keystore2::{
140 IKeystoreOperation::BnKeystoreOperation, IKeystoreOperation::IKeystoreOperation,
141 OperationChallenge::OperationChallenge,
142};
143use anyhow::{anyhow, Context, Result};
144use binder::{IBinder, Interface};
Janis Danisevskis1af91262020-08-10 14:58:08 -0700145use std::{
146 collections::HashMap,
147 sync::{Arc, Mutex, MutexGuard, Weak},
148 time::Duration,
149 time::Instant,
150};
151
Janis Danisevskis1af91262020-08-10 14:58:08 -0700152/// 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)]
156enum Outcome {
157 Unknown,
158 Success,
159 Abort,
160 Dropped,
161 Pruned,
162 ErrorCode(ErrorCode),
163}
164
165/// Operation bundles all of the operation related resources and tracks the operation's
166/// outcome.
167#[derive(Debug)]
168pub struct Operation {
169 // The index of this operation in the OperationDb.
170 index: usize,
171 km_op: Asp,
172 last_usage: Mutex<Instant>,
173 outcome: Mutex<Outcome>,
174 owner: u32, // Uid of the operation's owner.
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000175 auth_token_handler: Mutex<AuthTokenHandler>,
176 // optional because in create_operation, there is a case in which we might not load
177 // key parameters
178 key_params: Option<Vec<KeyParameter>>,
179 op_challenge: Option<OperationChallenge>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700180}
181
182struct PruningInfo {
183 last_usage: Instant,
184 owner: u32,
185 index: usize,
186}
187
Janis Danisevskis1af91262020-08-10 14:58:08 -0700188// We don't except more than 32KiB of data in `update`, `updateAad`, and `finish`.
189const MAX_RECEIVE_DATA: usize = 0x8000;
190
191impl Operation {
192 /// Constructor
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000193 pub fn new(
194 index: usize,
195 km_op: Box<dyn IKeyMintOperation>,
196 owner: u32,
197 auth_token_handler: AuthTokenHandler,
198 key_params: Option<Vec<KeyParameter>>,
199 op_challenge: Option<OperationChallenge>,
200 ) -> Self {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700201 Self {
202 index,
203 km_op: Asp::new(km_op.as_binder()),
204 last_usage: Mutex::new(Instant::now()),
205 outcome: Mutex::new(Outcome::Unknown),
206 owner,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000207 auth_token_handler: Mutex::new(auth_token_handler),
208 key_params,
209 op_challenge,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700210 }
211 }
212
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700213 fn get_pruning_info(&self) -> Option<PruningInfo> {
214 // An operation may be finalized.
215 if let Ok(guard) = self.outcome.try_lock() {
216 match *guard {
217 Outcome::Unknown => {}
218 // If the outcome is any other than unknown, it has been finalized,
219 // and we can no longer consider it for pruning.
220 _ => return None,
221 }
222 }
223 // Else: If we could not grab the lock, this means that the operation is currently
224 // being used and it may be transitioning to finalized or it was simply updated.
225 // In any case it is fair game to consider it for pruning. If the operation
226 // transitioned to a final state, we will notice when we attempt to prune, and
227 // a subsequent attempt to create a new operation will succeed.
228 Some(PruningInfo {
229 // Expect safety:
230 // `last_usage` is locked only for primitive single line statements.
231 // There is no chance to panic and poison the mutex.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700232 last_usage: *self.last_usage.lock().expect("In get_pruning_info."),
233 owner: self.owner,
234 index: self.index,
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700235 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700236 }
237
238 fn prune(&self, last_usage: Instant) -> Result<(), Error> {
239 let mut locked_outcome = match self.outcome.try_lock() {
240 Ok(guard) => match *guard {
241 Outcome::Unknown => guard,
242 _ => return Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)),
243 },
244 Err(_) => return Err(Error::Rc(ResponseCode::OPERATION_BUSY)),
245 };
246
247 // In `OperationDb::prune`, which is our caller, we first gather the pruning
248 // information including the last usage. When we select a candidate
249 // we call `prune` on that candidate passing the last_usage
250 // that we gathered earlier. If the actual last usage
251 // has changed since than, it means the operation was busy in the
252 // meantime, which means that we have to reevaluate the pruning score.
253 //
254 // Expect safety:
255 // `last_usage` is locked only for primitive single line statements.
256 // There is no chance to panic and poison the mutex.
257 if *self.last_usage.lock().expect("In Operation::prune()") != last_usage {
258 return Err(Error::Rc(ResponseCode::OPERATION_BUSY));
259 }
260 *locked_outcome = Outcome::Pruned;
261
262 let km_op: Box<dyn IKeyMintOperation> = match self.km_op.get_interface() {
263 Ok(km_op) => km_op,
264 Err(e) => {
265 log::error!("In prune: Failed to get KeyMintOperation interface.\n {:?}", e);
266 return Err(Error::sys());
267 }
268 };
269
270 // We abort the operation. If there was an error we log it but ignore it.
271 if let Err(e) = map_km_error(km_op.abort()) {
272 log::error!("In prune: KeyMint::abort failed with {:?}.", e);
273 }
274
275 Ok(())
276 }
277
278 // This function takes a Result from a KeyMint call and inspects it for errors.
279 // If an error was found it updates the given `locked_outcome` accordingly.
280 // It forwards the Result unmodified.
281 // The precondition to this call must be *locked_outcome == Outcome::Unknown.
282 // Ideally the `locked_outcome` came from a successful call to `check_active`
283 // see below.
284 fn update_outcome<T>(
285 &self,
286 locked_outcome: &mut Outcome,
287 err: Result<T, Error>,
288 ) -> Result<T, Error> {
289 match &err {
290 Err(Error::Km(e)) => *locked_outcome = Outcome::ErrorCode(*e),
291 Err(_) => *locked_outcome = Outcome::ErrorCode(ErrorCode::UNKNOWN_ERROR),
292 Ok(_) => (),
293 }
294 err
295 }
296
297 // This function grabs the outcome lock and checks the current outcome state.
298 // If the outcome is still `Outcome::Unknown`, this function returns
299 // the locked outcome for further updates. In any other case it returns
300 // ErrorCode::INVALID_OPERATION_HANDLE indicating that this operation has
301 // been finalized and is no longer active.
302 fn check_active(&self) -> Result<MutexGuard<Outcome>> {
303 let guard = self.outcome.lock().expect("In check_active.");
304 match *guard {
305 Outcome::Unknown => Ok(guard),
306 _ => Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)).context(format!(
307 "In check_active: Call on finalized operation with outcome: {:?}.",
308 *guard
309 )),
310 }
311 }
312
313 // This function checks the amount of input data sent to us. We reject any buffer
314 // exceeding MAX_RECEIVE_DATA bytes as input to `update`, `update_aad`, and `finish`
315 // in order to force clients into using reasonable limits.
316 fn check_input_length(data: &[u8]) -> Result<()> {
317 if data.len() > MAX_RECEIVE_DATA {
318 // This error code is unique, no context required here.
319 return Err(anyhow!(Error::Rc(ResponseCode::TOO_MUCH_DATA)));
320 }
321 Ok(())
322 }
323
324 // Update the last usage to now.
325 fn touch(&self) {
326 // Expect safety:
327 // `last_usage` is locked only for primitive single line statements.
328 // There is no chance to panic and poison the mutex.
329 *self.last_usage.lock().expect("In touch.") = Instant::now();
330 }
331
332 /// Implementation of `IKeystoreOperation::updateAad`.
333 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
334 fn update_aad(&self, aad_input: &[u8]) -> Result<()> {
335 let mut outcome = self.check_active().context("In update_aad")?;
336 Self::check_input_length(aad_input).context("In update_aad")?;
337 self.touch();
338
Janis Danisevskis85d47932020-10-23 16:12:59 -0700339 let params = KeyParameterArray {
340 params: vec![KmParam {
341 tag: Tag::ASSOCIATED_DATA,
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800342 value: KmParamValue::Blob(aad_input.into()),
Janis Danisevskis85d47932020-10-23 16:12:59 -0700343 }],
344 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700345
Janis Danisevskis85d47932020-10-23 16:12:59 -0700346 let mut out_params: Option<KeyParameterArray> = None;
347 let mut output: Option<ByteArray> = None;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700348
349 let km_op: Box<dyn IKeyMintOperation> =
350 self.km_op.get_interface().context("In update: Failed to get KeyMintOperation.")?;
351
352 self.update_outcome(
353 &mut *outcome,
354 map_km_error(km_op.update(
Janis Danisevskis85d47932020-10-23 16:12:59 -0700355 Some(&params),
356 None,
357 // TODO Get auth token from enforcement module if required.
358 None,
359 // TODO Get verification token from enforcement module if required.
360 None,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700361 &mut out_params,
362 &mut output,
363 )),
364 )
365 .context("In update_aad: KeyMint::update failed.")?;
366
367 Ok(())
368 }
369
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000370 /// Based on the authorization information stored in the operation during create_operation(),
371 /// and any previous calls to update(), this function returns appropriate auth token and
372 /// verification token to be passed to keymint.
373 /// Note that the call to the global enforcement object happens only during the first call to
374 /// update or if finish() is called right after create_opertation.
375 fn handle_authorization<'a>(
376 auth_token_handler: &'a mut AuthTokenHandler,
377 key_params: Option<&Vec<KeyParameter>>,
378 op_challenge: Option<&OperationChallenge>,
379 ) -> Result<(Option<&'a HardwareAuthToken>, Option<&'a VerificationToken>)> {
380 // keystore performs authorization only if key parameters have been loaded during
381 // create_operation()
382 if let Some(key_parameters) = key_params {
383 match *auth_token_handler {
384 // this variant is found only in a first call to update or if finish is called
385 // right after create_operation.
386 AuthTokenHandler::OpAuthRequired => {
387 *auth_token_handler = ENFORCEMENTS
388 .authorize_update_or_finish(key_parameters.as_slice(), op_challenge)
389 .context("In handle_authorization.")?;
390 Ok((auth_token_handler.get_auth_token(), None))
391 }
392 // this variant is found only in a first call to update or if finish is called
393 // right after create_operation.
394 AuthTokenHandler::Channel(_)|
395 // this variant is found in every subsequent call to update/finish,
396 // unless the authorization is not required for the key
397 AuthTokenHandler::Token(_, _) => {
398 auth_token_handler.retrieve_auth_and_verification_tokens()
399 }
400 _ => Ok((None, None))
401 }
402 } else {
403 Ok((None, None))
404 }
405 }
406
Janis Danisevskis1af91262020-08-10 14:58:08 -0700407 /// Implementation of `IKeystoreOperation::update`.
408 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
409 fn update(&self, input: &[u8]) -> Result<Option<Vec<u8>>> {
410 let mut outcome = self.check_active().context("In update")?;
411 Self::check_input_length(input).context("In update")?;
412 self.touch();
413
Janis Danisevskis85d47932020-10-23 16:12:59 -0700414 let mut out_params: Option<KeyParameterArray> = None;
415 let mut output: Option<ByteArray> = None;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700416
417 let km_op: Box<dyn IKeyMintOperation> =
418 self.km_op.get_interface().context("In update: Failed to get KeyMintOperation.")?;
419
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000420 let mut auth_handler = self.auth_token_handler.lock().unwrap();
421 let (auth_token_for_km, verification_token_for_km) = Self::handle_authorization(
422 &mut auth_handler,
423 self.key_params.as_ref(),
424 self.op_challenge.as_ref(),
425 )
426 .context("In update.")?;
427
Janis Danisevskis1af91262020-08-10 14:58:08 -0700428 self.update_outcome(
429 &mut *outcome,
430 map_km_error(km_op.update(
Janis Danisevskis85d47932020-10-23 16:12:59 -0700431 None,
432 Some(input),
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000433 auth_token_for_km,
434 verification_token_for_km,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700435 &mut out_params,
436 &mut output,
437 )),
438 )
439 .context("In update: KeyMint::update failed.")?;
440
Janis Danisevskis85d47932020-10-23 16:12:59 -0700441 match output {
Janis Danisevskis3cfd4a42020-11-23 13:42:38 -0800442 Some(blob) => {
443 if blob.data.is_empty() {
444 Ok(None)
445 } else {
446 Ok(Some(blob.data))
447 }
448 }
Janis Danisevskis85d47932020-10-23 16:12:59 -0700449 None => Ok(None),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700450 }
451 }
452
453 /// Implementation of `IKeystoreOperation::finish`.
454 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
455 fn finish(&self, input: Option<&[u8]>, signature: Option<&[u8]>) -> Result<Option<Vec<u8>>> {
456 let mut outcome = self.check_active().context("In finish")?;
457 if let Some(input) = input {
458 Self::check_input_length(input).context("In finish")?;
459 }
460 self.touch();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700461
Janis Danisevskis85d47932020-10-23 16:12:59 -0700462 let mut out_params: Option<KeyParameterArray> = None;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700463
464 let km_op: Box<dyn IKeyMintOperation> =
465 self.km_op.get_interface().context("In finish: Failed to get KeyMintOperation.")?;
466
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000467 let mut auth_handler = self.auth_token_handler.lock().unwrap();
468 let (auth_token_for_km, verification_token_for_km) = Self::handle_authorization(
469 &mut auth_handler,
470 self.key_params.as_ref(),
471 self.op_challenge.as_ref(),
472 )
473 .context("In finish.")?;
474
Janis Danisevskis85d47932020-10-23 16:12:59 -0700475 let output = self
476 .update_outcome(
477 &mut *outcome,
478 map_km_error(km_op.finish(
479 None,
480 input,
481 signature,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000482 auth_token_for_km,
483 verification_token_for_km,
Janis Danisevskis85d47932020-10-23 16:12:59 -0700484 &mut out_params,
485 )),
486 )
487 .context("In finish: KeyMint::finish failed.")?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700488
489 // At this point the operation concluded successfully.
490 *outcome = Outcome::Success;
491
492 if output.is_empty() {
493 Ok(None)
494 } else {
495 Ok(Some(output))
496 }
497 }
498
499 /// Aborts the operation if it is active. IFF the operation is aborted the outcome is
500 /// set to `outcome`. `outcome` must reflect the reason for the abort. Since the operation
501 /// gets aborted `outcome` must not be `Operation::Success` or `Operation::Unknown`.
502 fn abort(&self, outcome: Outcome) -> Result<()> {
503 let mut locked_outcome = self.check_active().context("In abort")?;
504 *locked_outcome = outcome;
505 let km_op: Box<dyn IKeyMintOperation> =
506 self.km_op.get_interface().context("In abort: Failed to get KeyMintOperation.")?;
507
508 map_km_error(km_op.abort()).context("In abort: KeyMint::abort failed.")
509 }
510}
511
512impl Drop for Operation {
513 fn drop(&mut self) {
514 if let Ok(Outcome::Unknown) = self.outcome.get_mut() {
515 // If the operation was still active we call abort, setting
516 // the outcome to `Outcome::Dropped`
517 if let Err(e) = self.abort(Outcome::Dropped) {
518 log::error!("While dropping Operation: abort failed:\n {:?}", e);
519 }
520 }
521 }
522}
523
524/// The OperationDb holds weak references to all ongoing operations.
525/// Its main purpose is to facilitate operation pruning.
526#[derive(Debug, Default)]
527pub struct OperationDb {
528 // TODO replace Vec with WeakTable when the weak_table crate becomes
529 // available.
530 operations: Mutex<Vec<Weak<Operation>>>,
531}
532
533impl OperationDb {
534 /// Creates a new OperationDb.
535 pub fn new() -> Self {
536 Self { operations: Mutex::new(Vec::new()) }
537 }
538
539 /// Creates a new operation.
540 /// This function takes a KeyMint operation and an associated
541 /// owner uid and returns a new Operation wrapped in a `std::sync::Arc`.
542 pub fn create_operation(
543 &self,
544 km_op: Box<dyn IKeyMintOperation>,
545 owner: u32,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000546 auth_token_handler: AuthTokenHandler,
547 key_params: Option<Vec<KeyParameter>>,
548 op_challenge: Option<OperationChallenge>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700549 ) -> Arc<Operation> {
550 // We use unwrap because we don't allow code that can panic while locked.
551 let mut operations = self.operations.lock().expect("In create_operation.");
552
553 let mut index: usize = 0;
554 // First we iterate through the operation slots to try and find an unused
555 // slot. If we don't find one, we append the new entry instead.
556 match (*operations).iter_mut().find(|s| {
557 index += 1;
558 s.upgrade().is_none()
559 }) {
560 Some(free_slot) => {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000561 let new_op = Arc::new(Operation::new(
562 index - 1,
563 km_op,
564 owner,
565 auth_token_handler,
566 key_params,
567 op_challenge,
568 ));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700569 *free_slot = Arc::downgrade(&new_op);
570 new_op
571 }
572 None => {
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000573 let new_op = Arc::new(Operation::new(
574 operations.len(),
575 km_op,
576 owner,
577 auth_token_handler,
578 key_params,
579 op_challenge,
580 ));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700581 operations.push(Arc::downgrade(&new_op));
582 new_op
583 }
584 }
585 }
586
587 fn get(&self, index: usize) -> Option<Arc<Operation>> {
588 self.operations.lock().expect("In OperationDb::get.").get(index).and_then(|op| op.upgrade())
589 }
590
591 /// Attempts to prune an operation.
592 ///
593 /// This function is used during operation creation, i.e., by
594 /// `KeystoreSecurityLevel::create_operation`, to try and free up an operation slot
595 /// if it got `ErrorCode::TOO_MANY_OPERATIONS` from the KeyMint backend. It is not
596 /// guaranteed that an operation slot is available after this call successfully
597 /// returned for various reasons. E.g., another thread may have snatched up the newly
598 /// available slot. Callers may have to call prune multiple times before they get a
599 /// free operation slot. Prune may also return `Err(Error::Rc(ResponseCode::BACKEND_BUSY))`
600 /// which indicates that no prunable operation was found.
601 ///
602 /// To find a suitable candidate we compute the malus for the caller and each existing
603 /// operation. The malus is the inverse of the pruning power (caller) or pruning
604 /// resistance (existing operation).
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700605 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700606 /// The malus is based on the number of sibling operations and age. Sibling
607 /// operations are operations that have the same owner (UID).
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700608 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700609 /// Every operation, existing or new, starts with a malus of 1. Every sibling
610 /// increases the malus by one. The age is the time since an operation was last touched.
611 /// It increases the malus by log6(<age in seconds> + 1) rounded down to the next
612 /// integer. So the malus increases stepwise after 5s, 35s, 215s, ...
613 /// Of two operations with the same malus the least recently used one is considered
614 /// weaker.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700615 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700616 /// For the caller to be able to prune an operation it must find an operation
617 /// with a malus higher than its own.
618 ///
619 /// The malus can be expressed as
620 /// ```
621 /// malus = 1 + no_of_siblings + floor(log6(age_in_seconds + 1))
622 /// ```
623 /// where the constant `1` accounts for the operation under consideration.
624 /// In reality we compute it as
625 /// ```
626 /// caller_malus = 1 + running_siblings
627 /// ```
628 /// because the new operation has no age and is not included in the `running_siblings`,
629 /// and
630 /// ```
631 /// running_malus = running_siblings + floor(log6(age_in_seconds + 1))
632 /// ```
633 /// because a running operation is included in the `running_siblings` and it has
634 /// an age.
635 ///
636 /// ## Example
637 /// A caller with no running operations has a malus of 1. Young (age < 5s) operations
638 /// also with no siblings have a malus of one and cannot be pruned by the caller.
639 /// We have to find an operation that has at least one sibling or is older than 5s.
640 ///
641 /// A caller with one running operation has a malus of 2. Now even young siblings
642 /// or single child aging (5s <= age < 35s) operations are off limit. An aging
643 /// sibling of two, however, would have a malus of 3 and would be fair game.
644 ///
645 /// ## Rationale
646 /// Due to the limitation of KeyMint operation slots, we cannot get around pruning or
647 /// a single app could easily DoS KeyMint.
648 /// Keystore 1.0 used to always prune the least recently used operation. This at least
649 /// guaranteed that new operations can always be started. With the increased usage
650 /// of Keystore we saw increased pruning activity which can lead to a livelock
651 /// situation in the worst case.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700652 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700653 /// With the new pruning strategy we want to provide well behaved clients with
654 /// progress assurances while punishing DoS attempts. As a result of this
655 /// strategy we can be in the situation where no operation can be pruned and the
656 /// creation of a new operation fails. This allows single child operations which
657 /// are frequently updated to complete, thereby breaking up livelock situations
658 /// and facilitating system wide progress.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700659 ///
660 /// ## Update
661 /// We also allow callers to cannibalize their own sibling operations if no other
662 /// slot can be found. In this case the least recently used sibling is pruned.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700663 pub fn prune(&self, caller: u32) -> Result<(), Error> {
664 loop {
665 // Maps the uid of the owner to the number of operations that owner has
666 // (running_siblings). More operations per owner lowers the pruning
667 // resistance of the operations of that owner. Whereas the number of
668 // ongoing operations of the caller lowers the pruning power of the caller.
669 let mut owners: HashMap<u32, u64> = HashMap::new();
670 let mut pruning_info: Vec<PruningInfo> = Vec::new();
671
672 let now = Instant::now();
673 self.operations
674 .lock()
675 .expect("In OperationDb::prune: Trying to lock self.operations.")
676 .iter()
677 .for_each(|op| {
678 if let Some(op) = op.upgrade() {
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700679 if let Some(p_info) = op.get_pruning_info() {
680 let owner = p_info.owner;
681 pruning_info.push(p_info);
682 // Count operations per owner.
683 *owners.entry(owner).or_insert(0) += 1;
684 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700685 }
686 });
687
688 let caller_malus = 1u64 + *owners.entry(caller).or_default();
689
690 // We iterate through all operations computing the malus and finding
691 // the candidate with the highest malus which must also be higher
692 // than the caller_malus.
693 struct CandidateInfo {
694 index: usize,
695 malus: u64,
696 last_usage: Instant,
697 age: Duration,
698 }
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700699 let mut oldest_caller_op: Option<CandidateInfo> = None;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700700 let candidate = pruning_info.iter().fold(
701 None,
702 |acc: Option<CandidateInfo>, &PruningInfo { last_usage, owner, index }| {
703 // Compute the age of the current operation.
704 let age = now
705 .checked_duration_since(last_usage)
706 .unwrap_or_else(|| Duration::new(0, 0));
707
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700708 // Find the least recently used sibling as an alternative pruning candidate.
709 if owner == caller {
710 if let Some(CandidateInfo { age: a, .. }) = oldest_caller_op {
711 if age > a {
712 oldest_caller_op =
713 Some(CandidateInfo { index, malus: 0, last_usage, age });
714 }
715 } else {
716 oldest_caller_op =
717 Some(CandidateInfo { index, malus: 0, last_usage, age });
718 }
719 }
720
Janis Danisevskis1af91262020-08-10 14:58:08 -0700721 // Compute the malus of the current operation.
722 // Expect safety: Every owner in pruning_info was counted in
723 // the owners map. So this unwrap cannot panic.
724 let malus = *owners
725 .get(&owner)
726 .expect("This is odd. We should have counted every owner in pruning_info.")
727 + ((age.as_secs() + 1) as f64).log(6.0).floor() as u64;
728
729 // Now check if the current operation is a viable/better candidate
730 // the one currently stored in the accumulator.
731 match acc {
732 // First we have to find any operation that is prunable by the caller.
733 None => {
734 if caller_malus < malus {
735 Some(CandidateInfo { index, malus, last_usage, age })
736 } else {
737 None
738 }
739 }
740 // If we have found one we look for the operation with the worst score.
741 // If there is a tie, the older operation is considered weaker.
742 Some(CandidateInfo { index: i, malus: m, last_usage: l, age: a }) => {
743 if malus > m || (malus == m && age > a) {
744 Some(CandidateInfo { index, malus, last_usage, age })
745 } else {
746 Some(CandidateInfo { index: i, malus: m, last_usage: l, age: a })
747 }
748 }
749 }
750 },
751 );
752
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700753 // If we did not find a suitable candidate we may cannibalize our oldest sibling.
754 let candidate = candidate.or(oldest_caller_op);
755
Janis Danisevskis1af91262020-08-10 14:58:08 -0700756 match candidate {
757 Some(CandidateInfo { index, malus: _, last_usage, age: _ }) => {
758 match self.get(index) {
759 Some(op) => {
760 match op.prune(last_usage) {
761 // We successfully freed up a slot.
762 Ok(()) => break Ok(()),
763 // This means the operation we tried to prune was on its way
764 // out. It also means that the slot it had occupied was freed up.
765 Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)) => break Ok(()),
766 // This means the operation we tried to prune was currently
767 // servicing a request. There are two options.
768 // * Assume that it was touched, which means that its
769 // pruning resistance increased. In that case we have
770 // to start over and find another candidate.
771 // * Assume that the operation is transitioning to end-of-life.
772 // which means that we got a free slot for free.
773 // If we assume the first but the second is true, we prune
774 // a good operation without need (aggressive approach).
775 // If we assume the second but the first is true, our
776 // caller will attempt to create a new KeyMint operation,
777 // fail with `ErrorCode::TOO_MANY_OPERATIONS`, and call
778 // us again (conservative approach).
779 Err(Error::Rc(ResponseCode::OPERATION_BUSY)) => {
780 // We choose the conservative approach, because
781 // every needlessly pruned operation can impact
782 // the user experience.
783 // To switch to the aggressive approach replace
784 // the following line with `continue`.
785 break Ok(());
786 }
787
788 // The candidate may have been touched so the score
789 // has changed since our evaluation.
790 _ => continue,
791 }
792 }
793 // This index does not exist any more. The operation
794 // in this slot was dropped. Good news, a slot
795 // has freed up.
796 None => break Ok(()),
797 }
798 }
799 // We did not get a pruning candidate.
800 None => break Err(Error::Rc(ResponseCode::BACKEND_BUSY)),
801 }
802 }
803 }
804}
805
806/// Implementation of IKeystoreOperation.
807pub struct KeystoreOperation {
808 operation: Mutex<Option<Arc<Operation>>>,
809}
810
811impl KeystoreOperation {
812 /// Creates a new operation instance wrapped in a
813 /// BnKeystoreOperation proxy object. It also
814 /// calls `IBinder::set_requesting_sid` on the new interface, because
815 /// we need it for checking Keystore permissions.
816 pub fn new_native_binder(operation: Arc<Operation>) -> impl IKeystoreOperation + Send {
817 let result =
818 BnKeystoreOperation::new_binder(Self { operation: Mutex::new(Some(operation)) });
819 result.as_binder().set_requesting_sid(true);
820 result
821 }
822
823 /// Grabs the outer operation mutex and calls `f` on the locked operation.
824 /// The function also deletes the operation if it returns with an error or if
825 /// `delete_op` is true.
826 fn with_locked_operation<T, F>(&self, f: F, delete_op: bool) -> Result<T>
827 where
828 for<'a> F: FnOnce(&'a Operation) -> Result<T>,
829 {
830 let mut delete_op: bool = delete_op;
831 match self.operation.try_lock() {
832 Ok(mut mutex_guard) => {
833 let result = match &*mutex_guard {
834 Some(op) => {
835 let result = f(&*op);
836 // Any error here means we can discard the operation.
837 if result.is_err() {
838 delete_op = true;
839 }
840 result
841 }
842 None => Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE))
843 .context("In KeystoreOperation::with_locked_operation"),
844 };
845
846 if delete_op {
847 // We give up our reference to the Operation, thereby freeing up our
848 // internal resources and ending the wrapped KeyMint operation.
849 // This KeystoreOperation object will still be owned by an SpIBinder
850 // until the client drops its remote reference.
851 *mutex_guard = None;
852 }
853 result
854 }
855 Err(_) => Err(Error::Rc(ResponseCode::OPERATION_BUSY))
856 .context("In KeystoreOperation::with_locked_operation"),
857 }
858 }
859}
860
861impl binder::Interface for KeystoreOperation {}
862
863impl IKeystoreOperation for KeystoreOperation {
864 fn updateAad(&self, aad_input: &[u8]) -> binder::public_api::Result<()> {
865 map_or_log_err(
866 self.with_locked_operation(
867 |op| op.update_aad(aad_input).context("In KeystoreOperation::updateAad"),
868 false,
869 ),
870 Ok,
871 )
872 }
873
874 fn update(&self, input: &[u8]) -> binder::public_api::Result<Option<Vec<u8>>> {
875 map_or_log_err(
876 self.with_locked_operation(
877 |op| op.update(input).context("In KeystoreOperation::update"),
878 false,
879 ),
880 Ok,
881 )
882 }
883 fn finish(
884 &self,
885 input: Option<&[u8]>,
886 signature: Option<&[u8]>,
887 ) -> binder::public_api::Result<Option<Vec<u8>>> {
888 map_or_log_err(
889 self.with_locked_operation(
890 |op| op.finish(input, signature).context("In KeystoreOperation::finish"),
891 true,
892 ),
893 Ok,
894 )
895 }
896
897 fn abort(&self) -> binder::public_api::Result<()> {
898 map_or_log_err(
899 self.with_locked_operation(
900 |op| op.abort(Outcome::Abort).context("In KeystoreOperation::abort"),
901 true,
902 ),
903 Ok,
904 )
905 }
906}