blob: c11c1f43a6dbbcabfe166bc1973417f694480e4b [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> {
Chris Wailese5f30872024-12-02 11:11:31 -0800311 if let Err(e) = &err {
312 *locked_outcome = Outcome::ErrorCode(error_to_serialized_error(e))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700313 }
314 err
315 }
316
317 // This function grabs the outcome lock and checks the current outcome state.
318 // If the outcome is still `Outcome::Unknown`, this function returns
319 // the locked outcome for further updates. In any other case it returns
320 // ErrorCode::INVALID_OPERATION_HANDLE indicating that this operation has
321 // been finalized and is no longer active.
322 fn check_active(&self) -> Result<MutexGuard<Outcome>> {
323 let guard = self.outcome.lock().expect("In check_active.");
324 match *guard {
325 Outcome::Unknown => Ok(guard),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000326 _ => Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE))
327 .context(ks_err!("Call on finalized operation with outcome: {:?}.", *guard)),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700328 }
329 }
330
331 // This function checks the amount of input data sent to us. We reject any buffer
332 // exceeding MAX_RECEIVE_DATA bytes as input to `update`, `update_aad`, and `finish`
333 // in order to force clients into using reasonable limits.
334 fn check_input_length(data: &[u8]) -> Result<()> {
335 if data.len() > MAX_RECEIVE_DATA {
336 // This error code is unique, no context required here.
337 return Err(anyhow!(Error::Rc(ResponseCode::TOO_MUCH_DATA)));
338 }
339 Ok(())
340 }
341
342 // Update the last usage to now.
343 fn touch(&self) {
344 // Expect safety:
345 // `last_usage` is locked only for primitive single line statements.
346 // There is no chance to panic and poison the mutex.
347 *self.last_usage.lock().expect("In touch.") = Instant::now();
348 }
349
350 /// Implementation of `IKeystoreOperation::updateAad`.
351 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
352 fn update_aad(&self, aad_input: &[u8]) -> Result<()> {
353 let mut outcome = self.check_active().context("In update_aad")?;
354 Self::check_input_length(aad_input).context("In update_aad")?;
355 self.touch();
356
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800357 let (hat, tst) = self
358 .auth_info
359 .lock()
360 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800361 .before_update()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000362 .context(ks_err!("Trying to get auth tokens."))?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800363
Chris Wailesdabb6fe2022-11-16 15:56:19 -0800364 self.update_outcome(&mut outcome, {
David Drysdalec652f6c2024-07-18 13:01:23 +0100365 let _wp = wd::watch("Operation::update_aad: calling IKeyMintOperation::updateAad");
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700366 map_km_error(self.km_op.updateAad(aad_input, hat.as_ref(), tst.as_ref()))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700367 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000368 .context(ks_err!("Update failed."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700369
370 Ok(())
371 }
372
373 /// Implementation of `IKeystoreOperation::update`.
374 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
375 fn update(&self, input: &[u8]) -> Result<Option<Vec<u8>>> {
376 let mut outcome = self.check_active().context("In update")?;
377 Self::check_input_length(input).context("In update")?;
378 self.touch();
379
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800380 let (hat, tst) = self
381 .auth_info
382 .lock()
383 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800384 .before_update()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000385 .context(ks_err!("Trying to get auth tokens."))?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000386
Shawn Willden44cc03d2021-02-19 10:53:49 -0700387 let output = self
Chris Wailesdabb6fe2022-11-16 15:56:19 -0800388 .update_outcome(&mut outcome, {
David Drysdalec652f6c2024-07-18 13:01:23 +0100389 let _wp = wd::watch("Operation::update: calling IKeyMintOperation::update");
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700390 map_km_error(self.km_op.update(input, hat.as_ref(), tst.as_ref()))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700391 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000392 .context(ks_err!("Update failed."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700393
Shawn Willden44cc03d2021-02-19 10:53:49 -0700394 if output.is_empty() {
395 Ok(None)
396 } else {
397 Ok(Some(output))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700398 }
399 }
400
401 /// Implementation of `IKeystoreOperation::finish`.
402 /// Refer to the AIDL spec at system/hardware/interfaces/keystore2 for details.
403 fn finish(&self, input: Option<&[u8]>, signature: Option<&[u8]>) -> Result<Option<Vec<u8>>> {
404 let mut outcome = self.check_active().context("In finish")?;
405 if let Some(input) = input {
406 Self::check_input_length(input).context("In finish")?;
407 }
408 self.touch();
Janis Danisevskis1af91262020-08-10 14:58:08 -0700409
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800410 let (hat, tst, confirmation_token) = self
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800411 .auth_info
412 .lock()
413 .unwrap()
Qi Wub9433b52020-12-01 14:52:46 +0800414 .before_finish()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000415 .context(ks_err!("Trying to get auth tokens."))?;
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000416
Janis Danisevskis85d47932020-10-23 16:12:59 -0700417 let output = self
Chris Wailesdabb6fe2022-11-16 15:56:19 -0800418 .update_outcome(&mut outcome, {
David Drysdalec652f6c2024-07-18 13:01:23 +0100419 let _wp = wd::watch("Operation::finish: calling IKeyMintOperation::finish");
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700420 map_km_error(self.km_op.finish(
Janis Danisevskis85d47932020-10-23 16:12:59 -0700421 input,
422 signature,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800423 hat.as_ref(),
424 tst.as_ref(),
Shawn Willden44cc03d2021-02-19 10:53:49 -0700425 confirmation_token.as_deref(),
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700426 ))
427 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000428 .context(ks_err!("Finish failed."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700429
Qi Wub9433b52020-12-01 14:52:46 +0800430 self.auth_info.lock().unwrap().after_finish().context("In finish.")?;
431
Janis Danisevskis1af91262020-08-10 14:58:08 -0700432 // At this point the operation concluded successfully.
433 *outcome = Outcome::Success;
434
435 if output.is_empty() {
436 Ok(None)
437 } else {
438 Ok(Some(output))
439 }
440 }
441
442 /// Aborts the operation if it is active. IFF the operation is aborted the outcome is
443 /// set to `outcome`. `outcome` must reflect the reason for the abort. Since the operation
444 /// gets aborted `outcome` must not be `Operation::Success` or `Operation::Unknown`.
445 fn abort(&self, outcome: Outcome) -> Result<()> {
446 let mut locked_outcome = self.check_active().context("In abort")?;
447 *locked_outcome = outcome;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700448
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700449 {
David Drysdalec652f6c2024-07-18 13:01:23 +0100450 let _wp = wd::watch("Operation::abort: calling IKeyMintOperation::abort");
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000451 map_km_error(self.km_op.abort()).context(ks_err!("KeyMint::abort failed."))
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700452 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700453 }
454}
455
456impl Drop for Operation {
457 fn drop(&mut self) {
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000458 let guard = self.outcome.lock().expect("In drop.");
459 log_key_operation_event_stats(
Hasini Gunasinghe9617fd92021-04-01 22:27:07 +0000460 self.logging_info.sec_level,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000461 self.logging_info.purpose,
462 &(self.logging_info.op_params),
463 &guard,
464 self.logging_info.key_upgraded,
465 );
466 if let Outcome::Unknown = *guard {
467 drop(guard);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700468 // If the operation was still active we call abort, setting
469 // the outcome to `Outcome::Dropped`
470 if let Err(e) = self.abort(Outcome::Dropped) {
471 log::error!("While dropping Operation: abort failed:\n {:?}", e);
472 }
473 }
474 }
475}
476
477/// The OperationDb holds weak references to all ongoing operations.
478/// Its main purpose is to facilitate operation pruning.
479#[derive(Debug, Default)]
480pub struct OperationDb {
481 // TODO replace Vec with WeakTable when the weak_table crate becomes
482 // available.
483 operations: Mutex<Vec<Weak<Operation>>>,
484}
485
486impl OperationDb {
487 /// Creates a new OperationDb.
488 pub fn new() -> Self {
489 Self { operations: Mutex::new(Vec::new()) }
490 }
491
492 /// Creates a new operation.
493 /// This function takes a KeyMint operation and an associated
494 /// owner uid and returns a new Operation wrapped in a `std::sync::Arc`.
495 pub fn create_operation(
496 &self,
Stephen Crane23cf7242022-01-19 17:49:46 +0000497 km_op: binder::Strong<dyn IKeyMintOperation>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700498 owner: u32,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800499 auth_info: AuthInfo,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800500 forced: bool,
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000501 logging_info: LoggingInfo,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700502 ) -> Arc<Operation> {
503 // We use unwrap because we don't allow code that can panic while locked.
504 let mut operations = self.operations.lock().expect("In create_operation.");
505
506 let mut index: usize = 0;
507 // First we iterate through the operation slots to try and find an unused
508 // slot. If we don't find one, we append the new entry instead.
509 match (*operations).iter_mut().find(|s| {
510 index += 1;
511 s.upgrade().is_none()
512 }) {
513 Some(free_slot) => {
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000514 let new_op = Arc::new(Operation::new(
515 index - 1,
516 km_op,
517 owner,
518 auth_info,
519 forced,
520 logging_info,
521 ));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700522 *free_slot = Arc::downgrade(&new_op);
523 new_op
524 }
525 None => {
Hasini Gunasinghe0aba68a2021-03-19 00:43:52 +0000526 let new_op = Arc::new(Operation::new(
527 operations.len(),
528 km_op,
529 owner,
530 auth_info,
531 forced,
532 logging_info,
533 ));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700534 operations.push(Arc::downgrade(&new_op));
535 new_op
536 }
537 }
538 }
539
540 fn get(&self, index: usize) -> Option<Arc<Operation>> {
541 self.operations.lock().expect("In OperationDb::get.").get(index).and_then(|op| op.upgrade())
542 }
543
544 /// Attempts to prune an operation.
545 ///
546 /// This function is used during operation creation, i.e., by
547 /// `KeystoreSecurityLevel::create_operation`, to try and free up an operation slot
548 /// if it got `ErrorCode::TOO_MANY_OPERATIONS` from the KeyMint backend. It is not
549 /// guaranteed that an operation slot is available after this call successfully
550 /// returned for various reasons. E.g., another thread may have snatched up the newly
551 /// available slot. Callers may have to call prune multiple times before they get a
552 /// free operation slot. Prune may also return `Err(Error::Rc(ResponseCode::BACKEND_BUSY))`
553 /// which indicates that no prunable operation was found.
554 ///
555 /// To find a suitable candidate we compute the malus for the caller and each existing
556 /// operation. The malus is the inverse of the pruning power (caller) or pruning
557 /// resistance (existing operation).
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700558 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700559 /// The malus is based on the number of sibling operations and age. Sibling
560 /// operations are operations that have the same owner (UID).
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700561 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700562 /// Every operation, existing or new, starts with a malus of 1. Every sibling
563 /// increases the malus by one. The age is the time since an operation was last touched.
564 /// It increases the malus by log6(<age in seconds> + 1) rounded down to the next
565 /// integer. So the malus increases stepwise after 5s, 35s, 215s, ...
566 /// Of two operations with the same malus the least recently used one is considered
567 /// weaker.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700568 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700569 /// For the caller to be able to prune an operation it must find an operation
570 /// with a malus higher than its own.
571 ///
572 /// The malus can be expressed as
573 /// ```
574 /// malus = 1 + no_of_siblings + floor(log6(age_in_seconds + 1))
575 /// ```
576 /// where the constant `1` accounts for the operation under consideration.
577 /// In reality we compute it as
578 /// ```
579 /// caller_malus = 1 + running_siblings
580 /// ```
581 /// because the new operation has no age and is not included in the `running_siblings`,
582 /// and
583 /// ```
584 /// running_malus = running_siblings + floor(log6(age_in_seconds + 1))
585 /// ```
586 /// because a running operation is included in the `running_siblings` and it has
587 /// an age.
588 ///
589 /// ## Example
590 /// A caller with no running operations has a malus of 1. Young (age < 5s) operations
591 /// also with no siblings have a malus of one and cannot be pruned by the caller.
592 /// We have to find an operation that has at least one sibling or is older than 5s.
593 ///
594 /// A caller with one running operation has a malus of 2. Now even young siblings
595 /// or single child aging (5s <= age < 35s) operations are off limit. An aging
596 /// sibling of two, however, would have a malus of 3 and would be fair game.
597 ///
598 /// ## Rationale
599 /// Due to the limitation of KeyMint operation slots, we cannot get around pruning or
600 /// a single app could easily DoS KeyMint.
601 /// Keystore 1.0 used to always prune the least recently used operation. This at least
602 /// guaranteed that new operations can always be started. With the increased usage
603 /// of Keystore we saw increased pruning activity which can lead to a livelock
604 /// situation in the worst case.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700605 ///
Janis Danisevskis1af91262020-08-10 14:58:08 -0700606 /// With the new pruning strategy we want to provide well behaved clients with
607 /// progress assurances while punishing DoS attempts. As a result of this
608 /// strategy we can be in the situation where no operation can be pruned and the
609 /// creation of a new operation fails. This allows single child operations which
610 /// are frequently updated to complete, thereby breaking up livelock situations
611 /// and facilitating system wide progress.
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700612 ///
613 /// ## Update
614 /// We also allow callers to cannibalize their own sibling operations if no other
615 /// slot can be found. In this case the least recently used sibling is pruned.
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800616 pub fn prune(&self, caller: u32, forced: bool) -> Result<(), Error> {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700617 loop {
618 // Maps the uid of the owner to the number of operations that owner has
619 // (running_siblings). More operations per owner lowers the pruning
620 // resistance of the operations of that owner. Whereas the number of
621 // ongoing operations of the caller lowers the pruning power of the caller.
622 let mut owners: HashMap<u32, u64> = HashMap::new();
623 let mut pruning_info: Vec<PruningInfo> = Vec::new();
624
625 let now = Instant::now();
626 self.operations
627 .lock()
628 .expect("In OperationDb::prune: Trying to lock self.operations.")
629 .iter()
630 .for_each(|op| {
631 if let Some(op) = op.upgrade() {
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700632 if let Some(p_info) = op.get_pruning_info() {
633 let owner = p_info.owner;
634 pruning_info.push(p_info);
635 // Count operations per owner.
636 *owners.entry(owner).or_insert(0) += 1;
637 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700638 }
639 });
640
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800641 // If the operation is forced, the caller has a malus of 0.
642 let caller_malus = if forced { 0 } else { 1u64 + *owners.entry(caller).or_default() };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700643
644 // We iterate through all operations computing the malus and finding
645 // the candidate with the highest malus which must also be higher
646 // than the caller_malus.
647 struct CandidateInfo {
648 index: usize,
649 malus: u64,
650 last_usage: Instant,
651 age: Duration,
652 }
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700653 let mut oldest_caller_op: Option<CandidateInfo> = None;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700654 let candidate = pruning_info.iter().fold(
655 None,
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800656 |acc: Option<CandidateInfo>, &PruningInfo { last_usage, owner, index, forced }| {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700657 // Compute the age of the current operation.
658 let age = now
659 .checked_duration_since(last_usage)
660 .unwrap_or_else(|| Duration::new(0, 0));
661
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700662 // Find the least recently used sibling as an alternative pruning candidate.
663 if owner == caller {
664 if let Some(CandidateInfo { age: a, .. }) = oldest_caller_op {
665 if age > a {
666 oldest_caller_op =
667 Some(CandidateInfo { index, malus: 0, last_usage, age });
668 }
669 } else {
670 oldest_caller_op =
671 Some(CandidateInfo { index, malus: 0, last_usage, age });
672 }
673 }
674
Janis Danisevskis1af91262020-08-10 14:58:08 -0700675 // Compute the malus of the current operation.
Janis Danisevskis186d9f42021-03-03 14:40:52 -0800676 let malus = if forced {
677 // Forced operations have a malus of 0. And cannot even be pruned
678 // by other forced operations.
679 0
680 } else {
681 // Expect safety: Every owner in pruning_info was counted in
682 // the owners map. So this unwrap cannot panic.
683 *owners.get(&owner).expect(
684 "This is odd. We should have counted every owner in pruning_info.",
685 ) + ((age.as_secs() + 1) as f64).log(6.0).floor() as u64
686 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700687
688 // Now check if the current operation is a viable/better candidate
689 // the one currently stored in the accumulator.
690 match acc {
691 // First we have to find any operation that is prunable by the caller.
692 None => {
693 if caller_malus < malus {
694 Some(CandidateInfo { index, malus, last_usage, age })
695 } else {
696 None
697 }
698 }
699 // If we have found one we look for the operation with the worst score.
700 // If there is a tie, the older operation is considered weaker.
701 Some(CandidateInfo { index: i, malus: m, last_usage: l, age: a }) => {
702 if malus > m || (malus == m && age > a) {
703 Some(CandidateInfo { index, malus, last_usage, age })
704 } else {
705 Some(CandidateInfo { index: i, malus: m, last_usage: l, age: a })
706 }
707 }
708 }
709 },
710 );
711
Janis Danisevskis45c5c972020-10-26 09:35:16 -0700712 // If we did not find a suitable candidate we may cannibalize our oldest sibling.
713 let candidate = candidate.or(oldest_caller_op);
714
Janis Danisevskis1af91262020-08-10 14:58:08 -0700715 match candidate {
716 Some(CandidateInfo { index, malus: _, last_usage, age: _ }) => {
717 match self.get(index) {
718 Some(op) => {
719 match op.prune(last_usage) {
720 // We successfully freed up a slot.
721 Ok(()) => break Ok(()),
722 // This means the operation we tried to prune was on its way
723 // out. It also means that the slot it had occupied was freed up.
724 Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)) => break Ok(()),
725 // This means the operation we tried to prune was currently
726 // servicing a request. There are two options.
727 // * Assume that it was touched, which means that its
728 // pruning resistance increased. In that case we have
729 // to start over and find another candidate.
730 // * Assume that the operation is transitioning to end-of-life.
731 // which means that we got a free slot for free.
732 // If we assume the first but the second is true, we prune
733 // a good operation without need (aggressive approach).
734 // If we assume the second but the first is true, our
735 // caller will attempt to create a new KeyMint operation,
736 // fail with `ErrorCode::TOO_MANY_OPERATIONS`, and call
737 // us again (conservative approach).
738 Err(Error::Rc(ResponseCode::OPERATION_BUSY)) => {
739 // We choose the conservative approach, because
740 // every needlessly pruned operation can impact
741 // the user experience.
742 // To switch to the aggressive approach replace
743 // the following line with `continue`.
744 break Ok(());
745 }
746
747 // The candidate may have been touched so the score
748 // has changed since our evaluation.
749 _ => continue,
750 }
751 }
752 // This index does not exist any more. The operation
753 // in this slot was dropped. Good news, a slot
754 // has freed up.
755 None => break Ok(()),
756 }
757 }
758 // We did not get a pruning candidate.
759 None => break Err(Error::Rc(ResponseCode::BACKEND_BUSY)),
760 }
761 }
762 }
763}
764
765/// Implementation of IKeystoreOperation.
766pub struct KeystoreOperation {
767 operation: Mutex<Option<Arc<Operation>>>,
768}
769
770impl KeystoreOperation {
771 /// Creates a new operation instance wrapped in a
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000772 /// BnKeystoreOperation proxy object. It also enables
773 /// `BinderFeatures::set_requesting_sid` on the new interface, because
Janis Danisevskis1af91262020-08-10 14:58:08 -0700774 /// we need it for checking Keystore permissions.
Stephen Crane23cf7242022-01-19 17:49:46 +0000775 pub fn new_native_binder(operation: Arc<Operation>) -> binder::Strong<dyn IKeystoreOperation> {
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000776 BnKeystoreOperation::new_binder(
777 Self { operation: Mutex::new(Some(operation)) },
778 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
779 )
Janis Danisevskis1af91262020-08-10 14:58:08 -0700780 }
781
782 /// Grabs the outer operation mutex and calls `f` on the locked operation.
783 /// The function also deletes the operation if it returns with an error or if
784 /// `delete_op` is true.
785 fn with_locked_operation<T, F>(&self, f: F, delete_op: bool) -> Result<T>
786 where
787 for<'a> F: FnOnce(&'a Operation) -> Result<T>,
788 {
789 let mut delete_op: bool = delete_op;
790 match self.operation.try_lock() {
791 Ok(mut mutex_guard) => {
792 let result = match &*mutex_guard {
793 Some(op) => {
Chris Wailes263de9f2022-08-11 15:00:51 -0700794 let result = f(op);
Janis Danisevskis1af91262020-08-10 14:58:08 -0700795 // Any error here means we can discard the operation.
796 if result.is_err() {
797 delete_op = true;
798 }
799 result
800 }
801 None => Err(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000802 .context(ks_err!("KeystoreOperation::with_locked_operation")),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700803 };
804
805 if delete_op {
806 // We give up our reference to the Operation, thereby freeing up our
807 // internal resources and ending the wrapped KeyMint operation.
808 // This KeystoreOperation object will still be owned by an SpIBinder
809 // until the client drops its remote reference.
810 *mutex_guard = None;
811 }
812 result
813 }
814 Err(_) => Err(Error::Rc(ResponseCode::OPERATION_BUSY))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000815 .context(ks_err!("KeystoreOperation::with_locked_operation")),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700816 }
817 }
818}
819
820impl binder::Interface for KeystoreOperation {}
821
822impl IKeystoreOperation for KeystoreOperation {
Stephen Crane23cf7242022-01-19 17:49:46 +0000823 fn updateAad(&self, aad_input: &[u8]) -> binder::Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +0100824 let _wp = wd::watch("IKeystoreOperation::updateAad");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100825 self.with_locked_operation(
David Drysdale5238d772024-06-07 15:12:10 +0100826 |op| op.update_aad(aad_input).context(ks_err!("KeystoreOperation::updateAad")),
827 false,
David Drysdaledb7ddde2024-06-07 16:22:49 +0100828 )
829 .map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700830 }
831
Stephen Crane23cf7242022-01-19 17:49:46 +0000832 fn update(&self, input: &[u8]) -> binder::Result<Option<Vec<u8>>> {
David Drysdale541846b2024-05-23 13:16:07 +0100833 let _wp = wd::watch("IKeystoreOperation::update");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100834 self.with_locked_operation(
David Drysdale5238d772024-06-07 15:12:10 +0100835 |op| op.update(input).context(ks_err!("KeystoreOperation::update")),
836 false,
David Drysdaledb7ddde2024-06-07 16:22:49 +0100837 )
838 .map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700839 }
840 fn finish(
841 &self,
842 input: Option<&[u8]>,
843 signature: Option<&[u8]>,
Stephen Crane23cf7242022-01-19 17:49:46 +0000844 ) -> binder::Result<Option<Vec<u8>>> {
David Drysdale541846b2024-05-23 13:16:07 +0100845 let _wp = wd::watch("IKeystoreOperation::finish");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100846 self.with_locked_operation(
David Drysdale5238d772024-06-07 15:12:10 +0100847 |op| op.finish(input, signature).context(ks_err!("KeystoreOperation::finish")),
848 true,
David Drysdaledb7ddde2024-06-07 16:22:49 +0100849 )
850 .map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700851 }
852
Stephen Crane23cf7242022-01-19 17:49:46 +0000853 fn abort(&self) -> binder::Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +0100854 let _wp = wd::watch("IKeystoreOperation::abort");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100855 let result = self.with_locked_operation(
856 |op| op.abort(Outcome::Abort).context(ks_err!("KeystoreOperation::abort")),
857 true,
858 );
859 result.map_err(|e| {
860 match e.root_cause().downcast_ref::<Error>() {
861 // Calling abort on expired operations is something very common.
862 // There is no reason to clutter the log with it. It is never the cause
863 // for a true problem.
864 Some(Error::Km(ErrorCode::INVALID_OPERATION_HANDLE)) => {}
865 _ => log::error!("{:?}", e),
866 };
867 into_binder(e)
868 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700869 }
870}