Hasini Gunasinghe | 3410f79 | 2020-09-14 17:55:21 +0000 | [diff] [blame] | 1 | // Copyright 2020, The Android Open Source Project |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
Hasini Gunasinghe | 3410f79 | 2020-09-14 17:55:21 +0000 | [diff] [blame] | 15 | //! This is the Keystore 2.0 Enforcements module. |
| 16 | // TODO: more description to follow. |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 17 | use crate::ks_err; |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 18 | use crate::error::{map_binder_status, Error, ErrorCode}; |
| 19 | use crate::globals::{get_timestamp_service, ASYNC_TASK, DB, ENFORCEMENTS}; |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 20 | use crate::key_parameter::{KeyParameter, KeyParameterValue}; |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 21 | use crate::{authorization::Error as AuthzError, super_key::SuperEncryptionType}; |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 22 | use crate::{ |
| 23 | database::{AuthTokenEntry, MonotonicRawTime}, |
| 24 | globals::SUPER_KEY, |
| 25 | }; |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 26 | use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{ |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 27 | Algorithm::Algorithm, ErrorCode::ErrorCode as Ec, HardwareAuthToken::HardwareAuthToken, |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 28 | HardwareAuthenticatorType::HardwareAuthenticatorType, |
| 29 | KeyParameter::KeyParameter as KmKeyParameter, KeyPurpose::KeyPurpose, Tag::Tag, |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame] | 30 | }; |
| 31 | use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{ |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 32 | TimeStampToken::TimeStampToken, |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 33 | }; |
Hasini Gunasinghe | b3715fb | 2021-02-26 20:34:45 +0000 | [diff] [blame] | 34 | use android_security_authorization::aidl::android::security::authorization::ResponseCode::ResponseCode as AuthzResponseCode; |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 35 | use android_system_keystore2::aidl::android::system::keystore2::{ |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 36 | Domain::Domain, IKeystoreSecurityLevel::KEY_FLAG_AUTH_BOUND_WITHOUT_CRYPTOGRAPHIC_LSKF_BINDING, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 37 | OperationChallenge::OperationChallenge, |
| 38 | }; |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 39 | use anyhow::{Context, Result}; |
Janis Danisevskis | b1673db | 2021-02-08 18:11:57 -0800 | [diff] [blame] | 40 | use std::{ |
| 41 | collections::{HashMap, HashSet}, |
Paul Crowley | 7c57bf1 | 2021-02-02 16:26:57 -0800 | [diff] [blame] | 42 | sync::{ |
Paul Crowley | 7c57bf1 | 2021-02-02 16:26:57 -0800 | [diff] [blame] | 43 | mpsc::{channel, Receiver, Sender, TryRecvError}, |
| 44 | Arc, Mutex, Weak, |
| 45 | }, |
| 46 | time::SystemTime, |
Janis Danisevskis | b1673db | 2021-02-08 18:11:57 -0800 | [diff] [blame] | 47 | }; |
Hasini Gunasinghe | 3410f79 | 2020-09-14 17:55:21 +0000 | [diff] [blame] | 48 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 49 | #[derive(Debug)] |
| 50 | enum AuthRequestState { |
| 51 | /// An outstanding per operation authorization request. |
| 52 | OpAuth, |
| 53 | /// An outstanding request for per operation authorization and secure timestamp. |
| 54 | TimeStampedOpAuth(Receiver<Result<TimeStampToken, Error>>), |
| 55 | /// An outstanding request for a timestamp token. |
| 56 | TimeStamp(Receiver<Result<TimeStampToken, Error>>), |
| 57 | } |
| 58 | |
| 59 | #[derive(Debug)] |
| 60 | struct AuthRequest { |
| 61 | state: AuthRequestState, |
| 62 | /// This need to be set to Some to fulfill a AuthRequestState::OpAuth or |
| 63 | /// AuthRequestState::TimeStampedOpAuth. |
Janis Danisevskis | be1969e | 2021-04-20 15:16:24 -0700 | [diff] [blame] | 64 | hat: Mutex<Option<HardwareAuthToken>>, |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 65 | } |
| 66 | |
Janis Danisevskis | be1969e | 2021-04-20 15:16:24 -0700 | [diff] [blame] | 67 | unsafe impl Sync for AuthRequest {} |
| 68 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 69 | impl AuthRequest { |
Janis Danisevskis | be1969e | 2021-04-20 15:16:24 -0700 | [diff] [blame] | 70 | fn op_auth() -> Arc<Self> { |
| 71 | Arc::new(Self { state: AuthRequestState::OpAuth, hat: Mutex::new(None) }) |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 72 | } |
| 73 | |
Janis Danisevskis | be1969e | 2021-04-20 15:16:24 -0700 | [diff] [blame] | 74 | fn timestamped_op_auth(receiver: Receiver<Result<TimeStampToken, Error>>) -> Arc<Self> { |
| 75 | Arc::new(Self { |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 76 | state: AuthRequestState::TimeStampedOpAuth(receiver), |
Janis Danisevskis | be1969e | 2021-04-20 15:16:24 -0700 | [diff] [blame] | 77 | hat: Mutex::new(None), |
| 78 | }) |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 79 | } |
| 80 | |
| 81 | fn timestamp( |
| 82 | hat: HardwareAuthToken, |
| 83 | receiver: Receiver<Result<TimeStampToken, Error>>, |
Janis Danisevskis | be1969e | 2021-04-20 15:16:24 -0700 | [diff] [blame] | 84 | ) -> Arc<Self> { |
| 85 | Arc::new(Self { state: AuthRequestState::TimeStamp(receiver), hat: Mutex::new(Some(hat)) }) |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 86 | } |
| 87 | |
Janis Danisevskis | be1969e | 2021-04-20 15:16:24 -0700 | [diff] [blame] | 88 | fn add_auth_token(&self, hat: HardwareAuthToken) { |
| 89 | *self.hat.lock().unwrap() = Some(hat) |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 90 | } |
| 91 | |
Janis Danisevskis | be1969e | 2021-04-20 15:16:24 -0700 | [diff] [blame] | 92 | fn get_auth_tokens(&self) -> Result<(HardwareAuthToken, Option<TimeStampToken>)> { |
| 93 | let hat = self |
| 94 | .hat |
| 95 | .lock() |
| 96 | .unwrap() |
| 97 | .take() |
| 98 | .ok_or(Error::Km(ErrorCode::KEY_USER_NOT_AUTHENTICATED)) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 99 | .context(ks_err!("No operation auth token received."))?; |
Janis Danisevskis | be1969e | 2021-04-20 15:16:24 -0700 | [diff] [blame] | 100 | |
| 101 | let tst = match &self.state { |
| 102 | AuthRequestState::TimeStampedOpAuth(recv) | AuthRequestState::TimeStamp(recv) => { |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 103 | let result = recv.recv().context("In get_auth_tokens: Sender disconnected.")?; |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 104 | Some(result.context(ks_err!( |
| 105 | "Worker responded with error \ |
| 106 | from generating timestamp token.", |
Janis Danisevskis | be1969e | 2021-04-20 15:16:24 -0700 | [diff] [blame] | 107 | ))?) |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 108 | } |
Janis Danisevskis | be1969e | 2021-04-20 15:16:24 -0700 | [diff] [blame] | 109 | AuthRequestState::OpAuth => None, |
| 110 | }; |
| 111 | Ok((hat, tst)) |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 112 | } |
| 113 | } |
| 114 | |
| 115 | /// DeferredAuthState describes how auth tokens and timestamp tokens need to be provided when |
| 116 | /// updating and finishing an operation. |
| 117 | #[derive(Debug)] |
| 118 | enum DeferredAuthState { |
| 119 | /// Used when an operation does not require further authorization. |
| 120 | NoAuthRequired, |
| 121 | /// Indicates that the operation requires an operation specific token. This means we have |
| 122 | /// to return an operation challenge to the client which should reward us with an |
| 123 | /// operation specific auth token. If it is not provided before the client calls update |
| 124 | /// or finish, the operation fails as not authorized. |
| 125 | OpAuthRequired, |
| 126 | /// Indicates that the operation requires a time stamp token. The auth token was already |
| 127 | /// loaded from the database, but it has to be accompanied by a time stamp token to inform |
| 128 | /// the target KM with a different clock about the time on the authenticators. |
| 129 | TimeStampRequired(HardwareAuthToken), |
| 130 | /// Indicates that both an operation bound auth token and a verification token are |
| 131 | /// before the operation can commence. |
| 132 | TimeStampedOpAuthRequired, |
| 133 | /// In this state the auth info is waiting for the deferred authorizations to come in. |
| 134 | /// We block on timestamp tokens, because we can always make progress on these requests. |
| 135 | /// The per-op auth tokens might never come, which means we fail if the client calls |
| 136 | /// update or finish before we got a per-op auth token. |
Janis Danisevskis | be1969e | 2021-04-20 15:16:24 -0700 | [diff] [blame] | 137 | Waiting(Arc<AuthRequest>), |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 138 | /// In this state we have gotten all of the required tokens, we just cache them to |
| 139 | /// be used when the operation progresses. |
| 140 | Token(HardwareAuthToken, Option<TimeStampToken>), |
| 141 | } |
| 142 | |
| 143 | /// Auth info hold all of the authorization related information of an operation. It is stored |
| 144 | /// in and owned by the operation. It is constructed by authorize_create and stays with the |
| 145 | /// operation until it completes. |
| 146 | #[derive(Debug)] |
| 147 | pub struct AuthInfo { |
| 148 | state: DeferredAuthState, |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 149 | /// An optional key id required to update the usage count if the key usage is limited. |
| 150 | key_usage_limited: Option<i64>, |
Janis Danisevskis | b1673db | 2021-02-08 18:11:57 -0800 | [diff] [blame] | 151 | confirmation_token_receiver: Option<Arc<Mutex<Option<Receiver<Vec<u8>>>>>>, |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 152 | } |
| 153 | |
| 154 | struct TokenReceiverMap { |
| 155 | /// The map maps an outstanding challenge to a TokenReceiver. If an incoming Hardware Auth |
| 156 | /// Token (HAT) has the map key in its challenge field, it gets passed to the TokenReceiver |
| 157 | /// and the entry is removed from the map. In the case where no HAT is received before the |
| 158 | /// corresponding operation gets dropped, the entry goes stale. So every time the cleanup |
| 159 | /// counter (second field in the tuple) turns 0, the map is cleaned from stale entries. |
| 160 | /// The cleanup counter is decremented every time a new receiver is added. |
| 161 | /// and reset to TokenReceiverMap::CLEANUP_PERIOD + 1 after each cleanup. |
| 162 | map_and_cleanup_counter: Mutex<(HashMap<i64, TokenReceiver>, u8)>, |
| 163 | } |
| 164 | |
| 165 | impl Default for TokenReceiverMap { |
| 166 | fn default() -> Self { |
| 167 | Self { map_and_cleanup_counter: Mutex::new((HashMap::new(), Self::CLEANUP_PERIOD + 1)) } |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | impl TokenReceiverMap { |
| 172 | /// There is a chance that receivers may become stale because their operation is dropped |
| 173 | /// without ever being authorized. So occasionally we iterate through the map and throw |
| 174 | /// out obsolete entries. |
| 175 | /// This is the number of calls to add_receiver between cleanups. |
| 176 | const CLEANUP_PERIOD: u8 = 25; |
| 177 | |
| 178 | pub fn add_auth_token(&self, hat: HardwareAuthToken) { |
Janis Danisevskis | be1969e | 2021-04-20 15:16:24 -0700 | [diff] [blame] | 179 | let recv = { |
| 180 | // Limit the scope of the mutex guard, so that it is not held while the auth token is |
| 181 | // added. |
| 182 | let mut map = self.map_and_cleanup_counter.lock().unwrap(); |
| 183 | let (ref mut map, _) = *map; |
| 184 | map.remove_entry(&hat.challenge) |
| 185 | }; |
| 186 | |
| 187 | if let Some((_, recv)) = recv { |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 188 | recv.add_auth_token(hat); |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | pub fn add_receiver(&self, challenge: i64, recv: TokenReceiver) { |
| 193 | let mut map = self.map_and_cleanup_counter.lock().unwrap(); |
| 194 | let (ref mut map, ref mut cleanup_counter) = *map; |
| 195 | map.insert(challenge, recv); |
| 196 | |
| 197 | *cleanup_counter -= 1; |
| 198 | if *cleanup_counter == 0 { |
| 199 | map.retain(|_, v| !v.is_obsolete()); |
| 200 | map.shrink_to_fit(); |
| 201 | *cleanup_counter = Self::CLEANUP_PERIOD + 1; |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | #[derive(Debug)] |
Janis Danisevskis | be1969e | 2021-04-20 15:16:24 -0700 | [diff] [blame] | 207 | struct TokenReceiver(Weak<AuthRequest>); |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 208 | |
| 209 | impl TokenReceiver { |
| 210 | fn is_obsolete(&self) -> bool { |
| 211 | self.0.upgrade().is_none() |
| 212 | } |
| 213 | |
| 214 | fn add_auth_token(&self, hat: HardwareAuthToken) { |
| 215 | if let Some(state_arc) = self.0.upgrade() { |
Janis Danisevskis | be1969e | 2021-04-20 15:16:24 -0700 | [diff] [blame] | 216 | state_arc.add_auth_token(hat); |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 217 | } |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | fn get_timestamp_token(challenge: i64) -> Result<TimeStampToken, Error> { |
Janis Danisevskis | 5f3a057 | 2021-06-18 11:26:42 -0700 | [diff] [blame] | 222 | let dev = get_timestamp_service().expect(concat!( |
| 223 | "Secure Clock service must be present ", |
| 224 | "if TimeStampTokens are required." |
| 225 | )); |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 226 | map_binder_status(dev.generateTimeStamp(challenge)) |
| 227 | } |
| 228 | |
| 229 | fn timestamp_token_request(challenge: i64, sender: Sender<Result<TimeStampToken, Error>>) { |
| 230 | if let Err(e) = sender.send(get_timestamp_token(challenge)) { |
| 231 | log::info!( |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 232 | concat!("Receiver hung up ", "before timestamp token could be delivered. {:?}"), |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 233 | e |
| 234 | ); |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | impl AuthInfo { |
| 239 | /// This function gets called after an operation was successfully created. |
| 240 | /// It makes all the preparations required, so that the operation has all the authentication |
| 241 | /// related artifacts to advance on update and finish. |
| 242 | pub fn finalize_create_authorization(&mut self, challenge: i64) -> Option<OperationChallenge> { |
| 243 | match &self.state { |
| 244 | DeferredAuthState::OpAuthRequired => { |
| 245 | let auth_request = AuthRequest::op_auth(); |
| 246 | let token_receiver = TokenReceiver(Arc::downgrade(&auth_request)); |
| 247 | ENFORCEMENTS.register_op_auth_receiver(challenge, token_receiver); |
| 248 | |
| 249 | self.state = DeferredAuthState::Waiting(auth_request); |
| 250 | Some(OperationChallenge { challenge }) |
| 251 | } |
| 252 | DeferredAuthState::TimeStampedOpAuthRequired => { |
| 253 | let (sender, receiver) = channel::<Result<TimeStampToken, Error>>(); |
| 254 | let auth_request = AuthRequest::timestamped_op_auth(receiver); |
| 255 | let token_receiver = TokenReceiver(Arc::downgrade(&auth_request)); |
| 256 | ENFORCEMENTS.register_op_auth_receiver(challenge, token_receiver); |
| 257 | |
Janis Danisevskis | 40f0e6b | 2021-02-10 15:48:44 -0800 | [diff] [blame] | 258 | ASYNC_TASK.queue_hi(move |_| timestamp_token_request(challenge, sender)); |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 259 | self.state = DeferredAuthState::Waiting(auth_request); |
| 260 | Some(OperationChallenge { challenge }) |
| 261 | } |
| 262 | DeferredAuthState::TimeStampRequired(hat) => { |
| 263 | let hat = (*hat).clone(); |
| 264 | let (sender, receiver) = channel::<Result<TimeStampToken, Error>>(); |
| 265 | let auth_request = AuthRequest::timestamp(hat, receiver); |
Janis Danisevskis | 40f0e6b | 2021-02-10 15:48:44 -0800 | [diff] [blame] | 266 | ASYNC_TASK.queue_hi(move |_| timestamp_token_request(challenge, sender)); |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 267 | self.state = DeferredAuthState::Waiting(auth_request); |
| 268 | None |
| 269 | } |
| 270 | _ => None, |
| 271 | } |
| 272 | } |
| 273 | |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 274 | /// This function is the authorization hook called before operation update. |
| 275 | /// It returns the auth tokens required by the operation to commence update. |
| 276 | pub fn before_update(&mut self) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>)> { |
| 277 | self.get_auth_tokens() |
| 278 | } |
| 279 | |
| 280 | /// This function is the authorization hook called before operation finish. |
| 281 | /// It returns the auth tokens required by the operation to commence finish. |
Janis Danisevskis | b1673db | 2021-02-08 18:11:57 -0800 | [diff] [blame] | 282 | /// The third token is a confirmation token. |
| 283 | pub fn before_finish( |
| 284 | &mut self, |
| 285 | ) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>, Option<Vec<u8>>)> { |
| 286 | let mut confirmation_token: Option<Vec<u8>> = None; |
| 287 | if let Some(ref confirmation_token_receiver) = self.confirmation_token_receiver { |
| 288 | let locked_receiver = confirmation_token_receiver.lock().unwrap(); |
| 289 | if let Some(ref receiver) = *locked_receiver { |
| 290 | loop { |
| 291 | match receiver.try_recv() { |
| 292 | // As long as we get tokens we loop and discard all but the most |
| 293 | // recent one. |
| 294 | Ok(t) => confirmation_token = Some(t), |
| 295 | Err(TryRecvError::Empty) => break, |
| 296 | Err(TryRecvError::Disconnected) => { |
| 297 | log::error!(concat!( |
| 298 | "We got disconnected from the APC service, ", |
| 299 | "this should never happen." |
| 300 | )); |
| 301 | break; |
| 302 | } |
| 303 | } |
| 304 | } |
| 305 | } |
| 306 | } |
| 307 | self.get_auth_tokens().map(|(hat, tst)| (hat, tst, confirmation_token)) |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 308 | } |
| 309 | |
| 310 | /// This function is the authorization hook called after finish succeeded. |
| 311 | /// As of this writing it checks if the key was a limited use key. If so it updates the |
| 312 | /// use counter of the key in the database. When the use counter is depleted, the key gets |
| 313 | /// marked for deletion and the garbage collector is notified. |
| 314 | pub fn after_finish(&self) -> Result<()> { |
| 315 | if let Some(key_id) = self.key_usage_limited { |
| 316 | // On the last successful use, the key gets deleted. In this case we |
| 317 | // have to notify the garbage collector. |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 318 | DB.with(|db| { |
| 319 | db.borrow_mut() |
| 320 | .check_and_update_key_usage_count(key_id) |
| 321 | .context("Trying to update key usage count.") |
| 322 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 323 | .context(ks_err!())?; |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 324 | } |
| 325 | Ok(()) |
| 326 | } |
| 327 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 328 | /// This function returns the auth tokens as needed by the ongoing operation or fails |
| 329 | /// with ErrorCode::KEY_USER_NOT_AUTHENTICATED. If this was called for the first time |
| 330 | /// after a deferred authorization was requested by finalize_create_authorization, this |
| 331 | /// function may block on the generation of a time stamp token. It then moves the |
| 332 | /// tokens into the DeferredAuthState::Token state for future use. |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 333 | fn get_auth_tokens(&mut self) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>)> { |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 334 | let deferred_tokens = if let DeferredAuthState::Waiting(ref auth_request) = self.state { |
Janis Danisevskis | be1969e | 2021-04-20 15:16:24 -0700 | [diff] [blame] | 335 | Some(auth_request.get_auth_tokens().context("In AuthInfo::get_auth_tokens.")?) |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 336 | } else { |
| 337 | None |
| 338 | }; |
| 339 | |
| 340 | if let Some((hat, tst)) = deferred_tokens { |
| 341 | self.state = DeferredAuthState::Token(hat, tst); |
| 342 | } |
| 343 | |
| 344 | match &self.state { |
| 345 | DeferredAuthState::NoAuthRequired => Ok((None, None)), |
| 346 | DeferredAuthState::Token(hat, tst) => Ok((Some((*hat).clone()), (*tst).clone())), |
| 347 | DeferredAuthState::OpAuthRequired |
| 348 | | DeferredAuthState::TimeStampedOpAuthRequired |
| 349 | | DeferredAuthState::TimeStampRequired(_) => { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 350 | Err(Error::Km(ErrorCode::KEY_USER_NOT_AUTHENTICATED)).context(ks_err!( |
| 351 | "No operation auth token requested??? \ |
| 352 | This should not happen." |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 353 | )) |
| 354 | } |
| 355 | // This should not be reachable, because it should have been handled above. |
| 356 | DeferredAuthState::Waiting(_) => { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 357 | Err(Error::sys()).context(ks_err!("AuthInfo::get_auth_tokens: Cannot be reached.",)) |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 358 | } |
| 359 | } |
| 360 | } |
| 361 | } |
| 362 | |
Hasini Gunasinghe | 3410f79 | 2020-09-14 17:55:21 +0000 | [diff] [blame] | 363 | /// Enforcements data structure |
Paul Crowley | 7c57bf1 | 2021-02-02 16:26:57 -0800 | [diff] [blame] | 364 | #[derive(Default)] |
Hasini Gunasinghe | 3410f79 | 2020-09-14 17:55:21 +0000 | [diff] [blame] | 365 | pub struct Enforcements { |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 366 | /// This hash set contains the user ids for whom the device is currently unlocked. If a user id |
| 367 | /// is not in the set, it implies that the device is locked for the user. |
Hasini Gunasinghe | 3410f79 | 2020-09-14 17:55:21 +0000 | [diff] [blame] | 368 | device_unlocked_set: Mutex<HashSet<i32>>, |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 369 | /// This field maps outstanding auth challenges to their operations. When an auth token |
| 370 | /// with the right challenge is received it is passed to the map using |
| 371 | /// TokenReceiverMap::add_auth_token() which removes the entry from the map. If an entry goes |
| 372 | /// stale, because the operation gets dropped before an auth token is received, the map |
| 373 | /// is cleaned up in regular intervals. |
| 374 | op_auth_map: TokenReceiverMap, |
Janis Danisevskis | b1673db | 2021-02-08 18:11:57 -0800 | [diff] [blame] | 375 | /// The enforcement module will try to get a confirmation token from this channel whenever |
| 376 | /// an operation that requires confirmation finishes. |
| 377 | confirmation_token_receiver: Arc<Mutex<Option<Receiver<Vec<u8>>>>>, |
Hasini Gunasinghe | 3410f79 | 2020-09-14 17:55:21 +0000 | [diff] [blame] | 378 | } |
| 379 | |
| 380 | impl Enforcements { |
Janis Danisevskis | b1673db | 2021-02-08 18:11:57 -0800 | [diff] [blame] | 381 | /// Install the confirmation token receiver. The enforcement module will try to get a |
| 382 | /// confirmation token from this channel whenever an operation that requires confirmation |
| 383 | /// finishes. |
| 384 | pub fn install_confirmation_token_receiver( |
| 385 | &self, |
| 386 | confirmation_token_receiver: Receiver<Vec<u8>>, |
| 387 | ) { |
| 388 | *self.confirmation_token_receiver.lock().unwrap() = Some(confirmation_token_receiver); |
| 389 | } |
| 390 | |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 391 | /// Checks if a create call is authorized, given key parameters and operation parameters. |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 392 | /// It returns an optional immediate auth token which can be presented to begin, and an |
| 393 | /// AuthInfo object which stays with the authorized operation and is used to obtain |
| 394 | /// auth tokens and timestamp tokens as required by the operation. |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 395 | /// With regard to auth tokens, the following steps are taken: |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 396 | /// |
| 397 | /// If no key parameters are given (typically when the client is self managed |
| 398 | /// (see Domain.Blob)) nothing is enforced. |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 399 | /// If the key is time-bound, find a matching auth token from the database. |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 400 | /// If the above step is successful, and if requires_timestamp is given, the returned |
| 401 | /// AuthInfo will provide a Timestamp token as appropriate. |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 402 | pub fn authorize_create( |
| 403 | &self, |
| 404 | purpose: KeyPurpose, |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 405 | key_properties: Option<&(i64, Vec<KeyParameter>)>, |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 406 | op_params: &[KmKeyParameter], |
| 407 | requires_timestamp: bool, |
| 408 | ) -> Result<(Option<HardwareAuthToken>, AuthInfo)> { |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 409 | let (key_id, key_params) = match key_properties { |
| 410 | Some((key_id, key_params)) => (*key_id, key_params), |
| 411 | None => { |
| 412 | return Ok(( |
| 413 | None, |
Janis Danisevskis | b1673db | 2021-02-08 18:11:57 -0800 | [diff] [blame] | 414 | AuthInfo { |
| 415 | state: DeferredAuthState::NoAuthRequired, |
| 416 | key_usage_limited: None, |
| 417 | confirmation_token_receiver: None, |
| 418 | }, |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 419 | )); |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 420 | } |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 421 | }; |
| 422 | |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 423 | match purpose { |
| 424 | // Allow SIGN, DECRYPT for both symmetric and asymmetric keys. |
| 425 | KeyPurpose::SIGN | KeyPurpose::DECRYPT => {} |
| 426 | // Rule out WRAP_KEY purpose |
| 427 | KeyPurpose::WRAP_KEY => { |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 428 | return Err(Error::Km(Ec::INCOMPATIBLE_PURPOSE)) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 429 | .context(ks_err!("WRAP_KEY purpose is not allowed here.",)); |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 430 | } |
Bram Bonné | a6b8382 | 2021-01-20 11:10:05 +0100 | [diff] [blame] | 431 | // Allow AGREE_KEY for EC keys only. |
| 432 | KeyPurpose::AGREE_KEY => { |
| 433 | for kp in key_params.iter() { |
| 434 | if kp.get_tag() == Tag::ALGORITHM |
| 435 | && *kp.key_parameter_value() != KeyParameterValue::Algorithm(Algorithm::EC) |
| 436 | { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 437 | return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE)) |
| 438 | .context(ks_err!("key agreement is only supported for EC keys.",)); |
Bram Bonné | a6b8382 | 2021-01-20 11:10:05 +0100 | [diff] [blame] | 439 | } |
| 440 | } |
| 441 | } |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 442 | KeyPurpose::VERIFY | KeyPurpose::ENCRYPT => { |
| 443 | // We do not support ENCRYPT and VERIFY (the remaining two options of purpose) for |
| 444 | // asymmetric keys. |
| 445 | for kp in key_params.iter() { |
| 446 | match *kp.key_parameter_value() { |
| 447 | KeyParameterValue::Algorithm(Algorithm::RSA) |
| 448 | | KeyParameterValue::Algorithm(Algorithm::EC) => { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 449 | return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE)).context(ks_err!( |
| 450 | "public operations on asymmetric keys are \ |
| 451 | not supported." |
| 452 | )); |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 453 | } |
| 454 | _ => {} |
| 455 | } |
| 456 | } |
| 457 | } |
| 458 | _ => { |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 459 | return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE)) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 460 | .context(ks_err!("authorize_create: specified purpose is not supported.")); |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 461 | } |
| 462 | } |
| 463 | // The following variables are to record information from key parameters to be used in |
| 464 | // enforcements, when two or more such pieces of information are required for enforcements. |
| 465 | // There is only one additional variable than what legacy keystore has, but this helps |
| 466 | // reduce the number of for loops on key parameters from 3 to 1, compared to legacy keystore |
| 467 | let mut key_purpose_authorized: bool = false; |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 468 | let mut user_auth_type: Option<HardwareAuthenticatorType> = None; |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 469 | let mut no_auth_required: bool = false; |
| 470 | let mut caller_nonce_allowed = false; |
| 471 | let mut user_id: i32 = -1; |
| 472 | let mut user_secure_ids = Vec::<i64>::new(); |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 473 | let mut key_time_out: Option<i64> = None; |
| 474 | let mut allow_while_on_body = false; |
Hasini Gunasinghe | a020b53 | 2021-01-07 21:42:35 +0000 | [diff] [blame] | 475 | let mut unlocked_device_required = false; |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 476 | let mut key_usage_limited: Option<i64> = None; |
Janis Danisevskis | b1673db | 2021-02-08 18:11:57 -0800 | [diff] [blame] | 477 | let mut confirmation_token_receiver: Option<Arc<Mutex<Option<Receiver<Vec<u8>>>>>> = None; |
Paul Crowley | 7c57bf1 | 2021-02-02 16:26:57 -0800 | [diff] [blame] | 478 | let mut max_boot_level: Option<i32> = None; |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 479 | |
| 480 | // iterate through key parameters, recording information we need for authorization |
| 481 | // enforcements later, or enforcing authorizations in place, where applicable |
| 482 | for key_param in key_params.iter() { |
| 483 | match key_param.key_parameter_value() { |
| 484 | KeyParameterValue::NoAuthRequired => { |
| 485 | no_auth_required = true; |
| 486 | } |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 487 | KeyParameterValue::AuthTimeout(t) => { |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 488 | key_time_out = Some(*t as i64); |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 489 | } |
| 490 | KeyParameterValue::HardwareAuthenticatorType(a) => { |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 491 | user_auth_type = Some(*a); |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 492 | } |
| 493 | KeyParameterValue::KeyPurpose(p) => { |
Janis Danisevskis | 104d8e4 | 2021-01-14 22:49:27 -0800 | [diff] [blame] | 494 | // The following check has the effect of key_params.contains(purpose) |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 495 | // Also, authorizing purpose can not be completed here, if there can be multiple |
Janis Danisevskis | 104d8e4 | 2021-01-14 22:49:27 -0800 | [diff] [blame] | 496 | // key parameters for KeyPurpose. |
| 497 | key_purpose_authorized = key_purpose_authorized || *p == purpose; |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 498 | } |
| 499 | KeyParameterValue::CallerNonce => { |
| 500 | caller_nonce_allowed = true; |
| 501 | } |
| 502 | KeyParameterValue::ActiveDateTime(a) => { |
| 503 | if !Enforcements::is_given_time_passed(*a, true) { |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 504 | return Err(Error::Km(Ec::KEY_NOT_YET_VALID)) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 505 | .context(ks_err!("key is not yet active.")); |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 506 | } |
| 507 | } |
| 508 | KeyParameterValue::OriginationExpireDateTime(o) => { |
| 509 | if (purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN) |
| 510 | && Enforcements::is_given_time_passed(*o, false) |
| 511 | { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 512 | return Err(Error::Km(Ec::KEY_EXPIRED)).context(ks_err!("key is expired.")); |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 513 | } |
| 514 | } |
| 515 | KeyParameterValue::UsageExpireDateTime(u) => { |
| 516 | if (purpose == KeyPurpose::DECRYPT || purpose == KeyPurpose::VERIFY) |
| 517 | && Enforcements::is_given_time_passed(*u, false) |
| 518 | { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 519 | return Err(Error::Km(Ec::KEY_EXPIRED)).context(ks_err!("key is expired.")); |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 520 | } |
| 521 | } |
| 522 | KeyParameterValue::UserSecureID(s) => { |
| 523 | user_secure_ids.push(*s); |
| 524 | } |
| 525 | KeyParameterValue::UserID(u) => { |
| 526 | user_id = *u; |
| 527 | } |
| 528 | KeyParameterValue::UnlockedDeviceRequired => { |
Hasini Gunasinghe | a020b53 | 2021-01-07 21:42:35 +0000 | [diff] [blame] | 529 | unlocked_device_required = true; |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 530 | } |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 531 | KeyParameterValue::AllowWhileOnBody => { |
| 532 | allow_while_on_body = true; |
| 533 | } |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 534 | KeyParameterValue::UsageCountLimit(_) => { |
| 535 | // We don't examine the limit here because this is enforced on finish. |
| 536 | // Instead, we store the key_id so that finish can look up the key |
| 537 | // in the database again and check and update the counter. |
| 538 | key_usage_limited = Some(key_id); |
| 539 | } |
Janis Danisevskis | b1673db | 2021-02-08 18:11:57 -0800 | [diff] [blame] | 540 | KeyParameterValue::TrustedConfirmationRequired => { |
| 541 | confirmation_token_receiver = Some(self.confirmation_token_receiver.clone()); |
| 542 | } |
Paul Crowley | 7c57bf1 | 2021-02-02 16:26:57 -0800 | [diff] [blame] | 543 | KeyParameterValue::MaxBootLevel(level) => { |
| 544 | max_boot_level = Some(*level); |
| 545 | } |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 546 | // NOTE: as per offline discussion, sanitizing key parameters and rejecting |
| 547 | // create operation if any non-allowed tags are present, is not done in |
| 548 | // authorize_create (unlike in legacy keystore where AuthorizeBegin is rejected if |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 549 | // a subset of non-allowed tags are present). Because sanitizing key parameters |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 550 | // should have been done during generate/import key, by KeyMint. |
| 551 | _ => { /*Do nothing on all the other key parameters, as in legacy keystore*/ } |
| 552 | } |
| 553 | } |
| 554 | |
| 555 | // authorize the purpose |
| 556 | if !key_purpose_authorized { |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 557 | return Err(Error::Km(Ec::INCOMPATIBLE_PURPOSE)) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 558 | .context(ks_err!("the purpose is not authorized.")); |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 559 | } |
| 560 | |
| 561 | // if both NO_AUTH_REQUIRED and USER_SECURE_ID tags are present, return error |
| 562 | if !user_secure_ids.is_empty() && no_auth_required { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 563 | return Err(Error::Km(Ec::INVALID_KEY_BLOB)) |
| 564 | .context(ks_err!("key has both NO_AUTH_REQUIRED and USER_SECURE_ID tags.")); |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 565 | } |
| 566 | |
| 567 | // if either of auth_type or secure_id is present and the other is not present, return error |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 568 | if (user_auth_type.is_some() && user_secure_ids.is_empty()) |
| 569 | || (user_auth_type.is_none() && !user_secure_ids.is_empty()) |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 570 | { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 571 | return Err(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED)).context(ks_err!( |
| 572 | "Auth required, but either auth type or secure ids \ |
| 573 | are not present." |
| 574 | )); |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 575 | } |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 576 | |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 577 | // validate caller nonce for origination purposes |
| 578 | if (purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN) |
| 579 | && !caller_nonce_allowed |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 580 | && op_params.iter().any(|kp| kp.tag == Tag::NONCE) |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 581 | { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 582 | return Err(Error::Km(Ec::CALLER_NONCE_PROHIBITED)) |
| 583 | .context(ks_err!("NONCE is present, although CALLER_NONCE is not present")); |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 584 | } |
| 585 | |
Hasini Gunasinghe | a020b53 | 2021-01-07 21:42:35 +0000 | [diff] [blame] | 586 | if unlocked_device_required { |
| 587 | // check the device locked status. If locked, operations on the key are not |
| 588 | // allowed. |
Hasini Gunasinghe | a020b53 | 2021-01-07 21:42:35 +0000 | [diff] [blame] | 589 | if self.is_device_locked(user_id) { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 590 | return Err(Error::Km(Ec::DEVICE_LOCKED)).context(ks_err!("device is locked.")); |
Hasini Gunasinghe | a020b53 | 2021-01-07 21:42:35 +0000 | [diff] [blame] | 591 | } |
| 592 | } |
| 593 | |
Paul Crowley | 7c57bf1 | 2021-02-02 16:26:57 -0800 | [diff] [blame] | 594 | if let Some(level) = max_boot_level { |
Janis Danisevskis | 0fd25a6 | 2022-01-04 19:53:37 -0800 | [diff] [blame] | 595 | if !SUPER_KEY.read().unwrap().level_accessible(level) { |
Paul Crowley | 7c57bf1 | 2021-02-02 16:26:57 -0800 | [diff] [blame] | 596 | return Err(Error::Km(Ec::BOOT_LEVEL_EXCEEDED)) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 597 | .context(ks_err!("boot level is too late.")); |
Paul Crowley | 7c57bf1 | 2021-02-02 16:26:57 -0800 | [diff] [blame] | 598 | } |
| 599 | } |
| 600 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 601 | if !unlocked_device_required && no_auth_required { |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 602 | return Ok(( |
| 603 | None, |
Janis Danisevskis | b1673db | 2021-02-08 18:11:57 -0800 | [diff] [blame] | 604 | AuthInfo { |
| 605 | state: DeferredAuthState::NoAuthRequired, |
| 606 | key_usage_limited, |
| 607 | confirmation_token_receiver, |
| 608 | }, |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 609 | )); |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 610 | } |
| 611 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 612 | let has_sids = !user_secure_ids.is_empty(); |
| 613 | |
| 614 | let timeout_bound = key_time_out.is_some() && has_sids; |
| 615 | |
| 616 | let per_op_bound = key_time_out.is_none() && has_sids; |
| 617 | |
| 618 | let need_auth_token = timeout_bound || unlocked_device_required; |
| 619 | |
| 620 | let hat_and_last_off_body = if need_auth_token { |
| 621 | let hat_and_last_off_body = Self::find_auth_token(|hat: &AuthTokenEntry| { |
Seth Moore | 653eca5 | 2021-11-19 16:52:19 -0800 | [diff] [blame] | 622 | if let (Some(auth_type), true) = (user_auth_type, timeout_bound) { |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 623 | hat.satisfies(&user_secure_ids, auth_type) |
| 624 | } else { |
| 625 | unlocked_device_required |
| 626 | } |
Matthew Maurer | d7815ca | 2021-05-06 21:58:45 -0700 | [diff] [blame] | 627 | }); |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 628 | Some( |
| 629 | hat_and_last_off_body |
| 630 | .ok_or(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED)) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 631 | .context(ks_err!("No suitable auth token found."))?, |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 632 | ) |
| 633 | } else { |
| 634 | None |
| 635 | }; |
| 636 | |
| 637 | // Now check the validity of the auth token if the key is timeout bound. |
| 638 | let hat = match (hat_and_last_off_body, key_time_out) { |
| 639 | (Some((hat, last_off_body)), Some(key_time_out)) => { |
| 640 | let now = MonotonicRawTime::now(); |
| 641 | let token_age = now |
| 642 | .checked_sub(&hat.time_received()) |
| 643 | .ok_or_else(Error::sys) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 644 | .context(ks_err!( |
| 645 | "Overflow while computing Auth token validity. \ |
| 646 | Validity cannot be established." |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 647 | ))?; |
| 648 | |
| 649 | let on_body_extended = allow_while_on_body && last_off_body < hat.time_received(); |
| 650 | |
| 651 | if token_age.seconds() > key_time_out && !on_body_extended { |
| 652 | return Err(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED)) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 653 | .context(ks_err!("matching auth token is expired.")); |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 654 | } |
| 655 | Some(hat) |
| 656 | } |
| 657 | (Some((hat, _)), None) => Some(hat), |
| 658 | // If timeout_bound is true, above code must have retrieved a HAT or returned with |
| 659 | // KEY_USER_NOT_AUTHENTICATED. This arm should not be reachable. |
| 660 | (None, Some(_)) => panic!("Logical error."), |
| 661 | _ => None, |
| 662 | }; |
| 663 | |
| 664 | Ok(match (hat, requires_timestamp, per_op_bound) { |
| 665 | // Per-op-bound and Some(hat) can only happen if we are both per-op bound and unlocked |
| 666 | // device required. In addition, this KM instance needs a timestamp token. |
| 667 | // So the HAT cannot be presented on create. So on update/finish we present both |
| 668 | // an per-op-bound auth token and a timestamp token. |
| 669 | (Some(_), true, true) => (None, DeferredAuthState::TimeStampedOpAuthRequired), |
Hasini Gunasinghe | e093b55 | 2021-04-30 20:05:31 +0000 | [diff] [blame] | 670 | (Some(hat), true, false) => ( |
| 671 | Some(hat.auth_token().clone()), |
| 672 | DeferredAuthState::TimeStampRequired(hat.take_auth_token()), |
| 673 | ), |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 674 | (Some(hat), false, true) => { |
| 675 | (Some(hat.take_auth_token()), DeferredAuthState::OpAuthRequired) |
| 676 | } |
| 677 | (Some(hat), false, false) => { |
| 678 | (Some(hat.take_auth_token()), DeferredAuthState::NoAuthRequired) |
| 679 | } |
| 680 | (None, _, true) => (None, DeferredAuthState::OpAuthRequired), |
| 681 | (None, _, false) => (None, DeferredAuthState::NoAuthRequired), |
| 682 | }) |
Janis Danisevskis | b1673db | 2021-02-08 18:11:57 -0800 | [diff] [blame] | 683 | .map(|(hat, state)| { |
| 684 | (hat, AuthInfo { state, key_usage_limited, confirmation_token_receiver }) |
| 685 | }) |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 686 | } |
| 687 | |
Matthew Maurer | d7815ca | 2021-05-06 21:58:45 -0700 | [diff] [blame] | 688 | fn find_auth_token<F>(p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)> |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 689 | where |
| 690 | F: Fn(&AuthTokenEntry) -> bool, |
| 691 | { |
Matthew Maurer | d7815ca | 2021-05-06 21:58:45 -0700 | [diff] [blame] | 692 | DB.with(|db| db.borrow().find_auth_token_entry(p)) |
Hasini Gunasinghe | 5112c70 | 2020-11-09 22:13:25 +0000 | [diff] [blame] | 693 | } |
| 694 | |
| 695 | /// Checks if the time now since epoch is greater than (or equal, if is_given_time_inclusive is |
| 696 | /// set) the given time (in milliseconds) |
| 697 | fn is_given_time_passed(given_time: i64, is_given_time_inclusive: bool) -> bool { |
| 698 | let duration_since_epoch = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH); |
| 699 | |
| 700 | let time_since_epoch = match duration_since_epoch { |
| 701 | Ok(duration) => duration.as_millis(), |
| 702 | Err(_) => return false, |
| 703 | }; |
| 704 | |
| 705 | if is_given_time_inclusive { |
| 706 | time_since_epoch >= (given_time as u128) |
| 707 | } else { |
| 708 | time_since_epoch > (given_time as u128) |
| 709 | } |
| 710 | } |
| 711 | |
| 712 | /// Check if the device is locked for the given user. If there's no entry yet for the user, |
| 713 | /// we assume that the device is locked |
| 714 | fn is_device_locked(&self, user_id: i32) -> bool { |
| 715 | // unwrap here because there's no way this mutex guard can be poisoned and |
| 716 | // because there's no way to recover, even if it is poisoned. |
| 717 | let set = self.device_unlocked_set.lock().unwrap(); |
| 718 | !set.contains(&user_id) |
| 719 | } |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 720 | |
| 721 | /// Sets the device locked status for the user. This method is called externally. |
| 722 | pub fn set_device_locked(&self, user_id: i32, device_locked_status: bool) { |
| 723 | // unwrap here because there's no way this mutex guard can be poisoned and |
| 724 | // because there's no way to recover, even if it is poisoned. |
| 725 | let mut set = self.device_unlocked_set.lock().unwrap(); |
| 726 | if device_locked_status { |
| 727 | set.remove(&user_id); |
| 728 | } else { |
| 729 | set.insert(user_id); |
| 730 | } |
| 731 | } |
| 732 | |
| 733 | /// Add this auth token to the database. |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 734 | /// Then present the auth token to the op auth map. If an operation is waiting for this |
| 735 | /// auth token this fulfills the request and removes the receiver from the map. |
Matthew Maurer | d7815ca | 2021-05-06 21:58:45 -0700 | [diff] [blame] | 736 | pub fn add_auth_token(&self, hat: HardwareAuthToken) { |
| 737 | DB.with(|db| db.borrow_mut().insert_auth_token(&hat)); |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 738 | self.op_auth_map.add_auth_token(hat); |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 739 | } |
Hasini Gunasinghe | 888dd35 | 2020-11-17 23:08:39 +0000 | [diff] [blame] | 740 | |
| 741 | /// This allows adding an entry to the op_auth_map, indexed by the operation challenge. |
| 742 | /// This is to be called by create_operation, once it has received the operation challenge |
| 743 | /// from keymint for an operation whose authorization decision is OpAuthRequired, as signalled |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 744 | /// by the DeferredAuthState. |
| 745 | fn register_op_auth_receiver(&self, challenge: i64, recv: TokenReceiver) { |
| 746 | self.op_auth_map.add_receiver(challenge, recv); |
Hasini Gunasinghe | f04d07a | 2020-11-25 22:41:35 +0000 | [diff] [blame] | 747 | } |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 748 | |
| 749 | /// Given the set of key parameters and flags, check if super encryption is required. |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 750 | pub fn super_encryption_required( |
| 751 | domain: &Domain, |
| 752 | key_parameters: &[KeyParameter], |
| 753 | flags: Option<i32>, |
| 754 | ) -> SuperEncryptionType { |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 755 | if let Some(flags) = flags { |
| 756 | if (flags & KEY_FLAG_AUTH_BOUND_WITHOUT_CRYPTOGRAPHIC_LSKF_BINDING) != 0 { |
| 757 | return SuperEncryptionType::None; |
| 758 | } |
| 759 | } |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 760 | // Each answer has a priority, numerically largest priority wins. |
| 761 | struct Candidate { |
| 762 | priority: u32, |
| 763 | enc_type: SuperEncryptionType, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 764 | } |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 765 | let mut result = Candidate { priority: 0, enc_type: SuperEncryptionType::None }; |
| 766 | for kp in key_parameters { |
| 767 | let t = match kp.key_parameter_value() { |
| 768 | KeyParameterValue::MaxBootLevel(level) => { |
| 769 | Candidate { priority: 3, enc_type: SuperEncryptionType::BootLevel(*level) } |
| 770 | } |
| 771 | KeyParameterValue::UnlockedDeviceRequired if *domain == Domain::APP => { |
| 772 | Candidate { priority: 2, enc_type: SuperEncryptionType::ScreenLockBound } |
| 773 | } |
| 774 | KeyParameterValue::UserSecureID(_) if *domain == Domain::APP => { |
| 775 | Candidate { priority: 1, enc_type: SuperEncryptionType::LskfBound } |
| 776 | } |
| 777 | _ => Candidate { priority: 0, enc_type: SuperEncryptionType::None }, |
| 778 | }; |
| 779 | if t.priority > result.priority { |
| 780 | result = t; |
| 781 | } |
Ulyana Trafimovich | 229f2c0 | 2021-04-06 16:07:07 +0000 | [diff] [blame] | 782 | } |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 783 | result.enc_type |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 784 | } |
Hasini Gunasinghe | 3410f79 | 2020-09-14 17:55:21 +0000 | [diff] [blame] | 785 | |
Hasini Gunasinghe | b3715fb | 2021-02-26 20:34:45 +0000 | [diff] [blame] | 786 | /// Finds a matching auth token along with a timestamp token. |
| 787 | /// This method looks through auth-tokens cached by keystore which satisfy the given |
| 788 | /// authentication information (i.e. |secureUserId|). |
| 789 | /// The most recent matching auth token which has a |challenge| field which matches |
| 790 | /// the passed-in |challenge| parameter is returned. |
| 791 | /// In this case the |authTokenMaxAgeMillis| parameter is not used. |
| 792 | /// |
| 793 | /// Otherwise, the most recent matching auth token which is younger than |authTokenMaxAgeMillis| |
| 794 | /// is returned. |
| 795 | pub fn get_auth_tokens( |
| 796 | &self, |
| 797 | challenge: i64, |
| 798 | secure_user_id: i64, |
| 799 | auth_token_max_age_millis: i64, |
| 800 | ) -> Result<(HardwareAuthToken, TimeStampToken)> { |
| 801 | let auth_type = HardwareAuthenticatorType::ANY; |
| 802 | let sids: Vec<i64> = vec![secure_user_id]; |
| 803 | // Filter the matching auth tokens by challenge |
| 804 | let result = Self::find_auth_token(|hat: &AuthTokenEntry| { |
| 805 | (challenge == hat.challenge()) && hat.satisfies(&sids, auth_type) |
Matthew Maurer | d7815ca | 2021-05-06 21:58:45 -0700 | [diff] [blame] | 806 | }); |
Hasini Gunasinghe | b3715fb | 2021-02-26 20:34:45 +0000 | [diff] [blame] | 807 | |
| 808 | let auth_token = if let Some((auth_token_entry, _)) = result { |
| 809 | auth_token_entry.take_auth_token() |
| 810 | } else { |
| 811 | // Filter the matching auth tokens by age. |
| 812 | if auth_token_max_age_millis != 0 { |
Hasini Gunasinghe | 66a2460 | 2021-05-12 19:03:12 +0000 | [diff] [blame] | 813 | let now_in_millis = MonotonicRawTime::now(); |
Hasini Gunasinghe | b3715fb | 2021-02-26 20:34:45 +0000 | [diff] [blame] | 814 | let result = Self::find_auth_token(|auth_token_entry: &AuthTokenEntry| { |
| 815 | let token_valid = now_in_millis |
Hasini Gunasinghe | 66a2460 | 2021-05-12 19:03:12 +0000 | [diff] [blame] | 816 | .checked_sub(&auth_token_entry.time_received()) |
Hasini Gunasinghe | b3715fb | 2021-02-26 20:34:45 +0000 | [diff] [blame] | 817 | .map_or(false, |token_age_in_millis| { |
Hasini Gunasinghe | 66a2460 | 2021-05-12 19:03:12 +0000 | [diff] [blame] | 818 | auth_token_max_age_millis > token_age_in_millis.milliseconds() |
Hasini Gunasinghe | b3715fb | 2021-02-26 20:34:45 +0000 | [diff] [blame] | 819 | }); |
| 820 | token_valid && auth_token_entry.satisfies(&sids, auth_type) |
Matthew Maurer | d7815ca | 2021-05-06 21:58:45 -0700 | [diff] [blame] | 821 | }); |
Hasini Gunasinghe | b3715fb | 2021-02-26 20:34:45 +0000 | [diff] [blame] | 822 | |
| 823 | if let Some((auth_token_entry, _)) = result { |
| 824 | auth_token_entry.take_auth_token() |
| 825 | } else { |
| 826 | return Err(AuthzError::Rc(AuthzResponseCode::NO_AUTH_TOKEN_FOUND)) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 827 | .context(ks_err!("No auth token found.")); |
Hasini Gunasinghe | b3715fb | 2021-02-26 20:34:45 +0000 | [diff] [blame] | 828 | } |
| 829 | } else { |
Hasini Gunasinghe | 1ce7293 | 2021-09-14 15:43:19 +0000 | [diff] [blame] | 830 | return Err(AuthzError::Rc(AuthzResponseCode::NO_AUTH_TOKEN_FOUND)).context( |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 831 | ks_err!( |
| 832 | "No auth token found for \ |
| 833 | the given challenge and passed-in auth token max age is zero." |
Hasini Gunasinghe | 1ce7293 | 2021-09-14 15:43:19 +0000 | [diff] [blame] | 834 | ), |
| 835 | ); |
Hasini Gunasinghe | b3715fb | 2021-02-26 20:34:45 +0000 | [diff] [blame] | 836 | } |
| 837 | }; |
| 838 | // Wait and obtain the timestamp token from secure clock service. |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame^] | 839 | let tst = |
| 840 | get_timestamp_token(challenge).context(ks_err!("Error in getting timestamp token."))?; |
Hasini Gunasinghe | b3715fb | 2021-02-26 20:34:45 +0000 | [diff] [blame] | 841 | Ok((auth_token, tst)) |
| 842 | } |
Hasini Gunasinghe | 3410f79 | 2020-09-14 17:55:21 +0000 | [diff] [blame] | 843 | } |
| 844 | |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 845 | // TODO: Add tests to enforcement module (b/175578618). |