blob: 9ae8ccfc6c0d2188df281e77fe93ebd4715c2b3e [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.
Chris Wailes1806f972024-08-19 16:37:40 -070034//!
Janis Danisevskis1af91262020-08-10 14:58:08 -070035//! `Operation` has an `Outcome` member. While the outcome is `Outcome::Unknown`,
36//! the operation is active and in a good state. Any of the above conditions may
37//! change the outcome to one of the defined outcomes Success, Abort, Dropped,
38//! Pruned, or ErrorCode. The latter is chosen in the case of an unexpected error, during
39//! `update` or `finish`. `Success` is chosen iff `finish` completes without error.
40//! Note that all operations get dropped eventually in the sense that they lose
41//! their last reference and get destroyed. At that point, the fate of the operation
42//! gets logged. However, an operation will transition to `Outcome::Dropped` iff
43//! the operation was still active (`Outcome::Unknown`) at that time.
44//!
45//! ## Operation Dropping
46//! To observe the dropping of an operation, we have to make sure that there
47//! are no strong references to the IBinder representing this operation.
48//! This would be simple enough if the operation object would need to be accessed
49//! only by transactions. But to perform pruning, we have to retain a reference to the
50//! original operation object.
51//!
52//! ## Operation Pruning
53//! Pruning an operation happens during the creation of a new operation.
54//! We have to iterate through the operation database to find a suitable
55//! candidate. Then we abort and finalize this operation setting its outcome to
56//! `Outcome::Pruned`. The corresponding KeyMint operation slot will have been freed
57//! up at this point, but the `Operation` object lingers. When the client
58//! attempts to use the operation again they will receive
59//! ErrorCode::INVALID_OPERATION_HANDLE indicating that the operation no longer
60//! exits. This should be the cue for the client to destroy its binder.
61//! At that point the operation gets dropped.
62//!
63//! ## Architecture
64//! The `IKeystoreOperation` trait is implemented by `KeystoreOperation`.
65//! This acts as a proxy object holding a strong reference to actual operation
66//! implementation `Operation`.
67//!
68//! ```
69//! struct KeystoreOperation {
70//! operation: Mutex<Option<Arc<Operation>>>,
71//! }
72//! ```
73//!
74//! The `Mutex` serves two purposes. It provides interior mutability allowing
75//! us to set the Option to None. We do this when the life cycle ends during
76//! a call to `update`, `finish`, or `abort`. As a result most of the Operation
77//! related resources are freed. The `KeystoreOperation` proxy object still
78//! lingers until dropped by the client.
79//! The second purpose is to protect operations against concurrent usage.
80//! Failing to lock this mutex yields `ResponseCode::OPERATION_BUSY` and indicates
81//! a programming error in the client.
82//!
83//! Note that the Mutex only protects the operation against concurrent client calls.
84//! We still retain weak references to the operation in the operation database:
85//!
86//! ```
87//! struct OperationDb {
88//! operations: Mutex<Vec<Weak<Operation>>>
89//! }
90//! ```
91//!
92//! This allows us to access the operations for the purpose of pruning.
93//! We do this in three phases.
94//! 1. We gather the pruning information. Besides non mutable information,
95//! we access `last_usage` which is protected by a mutex.
96//! We only lock this mutex for single statements at a time. During
97//! this phase we hold the operation db lock.
98//! 2. We choose a pruning candidate by computing the pruning resistance
99//! of each operation. We do this entirely with information we now
100//! have on the stack without holding any locks.
101//! (See `OperationDb::prune` for more details on the pruning strategy.)
102//! 3. During pruning we briefly lock the operation database again to get the
103//! the pruning candidate by index. We then attempt to abort the candidate.
104//! If the candidate was touched in the meantime or is currently fulfilling
105//! a request (i.e., the client calls update, finish, or abort),
106//! we go back to 1 and try again.
107//!
108//! So the outer Mutex in `KeystoreOperation::operation` only protects
109//! operations against concurrent client calls but not against concurrent
110//! pruning attempts. This is what the `Operation::outcome` mutex is used for.
111//!
112//! ```
113//! struct Operation {
114//! ...
115//! outcome: Mutex<Outcome>,
116//! ...
117//! }
118//! ```
119//!
120//! Any request that can change the outcome, i.e., `update`, `finish`, `abort`,
121//! `drop`, and `prune` has to take the outcome lock and check if the outcome
122//! is still `Outcome::Unknown` before entering. `prune` is special in that
123//! it will `try_lock`, because we don't want to be blocked on a potentially
124//! long running request at another operation. If it fails to get the lock
125//! the operation is either being touched, which changes its pruning resistance,
126//! or it transitions to its end-of-life, which means we may get a free slot.
127//! Either way, we have to revaluate the pruning scores.
128
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800129use crate::enforcements::AuthInfo;
Tri Vocd6fc7a2023-08-31 11:46:32 -0400130use crate::error::{
David Drysdaledb7ddde2024-06-07 16:22:49 +0100131 error_to_serialized_error, into_binder, into_logged_binder, map_km_error, Error, ErrorCode,
Tri Vocd6fc7a2023-08-31 11:46:32 -0400132 ResponseCode, SerializedError,
133};
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000134use crate::ks_err;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +0000135use crate::metrics_store::log_key_operation_event_stats;
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700136use crate::utils::watchdog as wd;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000137use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000138 IKeyMintOperation::IKeyMintOperation, KeyParameter::KeyParameter, KeyPurpose::KeyPurpose,
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000139 SecurityLevel::SecurityLevel,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000140};
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700141use android_hardware_security_keymint::binder::{BinderFeatures, Strong};
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000142use android_system_keystore2::aidl::android::system::keystore2::{
143 IKeystoreOperation::BnKeystoreOperation, IKeystoreOperation::IKeystoreOperation,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000144};
145use anyhow::{anyhow, Context, Result};
Janis Danisevskis1af91262020-08-10 14:58:08 -0700146use std::{
147 collections::HashMap,
148 sync::{Arc, Mutex, MutexGuard, Weak},
149 time::Duration,
150 time::Instant,
151};
152
Janis Danisevskis1af91262020-08-10 14:58:08 -0700153/// Operations have `Outcome::Unknown` as long as they are active. They transition
154/// to one of the other variants exactly once. The distinction in outcome is mainly
155/// for the statistic.
156#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000157pub enum Outcome {
158 /// Operations have `Outcome::Unknown` as long as they are active.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700159 Unknown,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000160 /// Operation is successful.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700161 Success,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000162 /// Operation is aborted.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700163 Abort,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000164 /// Operation is dropped.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700165 Dropped,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000166 /// Operation is pruned.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700167 Pruned,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000168 /// Operation is failed with the error code.
Tri Vocd6fc7a2023-08-31 11:46:32 -0400169 ErrorCode(SerializedError),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700170}
171
172/// Operation bundles all of the operation related resources and tracks the operation's
173/// outcome.
174#[derive(Debug)]
175pub struct Operation {
176 // The index of this operation in the OperationDb.
177 index: usize,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700178 km_op: Strong<dyn IKeyMintOperation>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700179 last_usage: Mutex<Instant>,
180 outcome: Mutex<Outcome>,
181 owner: u32, // Uid of the operation's owner.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800182 auth_info: Mutex<AuthInfo>,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800183 forced: bool,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000184 logging_info: LoggingInfo,
185}
186
187/// Keeps track of the information required for logging operations.
188#[derive(Debug)]
189pub struct LoggingInfo {
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000190 sec_level: SecurityLevel,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000191 purpose: KeyPurpose,
192 op_params: Vec<KeyParameter>,
193 key_upgraded: bool,
194}
195
196impl LoggingInfo {
197 /// Constructor
198 pub fn new(
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000199 sec_level: SecurityLevel,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000200 purpose: KeyPurpose,
201 op_params: Vec<KeyParameter>,
202 key_upgraded: bool,
203 ) -> LoggingInfo {
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000204 Self { sec_level, purpose, op_params, key_upgraded }
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000205 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700206}
207
208struct PruningInfo {
209 last_usage: Instant,
210 owner: u32,
211 index: usize,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800212 forced: bool,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700213}
214
Janis Danisevskis1af91262020-08-10 14:58:08 -0700215// We don't except more than 32KiB of data in `update`, `updateAad`, and `finish`.
216const MAX_RECEIVE_DATA: usize = 0x8000;
217
218impl Operation {
219 /// Constructor
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000220 pub fn new(
221 index: usize,
Stephen Crane221bbb52020-12-16 15:52:10 -0800222 km_op: binder::Strong<dyn IKeyMintOperation>,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000223 owner: u32,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800224 auth_info: AuthInfo,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800225 forced: bool,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000226 logging_info: LoggingInfo,
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000227 ) -> Self {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700228 Self {
229 index,
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700230 km_op,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700231 last_usage: Mutex::new(Instant::now()),
232 outcome: Mutex::new(Outcome::Unknown),
233 owner,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800234 auth_info: Mutex::new(auth_info),
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800235 forced,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000236 logging_info,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700237 }
238 }
239
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700240 fn get_pruning_info(&self) -> Option<PruningInfo> {
241 // An operation may be finalized.
242 if let Ok(guard) = self.outcome.try_lock() {
243 match *guard {
244 Outcome::Unknown => {}
245 // If the outcome is any other than unknown, it has been finalized,
246 // and we can no longer consider it for pruning.
247 _ => return None,
248 }
249 }
250 // Else: If we could not grab the lock, this means that the operation is currently
251 // being used and it may be transitioning to finalized or it was simply updated.
252 // In any case it is fair game to consider it for pruning. If the operation
253 // transitioned to a final state, we will notice when we attempt to prune, and
254 // a subsequent attempt to create a new operation will succeed.
255 Some(PruningInfo {
256 // Expect safety:
257 // `last_usage` is locked only for primitive single line statements.
258 // There is no chance to panic and poison the mutex.
Janis Danisevskis1af91262020-08-10 14:58:08 -0700259 last_usage: *self.last_usage.lock().expect("In get_pruning_info."),
260 owner: self.owner,
261 index: self.index,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800262 forced: self.forced,
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700263 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700264 }
265
266 fn prune(&self, last_usage: Instant) -> Result<(), Error> {
267 let mut locked_outcome = match self.outcome.try_lock() {
268 Ok(guard) => match *guard {
269 Outcome::Unknown => guard,
270 _ => return Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)),
271 },
272 Err(_) => return Err(Error::Rc(ResponseCode::OPERATION_BUSY)),
273 };
274
275 // In `OperationDb::prune`, which is our caller, we first gather the pruning
276 // information including the last usage. When we select a candidate
277 // we call `prune` on that candidate passing the last_usage
278 // that we gathered earlier. If the actual last usage
279 // has changed since than, it means the operation was busy in the
280 // meantime, which means that we have to reevaluate the pruning score.
281 //
282 // Expect safety:
283 // `last_usage` is locked only for primitive single line statements.
284 // There is no chance to panic and poison the mutex.
285 if *self.last_usage.lock().expect("In Operation::prune()") != last_usage {
286 return Err(Error::Rc(ResponseCode::OPERATION_BUSY));
287 }
288 *locked_outcome = Outcome::Pruned;
289
David Drysdalec652f6c2024-07-18 13:01:23 +0100290 let _wp = wd::watch("Operation::prune: calling IKeyMintOperation::abort()");
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700291
Janis Danisevskis1af91262020-08-10 14:58:08 -0700292 // We abort the operation. If there was an error we log it but ignore it.
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700293 if let Err(e) = map_km_error(self.km_op.abort()) {
Shaquille Johnson89106b82024-02-21 22:58:13 +0000294 log::warn!("In prune: KeyMint::abort failed with {:?}.", e);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700295 }
296
297 Ok(())
298 }
299
300 // This function takes a Result from a KeyMint call and inspects it for errors.
301 // If an error was found it updates the given `locked_outcome` accordingly.
302 // It forwards the Result unmodified.
303 // The precondition to this call must be *locked_outcome == Outcome::Unknown.
304 // Ideally the `locked_outcome` came from a successful call to `check_active`
305 // see below.
306 fn update_outcome<T>(
307 &self,
308 locked_outcome: &mut Outcome,
309 err: Result<T, Error>,
310 ) -> Result<T, Error> {
311 match &err {
Tri Vocd6fc7a2023-08-31 11:46:32 -0400312 Err(e) => *locked_outcome = Outcome::ErrorCode(error_to_serialized_error(e)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700313 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),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000327 _ => Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE))
328 .context(ks_err!("Call on finalized operation with outcome: {:?}.", *guard)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700329 }
330 }
331
332 // This function checks the amount of input data sent to us. We reject any buffer
333 // exceeding MAX_RECEIVE_DATA bytes as input to `update`, `update_aad`, and `finish`
334 // in order to force clients into using reasonable limits.
335 fn check_input_length(data: &[u8]) -> Result<()> {
336 if data.len() > MAX_RECEIVE_DATA {
337 // This error code is unique, no context required here.
338 return Err(anyhow!(Error::Rc(ResponseCode::TOO_MUCH_DATA)));
339 }
340 Ok(())
341 }
342
343 // Update the last usage to now.
344 fn touch(&self) {
345 // Expect safety:
346 // `last_usage` is locked only for primitive single line statements.
347 // There is no chance to panic and poison the mutex.
348 *self.last_usage.lock().expect("In touch.") = Instant::now();
349 }
350
351 /// Implementation of `IKeystoreOperation::updateAad`.
352 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
353 fn update_aad(&self, aad_input: &[u8]) -> Result<()> {
354 let mut outcome = self.check_active().context("In update_aad")?;
355 Self::check_input_length(aad_input).context("In update_aad")?;
356 self.touch();
357
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800358 let (hat, tst) = self
359 .auth_info
360 .lock()
361 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800362 .before_update()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000363 .context(ks_err!("Trying to get auth tokens."))?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800364
Chris Wailesdabb6fe2022-11-16 15:56:19 -0800365 self.update_outcome(&mut outcome, {
David Drysdalec652f6c2024-07-18 13:01:23 +0100366 let _wp = wd::watch("Operation::update_aad: calling IKeyMintOperation::updateAad");
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700367 map_km_error(self.km_op.updateAad(aad_input, hat.as_ref(), tst.as_ref()))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700368 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000369 .context(ks_err!("Update failed."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700370
371 Ok(())
372 }
373
374 /// Implementation of `IKeystoreOperation::update`.
375 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
376 fn update(&self, input: &[u8]) -> Result<Option<Vec<u8>>> {
377 let mut outcome = self.check_active().context("In update")?;
378 Self::check_input_length(input).context("In update")?;
379 self.touch();
380
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800381 let (hat, tst) = self
382 .auth_info
383 .lock()
384 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800385 .before_update()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000386 .context(ks_err!("Trying to get auth tokens."))?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000387
Shawn Willden44cc03d2021-02-19 10:53:49 -0700388 let output = self
Chris Wailesdabb6fe2022-11-16 15:56:19 -0800389 .update_outcome(&mut outcome, {
David Drysdalec652f6c2024-07-18 13:01:23 +0100390 let _wp = wd::watch("Operation::update: calling IKeyMintOperation::update");
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700391 map_km_error(self.km_op.update(input, hat.as_ref(), tst.as_ref()))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700392 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000393 .context(ks_err!("Update failed."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700394
Shawn Willden44cc03d2021-02-19 10:53:49 -0700395 if output.is_empty() {
396 Ok(None)
397 } else {
398 Ok(Some(output))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700399 }
400 }
401
402 /// Implementation of `IKeystoreOperation::finish`.
403 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
404 fn finish(&self, input: Option<&[u8]>, signature: Option<&[u8]>) -> Result<Option<Vec<u8>>> {
405 let mut outcome = self.check_active().context("In finish")?;
406 if let Some(input) = input {
407 Self::check_input_length(input).context("In finish")?;
408 }
409 self.touch();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700410
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800411 let (hat, tst, confirmation_token) = self
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800412 .auth_info
413 .lock()
414 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800415 .before_finish()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000416 .context(ks_err!("Trying to get auth tokens."))?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000417
Janis Danisevskis85d47932020-10-23 16:12:59 -0700418 let output = self
Chris Wailesdabb6fe2022-11-16 15:56:19 -0800419 .update_outcome(&mut outcome, {
David Drysdalec652f6c2024-07-18 13:01:23 +0100420 let _wp = wd::watch("Operation::finish: calling IKeyMintOperation::finish");
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700421 map_km_error(self.km_op.finish(
Janis Danisevskis85d47932020-10-23 16:12:59 -0700422 input,
423 signature,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800424 hat.as_ref(),
425 tst.as_ref(),
Shawn Willden44cc03d2021-02-19 10:53:49 -0700426 confirmation_token.as_deref(),
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700427 ))
428 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000429 .context(ks_err!("Finish failed."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700430
Qi Wub9433b52020-12-01 14:52:46 +0800431 self.auth_info.lock().unwrap().after_finish().context("In finish.")?;
432
Janis Danisevskis1af91262020-08-10 14:58:08 -0700433 // At this point the operation concluded successfully.
434 *outcome = Outcome::Success;
435
436 if output.is_empty() {
437 Ok(None)
438 } else {
439 Ok(Some(output))
440 }
441 }
442
443 /// Aborts the operation if it is active. IFF the operation is aborted the outcome is
444 /// set to `outcome`. `outcome` must reflect the reason for the abort. Since the operation
445 /// gets aborted `outcome` must not be `Operation::Success` or `Operation::Unknown`.
446 fn abort(&self, outcome: Outcome) -> Result<()> {
447 let mut locked_outcome = self.check_active().context("In abort")?;
448 *locked_outcome = outcome;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700449
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700450 {
David Drysdalec652f6c2024-07-18 13:01:23 +0100451 let _wp = wd::watch("Operation::abort: calling IKeyMintOperation::abort");
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000452 map_km_error(self.km_op.abort()).context(ks_err!("KeyMint::abort failed."))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700453 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700454 }
455}
456
457impl Drop for Operation {
458 fn drop(&mut self) {
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000459 let guard = self.outcome.lock().expect("In drop.");
460 log_key_operation_event_stats(
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000461 self.logging_info.sec_level,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000462 self.logging_info.purpose,
463 &(self.logging_info.op_params),
464 &guard,
465 self.logging_info.key_upgraded,
466 );
467 if let Outcome::Unknown = *guard {
468 drop(guard);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700469 // If the operation was still active we call abort, setting
470 // the outcome to `Outcome::Dropped`
471 if let Err(e) = self.abort(Outcome::Dropped) {
472 log::error!("While dropping Operation: abort failed:\n {:?}", e);
473 }
474 }
475 }
476}
477
478/// The OperationDb holds weak references to all ongoing operations.
479/// Its main purpose is to facilitate operation pruning.
480#[derive(Debug, Default)]
481pub struct OperationDb {
482 // TODO replace Vec with WeakTable when the weak_table crate becomes
483 // available.
484 operations: Mutex<Vec<Weak<Operation>>>,
485}
486
487impl OperationDb {
488 /// Creates a new OperationDb.
489 pub fn new() -> Self {
490 Self { operations: Mutex::new(Vec::new()) }
491 }
492
493 /// Creates a new operation.
494 /// This function takes a KeyMint operation and an associated
495 /// owner uid and returns a new Operation wrapped in a `std::sync::Arc`.
496 pub fn create_operation(
497 &self,
Stephen Crane23cf7242022-01-19 17:49:46 +0000498 km_op: binder::Strong<dyn IKeyMintOperation>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700499 owner: u32,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800500 auth_info: AuthInfo,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800501 forced: bool,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000502 logging_info: LoggingInfo,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700503 ) -> Arc<Operation> {
504 // We use unwrap because we don't allow code that can panic while locked.
505 let mut operations = self.operations.lock().expect("In create_operation.");
506
507 let mut index: usize = 0;
508 // First we iterate through the operation slots to try and find an unused
509 // slot. If we don't find one, we append the new entry instead.
510 match (*operations).iter_mut().find(|s| {
511 index += 1;
512 s.upgrade().is_none()
513 }) {
514 Some(free_slot) => {
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000515 let new_op = Arc::new(Operation::new(
516 index - 1,
517 km_op,
518 owner,
519 auth_info,
520 forced,
521 logging_info,
522 ));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700523 *free_slot = Arc::downgrade(&new_op);
524 new_op
525 }
526 None => {
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000527 let new_op = Arc::new(Operation::new(
528 operations.len(),
529 km_op,
530 owner,
531 auth_info,
532 forced,
533 logging_info,
534 ));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700535 operations.push(Arc::downgrade(&new_op));
536 new_op
537 }
538 }
539 }
540
541 fn get(&self, index: usize) -> Option<Arc<Operation>> {
542 self.operations.lock().expect("In OperationDb::get.").get(index).and_then(|op| op.upgrade())
543 }
544
545 /// Attempts to prune an operation.
546 ///
547 /// This function is used during operation creation, i.e., by
548 /// `KeystoreSecurityLevel::create_operation`, to try and free up an operation slot
549 /// if it got `ErrorCode::TOO_MANY_OPERATIONS` from the KeyMint backend. It is not
550 /// guaranteed that an operation slot is available after this call successfully
551 /// returned for various reasons. E.g., another thread may have snatched up the newly
552 /// available slot. Callers may have to call prune multiple times before they get a
553 /// free operation slot. Prune may also return `Err(Error::Rc(ResponseCode::BACKEND_BUSY))`
554 /// which indicates that no prunable operation was found.
555 ///
556 /// To find a suitable candidate we compute the malus for the caller and each existing
557 /// operation. The malus is the inverse of the pruning power (caller) or pruning
558 /// resistance (existing operation).
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700559 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700560 /// The malus is based on the number of sibling operations and age. Sibling
561 /// operations are operations that have the same owner (UID).
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700562 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700563 /// Every operation, existing or new, starts with a malus of 1. Every sibling
564 /// increases the malus by one. The age is the time since an operation was last touched.
565 /// It increases the malus by log6(<age in seconds> + 1) rounded down to the next
566 /// integer. So the malus increases stepwise after 5s, 35s, 215s, ...
567 /// Of two operations with the same malus the least recently used one is considered
568 /// weaker.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700569 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700570 /// For the caller to be able to prune an operation it must find an operation
571 /// with a malus higher than its own.
572 ///
573 /// The malus can be expressed as
574 /// ```
575 /// malus = 1 + no_of_siblings + floor(log6(age_in_seconds + 1))
576 /// ```
577 /// where the constant `1` accounts for the operation under consideration.
578 /// In reality we compute it as
579 /// ```
580 /// caller_malus = 1 + running_siblings
581 /// ```
582 /// because the new operation has no age and is not included in the `running_siblings`,
583 /// and
584 /// ```
585 /// running_malus = running_siblings + floor(log6(age_in_seconds + 1))
586 /// ```
587 /// because a running operation is included in the `running_siblings` and it has
588 /// an age.
589 ///
590 /// ## Example
591 /// A caller with no running operations has a malus of 1. Young (age < 5s) operations
592 /// also with no siblings have a malus of one and cannot be pruned by the caller.
593 /// We have to find an operation that has at least one sibling or is older than 5s.
594 ///
595 /// A caller with one running operation has a malus of 2. Now even young siblings
596 /// or single child aging (5s <= age < 35s) operations are off limit. An aging
597 /// sibling of two, however, would have a malus of 3 and would be fair game.
598 ///
599 /// ## Rationale
600 /// Due to the limitation of KeyMint operation slots, we cannot get around pruning or
601 /// a single app could easily DoS KeyMint.
602 /// Keystore 1.0 used to always prune the least recently used operation. This at least
603 /// guaranteed that new operations can always be started. With the increased usage
604 /// of Keystore we saw increased pruning activity which can lead to a livelock
605 /// situation in the worst case.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700606 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700607 /// With the new pruning strategy we want to provide well behaved clients with
608 /// progress assurances while punishing DoS attempts. As a result of this
609 /// strategy we can be in the situation where no operation can be pruned and the
610 /// creation of a new operation fails. This allows single child operations which
611 /// are frequently updated to complete, thereby breaking up livelock situations
612 /// and facilitating system wide progress.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700613 ///
614 /// ## Update
615 /// We also allow callers to cannibalize their own sibling operations if no other
616 /// slot can be found. In this case the least recently used sibling is pruned.
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800617 pub fn prune(&self, caller: u32, forced: bool) -> Result<(), Error> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700618 loop {
619 // Maps the uid of the owner to the number of operations that owner has
620 // (running_siblings). More operations per owner lowers the pruning
621 // resistance of the operations of that owner. Whereas the number of
622 // ongoing operations of the caller lowers the pruning power of the caller.
623 let mut owners: HashMap<u32, u64> = HashMap::new();
624 let mut pruning_info: Vec<PruningInfo> = Vec::new();
625
626 let now = Instant::now();
627 self.operations
628 .lock()
629 .expect("In OperationDb::prune: Trying to lock self.operations.")
630 .iter()
631 .for_each(|op| {
632 if let Some(op) = op.upgrade() {
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700633 if let Some(p_info) = op.get_pruning_info() {
634 let owner = p_info.owner;
635 pruning_info.push(p_info);
636 // Count operations per owner.
637 *owners.entry(owner).or_insert(0) += 1;
638 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700639 }
640 });
641
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800642 // If the operation is forced, the caller has a malus of 0.
643 let caller_malus = if forced { 0 } else { 1u64 + *owners.entry(caller).or_default() };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700644
645 // We iterate through all operations computing the malus and finding
646 // the candidate with the highest malus which must also be higher
647 // than the caller_malus.
648 struct CandidateInfo {
649 index: usize,
650 malus: u64,
651 last_usage: Instant,
652 age: Duration,
653 }
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700654 let mut oldest_caller_op: Option<CandidateInfo> = None;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700655 let candidate = pruning_info.iter().fold(
656 None,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800657 |acc: Option<CandidateInfo>, &PruningInfo { last_usage, owner, index, forced }| {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700658 // Compute the age of the current operation.
659 let age = now
660 .checked_duration_since(last_usage)
661 .unwrap_or_else(|| Duration::new(0, 0));
662
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700663 // Find the least recently used sibling as an alternative pruning candidate.
664 if owner == caller {
665 if let Some(CandidateInfo { age: a, .. }) = oldest_caller_op {
666 if age > a {
667 oldest_caller_op =
668 Some(CandidateInfo { index, malus: 0, last_usage, age });
669 }
670 } else {
671 oldest_caller_op =
672 Some(CandidateInfo { index, malus: 0, last_usage, age });
673 }
674 }
675
Janis Danisevskis1af91262020-08-10 14:58:08 -0700676 // Compute the malus of the current operation.
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800677 let malus = if forced {
678 // Forced operations have a malus of 0. And cannot even be pruned
679 // by other forced operations.
680 0
681 } else {
682 // Expect safety: Every owner in pruning_info was counted in
683 // the owners map. So this unwrap cannot panic.
684 *owners.get(&owner).expect(
685 "This is odd. We should have counted every owner in pruning_info.",
686 ) + ((age.as_secs() + 1) as f64).log(6.0).floor() as u64
687 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700688
689 // Now check if the current operation is a viable/better candidate
690 // the one currently stored in the accumulator.
691 match acc {
692 // First we have to find any operation that is prunable by the caller.
693 None => {
694 if caller_malus < malus {
695 Some(CandidateInfo { index, malus, last_usage, age })
696 } else {
697 None
698 }
699 }
700 // If we have found one we look for the operation with the worst score.
701 // If there is a tie, the older operation is considered weaker.
702 Some(CandidateInfo { index: i, malus: m, last_usage: l, age: a }) => {
703 if malus > m || (malus == m && age > a) {
704 Some(CandidateInfo { index, malus, last_usage, age })
705 } else {
706 Some(CandidateInfo { index: i, malus: m, last_usage: l, age: a })
707 }
708 }
709 }
710 },
711 );
712
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700713 // If we did not find a suitable candidate we may cannibalize our oldest sibling.
714 let candidate = candidate.or(oldest_caller_op);
715
Janis Danisevskis1af91262020-08-10 14:58:08 -0700716 match candidate {
717 Some(CandidateInfo { index, malus: _, last_usage, age: _ }) => {
718 match self.get(index) {
719 Some(op) => {
720 match op.prune(last_usage) {
721 // We successfully freed up a slot.
722 Ok(()) => break Ok(()),
723 // This means the operation we tried to prune was on its way
724 // out. It also means that the slot it had occupied was freed up.
725 Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)) => break Ok(()),
726 // This means the operation we tried to prune was currently
727 // servicing a request. There are two options.
728 // * Assume that it was touched, which means that its
729 // pruning resistance increased. In that case we have
730 // to start over and find another candidate.
731 // * Assume that the operation is transitioning to end-of-life.
732 // which means that we got a free slot for free.
733 // If we assume the first but the second is true, we prune
734 // a good operation without need (aggressive approach).
735 // If we assume the second but the first is true, our
736 // caller will attempt to create a new KeyMint operation,
737 // fail with `ErrorCode::TOO_MANY_OPERATIONS`, and call
738 // us again (conservative approach).
739 Err(Error::Rc(ResponseCode::OPERATION_BUSY)) => {
740 // We choose the conservative approach, because
741 // every needlessly pruned operation can impact
742 // the user experience.
743 // To switch to the aggressive approach replace
744 // the following line with `continue`.
745 break Ok(());
746 }
747
748 // The candidate may have been touched so the score
749 // has changed since our evaluation.
750 _ => continue,
751 }
752 }
753 // This index does not exist any more. The operation
754 // in this slot was dropped. Good news, a slot
755 // has freed up.
756 None => break Ok(()),
757 }
758 }
759 // We did not get a pruning candidate.
760 None => break Err(Error::Rc(ResponseCode::BACKEND_BUSY)),
761 }
762 }
763 }
764}
765
766/// Implementation of IKeystoreOperation.
767pub struct KeystoreOperation {
768 operation: Mutex<Option<Arc<Operation>>>,
769}
770
771impl KeystoreOperation {
772 /// Creates a new operation instance wrapped in a
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000773 /// BnKeystoreOperation proxy object. It also enables
774 /// `BinderFeatures::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -0700775 /// we need it for checking Keystore permissions.
Stephen Crane23cf7242022-01-19 17:49:46 +0000776 pub fn new_native_binder(operation: Arc<Operation>) -> binder::Strong<dyn IKeystoreOperation> {
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000777 BnKeystoreOperation::new_binder(
778 Self { operation: Mutex::new(Some(operation)) },
779 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
780 )
Janis Danisevskis1af91262020-08-10 14:58:08 -0700781 }
782
783 /// Grabs the outer operation mutex and calls `f` on the locked operation.
784 /// The function also deletes the operation if it returns with an error or if
785 /// `delete_op` is true.
786 fn with_locked_operation<T, F>(&self, f: F, delete_op: bool) -> Result<T>
787 where
788 for<'a> F: FnOnce(&'a Operation) -> Result<T>,
789 {
790 let mut delete_op: bool = delete_op;
791 match self.operation.try_lock() {
792 Ok(mut mutex_guard) => {
793 let result = match &*mutex_guard {
794 Some(op) => {
Chris Wailes263de9f2022-08-11 15:00:51 -0700795 let result = f(op);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700796 // Any error here means we can discard the operation.
797 if result.is_err() {
798 delete_op = true;
799 }
800 result
801 }
802 None => Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000803 .context(ks_err!("KeystoreOperation::with_locked_operation")),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700804 };
805
806 if delete_op {
807 // We give up our reference to the Operation, thereby freeing up our
808 // internal resources and ending the wrapped KeyMint operation.
809 // This KeystoreOperation object will still be owned by an SpIBinder
810 // until the client drops its remote reference.
811 *mutex_guard = None;
812 }
813 result
814 }
815 Err(_) => Err(Error::Rc(ResponseCode::OPERATION_BUSY))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000816 .context(ks_err!("KeystoreOperation::with_locked_operation")),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700817 }
818 }
819}
820
821impl binder::Interface for KeystoreOperation {}
822
823impl IKeystoreOperation for KeystoreOperation {
Stephen Crane23cf7242022-01-19 17:49:46 +0000824 fn updateAad(&self, aad_input: &[u8]) -> binder::Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +0100825 let _wp = wd::watch("IKeystoreOperation::updateAad");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100826 self.with_locked_operation(
David Drysdale5238d772024-06-07 15:12:10 +0100827 |op| op.update_aad(aad_input).context(ks_err!("KeystoreOperation::updateAad")),
828 false,
David Drysdaledb7ddde2024-06-07 16:22:49 +0100829 )
830 .map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700831 }
832
Stephen Crane23cf7242022-01-19 17:49:46 +0000833 fn update(&self, input: &[u8]) -> binder::Result<Option<Vec<u8>>> {
David Drysdale541846b2024-05-23 13:16:07 +0100834 let _wp = wd::watch("IKeystoreOperation::update");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100835 self.with_locked_operation(
David Drysdale5238d772024-06-07 15:12:10 +0100836 |op| op.update(input).context(ks_err!("KeystoreOperation::update")),
837 false,
David Drysdaledb7ddde2024-06-07 16:22:49 +0100838 )
839 .map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700840 }
841 fn finish(
842 &self,
843 input: Option<&[u8]>,
844 signature: Option<&[u8]>,
Stephen Crane23cf7242022-01-19 17:49:46 +0000845 ) -> binder::Result<Option<Vec<u8>>> {
David Drysdale541846b2024-05-23 13:16:07 +0100846 let _wp = wd::watch("IKeystoreOperation::finish");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100847 self.with_locked_operation(
David Drysdale5238d772024-06-07 15:12:10 +0100848 |op| op.finish(input, signature).context(ks_err!("KeystoreOperation::finish")),
849 true,
David Drysdaledb7ddde2024-06-07 16:22:49 +0100850 )
851 .map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700852 }
853
Stephen Crane23cf7242022-01-19 17:49:46 +0000854 fn abort(&self) -> binder::Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +0100855 let _wp = wd::watch("IKeystoreOperation::abort");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100856 let result = self.with_locked_operation(
857 |op| op.abort(Outcome::Abort).context(ks_err!("KeystoreOperation::abort")),
858 true,
859 );
860 result.map_err(|e| {
861 match e.root_cause().downcast_ref::<Error>() {
862 // Calling abort on expired operations is something very common.
863 // There is no reason to clutter the log with it. It is never the cause
864 // for a true problem.
865 Some(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)) => {}
866 _ => log::error!("{:?}", e),
867 };
868 into_binder(e)
869 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700870 }
871}