blob: 43147e86c2e283ea810ee602b46d26601e0377cc [file] [log] [blame]
Hasini Gunasinghe3410f792020-09-14 17:55:21 +00001// 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 Gunasinghe3410f792020-09-14 17:55:21 +000015//! This is the Keystore 2.0 Enforcements module.
16// TODO: more description to follow.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000017use crate::ks_err;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080018use crate::error::{map_binder_status, Error, ErrorCode};
19use crate::globals::{get_timestamp_service, ASYNC_TASK, DB, ENFORCEMENTS};
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000020use crate::key_parameter::{KeyParameter, KeyParameterValue};
Paul Crowley7a658392021-03-18 17:08:20 -070021use crate::{authorization::Error as AuthzError, super_key::SuperEncryptionType};
Paul Crowley44c02da2021-04-08 17:04:43 +000022use crate::{
23 database::{AuthTokenEntry, MonotonicRawTime},
24 globals::SUPER_KEY,
25};
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000026use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Hasini Gunasinghe5112c702020-11-09 22:13:25 +000027 Algorithm::Algorithm, ErrorCode::ErrorCode as Ec, HardwareAuthToken::HardwareAuthToken,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080028 HardwareAuthenticatorType::HardwareAuthenticatorType,
29 KeyParameter::KeyParameter as KmKeyParameter, KeyPurpose::KeyPurpose, Tag::Tag,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080030};
31use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070032 TimeStampToken::TimeStampToken,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000033};
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +000034use android_security_authorization::aidl::android::security::authorization::ResponseCode::ResponseCode as AuthzResponseCode;
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000035use android_system_keystore2::aidl::android::system::keystore2::{
Paul Crowley7a658392021-03-18 17:08:20 -070036 Domain::Domain, IKeystoreSecurityLevel::KEY_FLAG_AUTH_BOUND_WITHOUT_CRYPTOGRAPHIC_LSKF_BINDING,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000037 OperationChallenge::OperationChallenge,
38};
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000039use anyhow::{Context, Result};
Janis Danisevskisb1673db2021-02-08 18:11:57 -080040use std::{
41 collections::{HashMap, HashSet},
Paul Crowley7c57bf12021-02-02 16:26:57 -080042 sync::{
Paul Crowley7c57bf12021-02-02 16:26:57 -080043 mpsc::{channel, Receiver, Sender, TryRecvError},
44 Arc, Mutex, Weak,
45 },
46 time::SystemTime,
Janis Danisevskisb1673db2021-02-08 18:11:57 -080047};
Hasini Gunasinghe3410f792020-09-14 17:55:21 +000048
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080049#[derive(Debug)]
50enum AuthRequestState {
51 /// An outstanding per operation authorization request.
52 OpAuth,
53 /// An outstanding request for per operation authorization and secure timestamp.
Andrew Walbran7036c2b2023-07-21 17:25:45 +010054 TimeStampedOpAuth(Mutex<Receiver<Result<TimeStampToken, Error>>>),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080055 /// An outstanding request for a timestamp token.
Andrew Walbran7036c2b2023-07-21 17:25:45 +010056 TimeStamp(Mutex<Receiver<Result<TimeStampToken, Error>>>),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080057}
58
59#[derive(Debug)]
60struct AuthRequest {
61 state: AuthRequestState,
62 /// This need to be set to Some to fulfill a AuthRequestState::OpAuth or
63 /// AuthRequestState::TimeStampedOpAuth.
Janis Danisevskisbe1969e2021-04-20 15:16:24 -070064 hat: Mutex<Option<HardwareAuthToken>>,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080065}
66
67impl AuthRequest {
Janis Danisevskisbe1969e2021-04-20 15:16:24 -070068 fn op_auth() -> Arc<Self> {
69 Arc::new(Self { state: AuthRequestState::OpAuth, hat: Mutex::new(None) })
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080070 }
71
Janis Danisevskisbe1969e2021-04-20 15:16:24 -070072 fn timestamped_op_auth(receiver: Receiver<Result<TimeStampToken, Error>>) -> Arc<Self> {
73 Arc::new(Self {
Andrew Walbran7036c2b2023-07-21 17:25:45 +010074 state: AuthRequestState::TimeStampedOpAuth(Mutex::new(receiver)),
Janis Danisevskisbe1969e2021-04-20 15:16:24 -070075 hat: Mutex::new(None),
76 })
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080077 }
78
79 fn timestamp(
80 hat: HardwareAuthToken,
81 receiver: Receiver<Result<TimeStampToken, Error>>,
Janis Danisevskisbe1969e2021-04-20 15:16:24 -070082 ) -> Arc<Self> {
Andrew Walbran7036c2b2023-07-21 17:25:45 +010083 Arc::new(Self {
84 state: AuthRequestState::TimeStamp(Mutex::new(receiver)),
85 hat: Mutex::new(Some(hat)),
86 })
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080087 }
88
Janis Danisevskisbe1969e2021-04-20 15:16:24 -070089 fn add_auth_token(&self, hat: HardwareAuthToken) {
90 *self.hat.lock().unwrap() = Some(hat)
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080091 }
92
Janis Danisevskisbe1969e2021-04-20 15:16:24 -070093 fn get_auth_tokens(&self) -> Result<(HardwareAuthToken, Option<TimeStampToken>)> {
94 let hat = self
95 .hat
96 .lock()
97 .unwrap()
98 .take()
99 .ok_or(Error::Km(ErrorCode::KEY_USER_NOT_AUTHENTICATED))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000100 .context(ks_err!("No operation auth token received."))?;
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700101
102 let tst = match &self.state {
103 AuthRequestState::TimeStampedOpAuth(recv) | AuthRequestState::TimeStamp(recv) => {
Andrew Walbran7036c2b2023-07-21 17:25:45 +0100104 let result = recv
105 .lock()
106 .unwrap()
107 .recv()
108 .context("In get_auth_tokens: Sender disconnected.")?;
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000109 Some(result.context(ks_err!(
110 "Worker responded with error \
111 from generating timestamp token.",
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700112 ))?)
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800113 }
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700114 AuthRequestState::OpAuth => None,
115 };
116 Ok((hat, tst))
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800117 }
118}
119
120/// DeferredAuthState describes how auth tokens and timestamp tokens need to be provided when
121/// updating and finishing an operation.
122#[derive(Debug)]
123enum DeferredAuthState {
124 /// Used when an operation does not require further authorization.
125 NoAuthRequired,
126 /// Indicates that the operation requires an operation specific token. This means we have
127 /// to return an operation challenge to the client which should reward us with an
128 /// operation specific auth token. If it is not provided before the client calls update
129 /// or finish, the operation fails as not authorized.
130 OpAuthRequired,
131 /// Indicates that the operation requires a time stamp token. The auth token was already
132 /// loaded from the database, but it has to be accompanied by a time stamp token to inform
133 /// the target KM with a different clock about the time on the authenticators.
134 TimeStampRequired(HardwareAuthToken),
135 /// Indicates that both an operation bound auth token and a verification token are
136 /// before the operation can commence.
137 TimeStampedOpAuthRequired,
138 /// In this state the auth info is waiting for the deferred authorizations to come in.
139 /// We block on timestamp tokens, because we can always make progress on these requests.
140 /// The per-op auth tokens might never come, which means we fail if the client calls
141 /// update or finish before we got a per-op auth token.
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700142 Waiting(Arc<AuthRequest>),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800143 /// In this state we have gotten all of the required tokens, we just cache them to
144 /// be used when the operation progresses.
145 Token(HardwareAuthToken, Option<TimeStampToken>),
146}
147
148/// Auth info hold all of the authorization related information of an operation. It is stored
149/// in and owned by the operation. It is constructed by authorize_create and stays with the
150/// operation until it completes.
151#[derive(Debug)]
152pub struct AuthInfo {
153 state: DeferredAuthState,
Qi Wub9433b52020-12-01 14:52:46 +0800154 /// An optional key id required to update the usage count if the key usage is limited.
155 key_usage_limited: Option<i64>,
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800156 confirmation_token_receiver: Option<Arc<Mutex<Option<Receiver<Vec<u8>>>>>>,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800157}
158
159struct TokenReceiverMap {
160 /// The map maps an outstanding challenge to a TokenReceiver. If an incoming Hardware Auth
161 /// Token (HAT) has the map key in its challenge field, it gets passed to the TokenReceiver
162 /// and the entry is removed from the map. In the case where no HAT is received before the
163 /// corresponding operation gets dropped, the entry goes stale. So every time the cleanup
164 /// counter (second field in the tuple) turns 0, the map is cleaned from stale entries.
165 /// The cleanup counter is decremented every time a new receiver is added.
166 /// and reset to TokenReceiverMap::CLEANUP_PERIOD + 1 after each cleanup.
167 map_and_cleanup_counter: Mutex<(HashMap<i64, TokenReceiver>, u8)>,
168}
169
170impl Default for TokenReceiverMap {
171 fn default() -> Self {
172 Self { map_and_cleanup_counter: Mutex::new((HashMap::new(), Self::CLEANUP_PERIOD + 1)) }
173 }
174}
175
176impl TokenReceiverMap {
177 /// There is a chance that receivers may become stale because their operation is dropped
178 /// without ever being authorized. So occasionally we iterate through the map and throw
179 /// out obsolete entries.
180 /// This is the number of calls to add_receiver between cleanups.
181 const CLEANUP_PERIOD: u8 = 25;
182
183 pub fn add_auth_token(&self, hat: HardwareAuthToken) {
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700184 let recv = {
185 // Limit the scope of the mutex guard, so that it is not held while the auth token is
186 // added.
187 let mut map = self.map_and_cleanup_counter.lock().unwrap();
188 let (ref mut map, _) = *map;
189 map.remove_entry(&hat.challenge)
190 };
191
192 if let Some((_, recv)) = recv {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800193 recv.add_auth_token(hat);
194 }
195 }
196
197 pub fn add_receiver(&self, challenge: i64, recv: TokenReceiver) {
198 let mut map = self.map_and_cleanup_counter.lock().unwrap();
199 let (ref mut map, ref mut cleanup_counter) = *map;
200 map.insert(challenge, recv);
201
202 *cleanup_counter -= 1;
203 if *cleanup_counter == 0 {
204 map.retain(|_, v| !v.is_obsolete());
205 map.shrink_to_fit();
206 *cleanup_counter = Self::CLEANUP_PERIOD + 1;
207 }
208 }
209}
210
211#[derive(Debug)]
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700212struct TokenReceiver(Weak<AuthRequest>);
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800213
214impl TokenReceiver {
215 fn is_obsolete(&self) -> bool {
216 self.0.upgrade().is_none()
217 }
218
219 fn add_auth_token(&self, hat: HardwareAuthToken) {
220 if let Some(state_arc) = self.0.upgrade() {
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700221 state_arc.add_auth_token(hat);
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800222 }
223 }
224}
225
226fn get_timestamp_token(challenge: i64) -> Result<TimeStampToken, Error> {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700227 let dev = get_timestamp_service().expect(concat!(
228 "Secure Clock service must be present ",
229 "if TimeStampTokens are required."
230 ));
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800231 map_binder_status(dev.generateTimeStamp(challenge))
232}
233
234fn timestamp_token_request(challenge: i64, sender: Sender<Result<TimeStampToken, Error>>) {
235 if let Err(e) = sender.send(get_timestamp_token(challenge)) {
236 log::info!(
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000237 concat!("Receiver hung up ", "before timestamp token could be delivered. {:?}"),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800238 e
239 );
240 }
241}
242
243impl AuthInfo {
244 /// This function gets called after an operation was successfully created.
245 /// It makes all the preparations required, so that the operation has all the authentication
246 /// related artifacts to advance on update and finish.
247 pub fn finalize_create_authorization(&mut self, challenge: i64) -> Option<OperationChallenge> {
248 match &self.state {
249 DeferredAuthState::OpAuthRequired => {
250 let auth_request = AuthRequest::op_auth();
251 let token_receiver = TokenReceiver(Arc::downgrade(&auth_request));
252 ENFORCEMENTS.register_op_auth_receiver(challenge, token_receiver);
253
254 self.state = DeferredAuthState::Waiting(auth_request);
255 Some(OperationChallenge { challenge })
256 }
257 DeferredAuthState::TimeStampedOpAuthRequired => {
258 let (sender, receiver) = channel::<Result<TimeStampToken, Error>>();
259 let auth_request = AuthRequest::timestamped_op_auth(receiver);
260 let token_receiver = TokenReceiver(Arc::downgrade(&auth_request));
261 ENFORCEMENTS.register_op_auth_receiver(challenge, token_receiver);
262
Janis Danisevskis40f0e6b2021-02-10 15:48:44 -0800263 ASYNC_TASK.queue_hi(move |_| timestamp_token_request(challenge, sender));
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800264 self.state = DeferredAuthState::Waiting(auth_request);
265 Some(OperationChallenge { challenge })
266 }
267 DeferredAuthState::TimeStampRequired(hat) => {
268 let hat = (*hat).clone();
269 let (sender, receiver) = channel::<Result<TimeStampToken, Error>>();
270 let auth_request = AuthRequest::timestamp(hat, receiver);
Janis Danisevskis40f0e6b2021-02-10 15:48:44 -0800271 ASYNC_TASK.queue_hi(move |_| timestamp_token_request(challenge, sender));
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800272 self.state = DeferredAuthState::Waiting(auth_request);
273 None
274 }
275 _ => None,
276 }
277 }
278
Qi Wub9433b52020-12-01 14:52:46 +0800279 /// This function is the authorization hook called before operation update.
280 /// It returns the auth tokens required by the operation to commence update.
281 pub fn before_update(&mut self) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>)> {
282 self.get_auth_tokens()
283 }
284
285 /// This function is the authorization hook called before operation finish.
286 /// It returns the auth tokens required by the operation to commence finish.
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800287 /// The third token is a confirmation token.
288 pub fn before_finish(
289 &mut self,
290 ) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>, Option<Vec<u8>>)> {
291 let mut confirmation_token: Option<Vec<u8>> = None;
292 if let Some(ref confirmation_token_receiver) = self.confirmation_token_receiver {
293 let locked_receiver = confirmation_token_receiver.lock().unwrap();
294 if let Some(ref receiver) = *locked_receiver {
295 loop {
296 match receiver.try_recv() {
297 // As long as we get tokens we loop and discard all but the most
298 // recent one.
299 Ok(t) => confirmation_token = Some(t),
300 Err(TryRecvError::Empty) => break,
301 Err(TryRecvError::Disconnected) => {
302 log::error!(concat!(
303 "We got disconnected from the APC service, ",
304 "this should never happen."
305 ));
306 break;
307 }
308 }
309 }
310 }
311 }
312 self.get_auth_tokens().map(|(hat, tst)| (hat, tst, confirmation_token))
Qi Wub9433b52020-12-01 14:52:46 +0800313 }
314
315 /// This function is the authorization hook called after finish succeeded.
316 /// As of this writing it checks if the key was a limited use key. If so it updates the
317 /// use counter of the key in the database. When the use counter is depleted, the key gets
318 /// marked for deletion and the garbage collector is notified.
319 pub fn after_finish(&self) -> Result<()> {
320 if let Some(key_id) = self.key_usage_limited {
321 // On the last successful use, the key gets deleted. In this case we
322 // have to notify the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800323 DB.with(|db| {
324 db.borrow_mut()
325 .check_and_update_key_usage_count(key_id)
326 .context("Trying to update key usage count.")
327 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000328 .context(ks_err!())?;
Qi Wub9433b52020-12-01 14:52:46 +0800329 }
330 Ok(())
331 }
332
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800333 /// This function returns the auth tokens as needed by the ongoing operation or fails
334 /// with ErrorCode::KEY_USER_NOT_AUTHENTICATED. If this was called for the first time
335 /// after a deferred authorization was requested by finalize_create_authorization, this
336 /// function may block on the generation of a time stamp token. It then moves the
337 /// tokens into the DeferredAuthState::Token state for future use.
Qi Wub9433b52020-12-01 14:52:46 +0800338 fn get_auth_tokens(&mut self) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>)> {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800339 let deferred_tokens = if let DeferredAuthState::Waiting(ref auth_request) = self.state {
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700340 Some(auth_request.get_auth_tokens().context("In AuthInfo::get_auth_tokens.")?)
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800341 } else {
342 None
343 };
344
345 if let Some((hat, tst)) = deferred_tokens {
346 self.state = DeferredAuthState::Token(hat, tst);
347 }
348
349 match &self.state {
350 DeferredAuthState::NoAuthRequired => Ok((None, None)),
351 DeferredAuthState::Token(hat, tst) => Ok((Some((*hat).clone()), (*tst).clone())),
352 DeferredAuthState::OpAuthRequired
353 | DeferredAuthState::TimeStampedOpAuthRequired
354 | DeferredAuthState::TimeStampRequired(_) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000355 Err(Error::Km(ErrorCode::KEY_USER_NOT_AUTHENTICATED)).context(ks_err!(
356 "No operation auth token requested??? \
357 This should not happen."
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800358 ))
359 }
360 // This should not be reachable, because it should have been handled above.
361 DeferredAuthState::Waiting(_) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000362 Err(Error::sys()).context(ks_err!("AuthInfo::get_auth_tokens: Cannot be reached.",))
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800363 }
364 }
365 }
366}
367
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000368/// Enforcements data structure
Paul Crowley7c57bf12021-02-02 16:26:57 -0800369#[derive(Default)]
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000370pub struct Enforcements {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800371 /// This hash set contains the user ids for whom the device is currently unlocked. If a user id
372 /// is not in the set, it implies that the device is locked for the user.
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000373 device_unlocked_set: Mutex<HashSet<i32>>,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800374 /// This field maps outstanding auth challenges to their operations. When an auth token
375 /// with the right challenge is received it is passed to the map using
376 /// TokenReceiverMap::add_auth_token() which removes the entry from the map. If an entry goes
377 /// stale, because the operation gets dropped before an auth token is received, the map
378 /// is cleaned up in regular intervals.
379 op_auth_map: TokenReceiverMap,
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800380 /// The enforcement module will try to get a confirmation token from this channel whenever
381 /// an operation that requires confirmation finishes.
382 confirmation_token_receiver: Arc<Mutex<Option<Receiver<Vec<u8>>>>>,
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000383}
384
385impl Enforcements {
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800386 /// Install the confirmation token receiver. The enforcement module will try to get a
387 /// confirmation token from this channel whenever an operation that requires confirmation
388 /// finishes.
389 pub fn install_confirmation_token_receiver(
390 &self,
391 confirmation_token_receiver: Receiver<Vec<u8>>,
392 ) {
393 *self.confirmation_token_receiver.lock().unwrap() = Some(confirmation_token_receiver);
394 }
395
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000396 /// Checks if a create call is authorized, given key parameters and operation parameters.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800397 /// It returns an optional immediate auth token which can be presented to begin, and an
398 /// AuthInfo object which stays with the authorized operation and is used to obtain
399 /// auth tokens and timestamp tokens as required by the operation.
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000400 /// With regard to auth tokens, the following steps are taken:
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800401 ///
402 /// If no key parameters are given (typically when the client is self managed
403 /// (see Domain.Blob)) nothing is enforced.
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000404 /// If the key is time-bound, find a matching auth token from the database.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800405 /// If the above step is successful, and if requires_timestamp is given, the returned
406 /// AuthInfo will provide a Timestamp token as appropriate.
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000407 pub fn authorize_create(
408 &self,
409 purpose: KeyPurpose,
Qi Wub9433b52020-12-01 14:52:46 +0800410 key_properties: Option<&(i64, Vec<KeyParameter>)>,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800411 op_params: &[KmKeyParameter],
412 requires_timestamp: bool,
413 ) -> Result<(Option<HardwareAuthToken>, AuthInfo)> {
Qi Wub9433b52020-12-01 14:52:46 +0800414 let (key_id, key_params) = match key_properties {
415 Some((key_id, key_params)) => (*key_id, key_params),
416 None => {
417 return Ok((
418 None,
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800419 AuthInfo {
420 state: DeferredAuthState::NoAuthRequired,
421 key_usage_limited: None,
422 confirmation_token_receiver: None,
423 },
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000424 ));
Qi Wub9433b52020-12-01 14:52:46 +0800425 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800426 };
427
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000428 match purpose {
429 // Allow SIGN, DECRYPT for both symmetric and asymmetric keys.
430 KeyPurpose::SIGN | KeyPurpose::DECRYPT => {}
431 // Rule out WRAP_KEY purpose
432 KeyPurpose::WRAP_KEY => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800433 return Err(Error::Km(Ec::INCOMPATIBLE_PURPOSE))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000434 .context(ks_err!("WRAP_KEY purpose is not allowed here.",));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000435 }
Bram Bonnéa6b83822021-01-20 11:10:05 +0100436 // Allow AGREE_KEY for EC keys only.
437 KeyPurpose::AGREE_KEY => {
438 for kp in key_params.iter() {
439 if kp.get_tag() == Tag::ALGORITHM
440 && *kp.key_parameter_value() != KeyParameterValue::Algorithm(Algorithm::EC)
441 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000442 return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE))
443 .context(ks_err!("key agreement is only supported for EC keys.",));
Bram Bonnéa6b83822021-01-20 11:10:05 +0100444 }
445 }
446 }
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000447 KeyPurpose::VERIFY | KeyPurpose::ENCRYPT => {
448 // We do not support ENCRYPT and VERIFY (the remaining two options of purpose) for
449 // asymmetric keys.
450 for kp in key_params.iter() {
451 match *kp.key_parameter_value() {
452 KeyParameterValue::Algorithm(Algorithm::RSA)
453 | KeyParameterValue::Algorithm(Algorithm::EC) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000454 return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE)).context(ks_err!(
455 "public operations on asymmetric keys are \
456 not supported."
457 ));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000458 }
459 _ => {}
460 }
461 }
462 }
463 _ => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800464 return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000465 .context(ks_err!("authorize_create: specified purpose is not supported."));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000466 }
467 }
468 // The following variables are to record information from key parameters to be used in
469 // enforcements, when two or more such pieces of information are required for enforcements.
470 // There is only one additional variable than what legacy keystore has, but this helps
471 // reduce the number of for loops on key parameters from 3 to 1, compared to legacy keystore
472 let mut key_purpose_authorized: bool = false;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000473 let mut user_auth_type: Option<HardwareAuthenticatorType> = None;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000474 let mut no_auth_required: bool = false;
475 let mut caller_nonce_allowed = false;
476 let mut user_id: i32 = -1;
477 let mut user_secure_ids = Vec::<i64>::new();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000478 let mut key_time_out: Option<i64> = None;
479 let mut allow_while_on_body = false;
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000480 let mut unlocked_device_required = false;
Qi Wub9433b52020-12-01 14:52:46 +0800481 let mut key_usage_limited: Option<i64> = None;
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800482 let mut confirmation_token_receiver: Option<Arc<Mutex<Option<Receiver<Vec<u8>>>>>> = None;
Paul Crowley7c57bf12021-02-02 16:26:57 -0800483 let mut max_boot_level: Option<i32> = None;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000484
485 // iterate through key parameters, recording information we need for authorization
486 // enforcements later, or enforcing authorizations in place, where applicable
487 for key_param in key_params.iter() {
488 match key_param.key_parameter_value() {
489 KeyParameterValue::NoAuthRequired => {
490 no_auth_required = true;
491 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000492 KeyParameterValue::AuthTimeout(t) => {
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000493 key_time_out = Some(*t as i64);
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000494 }
495 KeyParameterValue::HardwareAuthenticatorType(a) => {
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000496 user_auth_type = Some(*a);
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000497 }
498 KeyParameterValue::KeyPurpose(p) => {
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800499 // The following check has the effect of key_params.contains(purpose)
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000500 // Also, authorizing purpose can not be completed here, if there can be multiple
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800501 // key parameters for KeyPurpose.
502 key_purpose_authorized = key_purpose_authorized || *p == purpose;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000503 }
504 KeyParameterValue::CallerNonce => {
505 caller_nonce_allowed = true;
506 }
507 KeyParameterValue::ActiveDateTime(a) => {
508 if !Enforcements::is_given_time_passed(*a, true) {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800509 return Err(Error::Km(Ec::KEY_NOT_YET_VALID))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000510 .context(ks_err!("key is not yet active."));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000511 }
512 }
513 KeyParameterValue::OriginationExpireDateTime(o) => {
514 if (purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN)
515 && Enforcements::is_given_time_passed(*o, false)
516 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000517 return Err(Error::Km(Ec::KEY_EXPIRED)).context(ks_err!("key is expired."));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000518 }
519 }
520 KeyParameterValue::UsageExpireDateTime(u) => {
521 if (purpose == KeyPurpose::DECRYPT || purpose == KeyPurpose::VERIFY)
522 && Enforcements::is_given_time_passed(*u, false)
523 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000524 return Err(Error::Km(Ec::KEY_EXPIRED)).context(ks_err!("key is expired."));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000525 }
526 }
527 KeyParameterValue::UserSecureID(s) => {
528 user_secure_ids.push(*s);
529 }
530 KeyParameterValue::UserID(u) => {
531 user_id = *u;
532 }
533 KeyParameterValue::UnlockedDeviceRequired => {
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000534 unlocked_device_required = true;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000535 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000536 KeyParameterValue::AllowWhileOnBody => {
537 allow_while_on_body = true;
538 }
Qi Wub9433b52020-12-01 14:52:46 +0800539 KeyParameterValue::UsageCountLimit(_) => {
540 // We don't examine the limit here because this is enforced on finish.
541 // Instead, we store the key_id so that finish can look up the key
542 // in the database again and check and update the counter.
543 key_usage_limited = Some(key_id);
544 }
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800545 KeyParameterValue::TrustedConfirmationRequired => {
546 confirmation_token_receiver = Some(self.confirmation_token_receiver.clone());
547 }
Paul Crowley7c57bf12021-02-02 16:26:57 -0800548 KeyParameterValue::MaxBootLevel(level) => {
549 max_boot_level = Some(*level);
550 }
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000551 // NOTE: as per offline discussion, sanitizing key parameters and rejecting
552 // create operation if any non-allowed tags are present, is not done in
553 // authorize_create (unlike in legacy keystore where AuthorizeBegin is rejected if
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800554 // a subset of non-allowed tags are present). Because sanitizing key parameters
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000555 // should have been done during generate/import key, by KeyMint.
556 _ => { /*Do nothing on all the other key parameters, as in legacy keystore*/ }
557 }
558 }
559
560 // authorize the purpose
561 if !key_purpose_authorized {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800562 return Err(Error::Km(Ec::INCOMPATIBLE_PURPOSE))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000563 .context(ks_err!("the purpose is not authorized."));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000564 }
565
566 // if both NO_AUTH_REQUIRED and USER_SECURE_ID tags are present, return error
567 if !user_secure_ids.is_empty() && no_auth_required {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000568 return Err(Error::Km(Ec::INVALID_KEY_BLOB))
569 .context(ks_err!("key has both NO_AUTH_REQUIRED and USER_SECURE_ID tags."));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000570 }
571
572 // if either of auth_type or secure_id is present and the other is not present, return error
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000573 if (user_auth_type.is_some() && user_secure_ids.is_empty())
574 || (user_auth_type.is_none() && !user_secure_ids.is_empty())
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000575 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000576 return Err(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED)).context(ks_err!(
577 "Auth required, but either auth type or secure ids \
578 are not present."
579 ));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000580 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800581
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000582 // validate caller nonce for origination purposes
583 if (purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN)
584 && !caller_nonce_allowed
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800585 && op_params.iter().any(|kp| kp.tag == Tag::NONCE)
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000586 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000587 return Err(Error::Km(Ec::CALLER_NONCE_PROHIBITED))
588 .context(ks_err!("NONCE is present, although CALLER_NONCE is not present"));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000589 }
590
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000591 if unlocked_device_required {
592 // check the device locked status. If locked, operations on the key are not
593 // allowed.
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000594 if self.is_device_locked(user_id) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000595 return Err(Error::Km(Ec::DEVICE_LOCKED)).context(ks_err!("device is locked."));
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000596 }
597 }
598
Paul Crowley7c57bf12021-02-02 16:26:57 -0800599 if let Some(level) = max_boot_level {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800600 if !SUPER_KEY.read().unwrap().level_accessible(level) {
Paul Crowley7c57bf12021-02-02 16:26:57 -0800601 return Err(Error::Km(Ec::BOOT_LEVEL_EXCEEDED))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000602 .context(ks_err!("boot level is too late."));
Paul Crowley7c57bf12021-02-02 16:26:57 -0800603 }
604 }
605
Eric Biggersb0478cf2023-10-27 03:55:29 +0000606 if android_security_flags::fix_unlocked_device_required_keys() {
607 let (hat, state) = if user_secure_ids.is_empty() {
608 (None, DeferredAuthState::NoAuthRequired)
609 } else if let Some(key_time_out) = key_time_out {
610 let (hat, last_off_body) =
611 Self::find_auth_token(|hat: &AuthTokenEntry| match user_auth_type {
612 Some(auth_type) => hat.satisfies(&user_secure_ids, auth_type),
613 None => false, // not reachable due to earlier check
614 })
615 .ok_or(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
616 .context(ks_err!("No suitable auth token found."))?;
617 let now = MonotonicRawTime::now();
618 let token_age = now
619 .checked_sub(&hat.time_received())
620 .ok_or_else(Error::sys)
621 .context(ks_err!(
622 "Overflow while computing Auth token validity. \
623 Validity cannot be established."
624 ))?;
625
626 let on_body_extended = allow_while_on_body && last_off_body < hat.time_received();
627
628 if token_age.seconds() > key_time_out && !on_body_extended {
629 return Err(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
630 .context(ks_err!("matching auth token is expired."));
631 }
632 let state = if requires_timestamp {
633 DeferredAuthState::TimeStampRequired(hat.auth_token().clone())
634 } else {
635 DeferredAuthState::NoAuthRequired
636 };
637 (Some(hat.take_auth_token()), state)
638 } else {
639 (None, DeferredAuthState::OpAuthRequired)
640 };
641 return Ok((hat, AuthInfo { state, key_usage_limited, confirmation_token_receiver }));
642 }
643
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800644 if !unlocked_device_required && no_auth_required {
Qi Wub9433b52020-12-01 14:52:46 +0800645 return Ok((
646 None,
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800647 AuthInfo {
648 state: DeferredAuthState::NoAuthRequired,
649 key_usage_limited,
650 confirmation_token_receiver,
651 },
Qi Wub9433b52020-12-01 14:52:46 +0800652 ));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000653 }
654
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800655 let has_sids = !user_secure_ids.is_empty();
656
657 let timeout_bound = key_time_out.is_some() && has_sids;
658
659 let per_op_bound = key_time_out.is_none() && has_sids;
660
661 let need_auth_token = timeout_bound || unlocked_device_required;
662
663 let hat_and_last_off_body = if need_auth_token {
664 let hat_and_last_off_body = Self::find_auth_token(|hat: &AuthTokenEntry| {
Seth Moore653eca52021-11-19 16:52:19 -0800665 if let (Some(auth_type), true) = (user_auth_type, timeout_bound) {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800666 hat.satisfies(&user_secure_ids, auth_type)
667 } else {
668 unlocked_device_required
669 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700670 });
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800671 Some(
672 hat_and_last_off_body
673 .ok_or(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000674 .context(ks_err!("No suitable auth token found."))?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800675 )
676 } else {
677 None
678 };
679
680 // Now check the validity of the auth token if the key is timeout bound.
681 let hat = match (hat_and_last_off_body, key_time_out) {
682 (Some((hat, last_off_body)), Some(key_time_out)) => {
683 let now = MonotonicRawTime::now();
684 let token_age = now
685 .checked_sub(&hat.time_received())
686 .ok_or_else(Error::sys)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000687 .context(ks_err!(
688 "Overflow while computing Auth token validity. \
689 Validity cannot be established."
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800690 ))?;
691
692 let on_body_extended = allow_while_on_body && last_off_body < hat.time_received();
693
694 if token_age.seconds() > key_time_out && !on_body_extended {
695 return Err(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000696 .context(ks_err!("matching auth token is expired."));
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800697 }
698 Some(hat)
699 }
700 (Some((hat, _)), None) => Some(hat),
701 // If timeout_bound is true, above code must have retrieved a HAT or returned with
702 // KEY_USER_NOT_AUTHENTICATED. This arm should not be reachable.
703 (None, Some(_)) => panic!("Logical error."),
704 _ => None,
705 };
706
707 Ok(match (hat, requires_timestamp, per_op_bound) {
708 // Per-op-bound and Some(hat) can only happen if we are both per-op bound and unlocked
709 // device required. In addition, this KM instance needs a timestamp token.
710 // So the HAT cannot be presented on create. So on update/finish we present both
711 // an per-op-bound auth token and a timestamp token.
712 (Some(_), true, true) => (None, DeferredAuthState::TimeStampedOpAuthRequired),
Hasini Gunasinghee093b552021-04-30 20:05:31 +0000713 (Some(hat), true, false) => (
714 Some(hat.auth_token().clone()),
715 DeferredAuthState::TimeStampRequired(hat.take_auth_token()),
716 ),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800717 (Some(hat), false, true) => {
718 (Some(hat.take_auth_token()), DeferredAuthState::OpAuthRequired)
719 }
720 (Some(hat), false, false) => {
721 (Some(hat.take_auth_token()), DeferredAuthState::NoAuthRequired)
722 }
723 (None, _, true) => (None, DeferredAuthState::OpAuthRequired),
724 (None, _, false) => (None, DeferredAuthState::NoAuthRequired),
725 })
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800726 .map(|(hat, state)| {
727 (hat, AuthInfo { state, key_usage_limited, confirmation_token_receiver })
728 })
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800729 }
730
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700731 fn find_auth_token<F>(p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800732 where
733 F: Fn(&AuthTokenEntry) -> bool,
734 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700735 DB.with(|db| db.borrow().find_auth_token_entry(p))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000736 }
737
738 /// Checks if the time now since epoch is greater than (or equal, if is_given_time_inclusive is
739 /// set) the given time (in milliseconds)
740 fn is_given_time_passed(given_time: i64, is_given_time_inclusive: bool) -> bool {
741 let duration_since_epoch = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH);
742
743 let time_since_epoch = match duration_since_epoch {
744 Ok(duration) => duration.as_millis(),
745 Err(_) => return false,
746 };
747
748 if is_given_time_inclusive {
749 time_since_epoch >= (given_time as u128)
750 } else {
751 time_since_epoch > (given_time as u128)
752 }
753 }
754
755 /// Check if the device is locked for the given user. If there's no entry yet for the user,
756 /// we assume that the device is locked
757 fn is_device_locked(&self, user_id: i32) -> bool {
758 // unwrap here because there's no way this mutex guard can be poisoned and
759 // because there's no way to recover, even if it is poisoned.
760 let set = self.device_unlocked_set.lock().unwrap();
761 !set.contains(&user_id)
762 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000763
764 /// Sets the device locked status for the user. This method is called externally.
765 pub fn set_device_locked(&self, user_id: i32, device_locked_status: bool) {
766 // unwrap here because there's no way this mutex guard can be poisoned and
767 // because there's no way to recover, even if it is poisoned.
768 let mut set = self.device_unlocked_set.lock().unwrap();
769 if device_locked_status {
770 set.remove(&user_id);
771 } else {
772 set.insert(user_id);
773 }
774 }
775
776 /// Add this auth token to the database.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800777 /// Then present the auth token to the op auth map. If an operation is waiting for this
778 /// auth token this fulfills the request and removes the receiver from the map.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700779 pub fn add_auth_token(&self, hat: HardwareAuthToken) {
780 DB.with(|db| db.borrow_mut().insert_auth_token(&hat));
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800781 self.op_auth_map.add_auth_token(hat);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000782 }
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000783
784 /// This allows adding an entry to the op_auth_map, indexed by the operation challenge.
785 /// This is to be called by create_operation, once it has received the operation challenge
786 /// from keymint for an operation whose authorization decision is OpAuthRequired, as signalled
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800787 /// by the DeferredAuthState.
788 fn register_op_auth_receiver(&self, challenge: i64, recv: TokenReceiver) {
789 self.op_auth_map.add_receiver(challenge, recv);
Hasini Gunasinghef04d07a2020-11-25 22:41:35 +0000790 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000791
792 /// Given the set of key parameters and flags, check if super encryption is required.
Paul Crowley7a658392021-03-18 17:08:20 -0700793 pub fn super_encryption_required(
794 domain: &Domain,
795 key_parameters: &[KeyParameter],
796 flags: Option<i32>,
797 ) -> SuperEncryptionType {
Paul Crowley7a658392021-03-18 17:08:20 -0700798 if let Some(flags) = flags {
799 if (flags & KEY_FLAG_AUTH_BOUND_WITHOUT_CRYPTOGRAPHIC_LSKF_BINDING) != 0 {
800 return SuperEncryptionType::None;
801 }
802 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000803 // Each answer has a priority, numerically largest priority wins.
804 struct Candidate {
805 priority: u32,
806 enc_type: SuperEncryptionType,
Paul Crowley7a658392021-03-18 17:08:20 -0700807 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000808 let mut result = Candidate { priority: 0, enc_type: SuperEncryptionType::None };
809 for kp in key_parameters {
810 let t = match kp.key_parameter_value() {
811 KeyParameterValue::MaxBootLevel(level) => {
812 Candidate { priority: 3, enc_type: SuperEncryptionType::BootLevel(*level) }
813 }
814 KeyParameterValue::UnlockedDeviceRequired if *domain == Domain::APP => {
Eric Biggersb1f641d2023-10-18 01:54:18 +0000815 Candidate { priority: 2, enc_type: SuperEncryptionType::UnlockedDeviceRequired }
Paul Crowley44c02da2021-04-08 17:04:43 +0000816 }
817 KeyParameterValue::UserSecureID(_) if *domain == Domain::APP => {
Eric Biggers673d34a2023-10-18 01:54:18 +0000818 Candidate { priority: 1, enc_type: SuperEncryptionType::AfterFirstUnlock }
Paul Crowley44c02da2021-04-08 17:04:43 +0000819 }
820 _ => Candidate { priority: 0, enc_type: SuperEncryptionType::None },
821 };
822 if t.priority > result.priority {
823 result = t;
824 }
Ulyana Trafimovich229f2c02021-04-06 16:07:07 +0000825 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000826 result.enc_type
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000827 }
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000828
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000829 /// Finds a matching auth token along with a timestamp token.
830 /// This method looks through auth-tokens cached by keystore which satisfy the given
831 /// authentication information (i.e. |secureUserId|).
832 /// The most recent matching auth token which has a |challenge| field which matches
833 /// the passed-in |challenge| parameter is returned.
834 /// In this case the |authTokenMaxAgeMillis| parameter is not used.
835 ///
836 /// Otherwise, the most recent matching auth token which is younger than |authTokenMaxAgeMillis|
837 /// is returned.
838 pub fn get_auth_tokens(
839 &self,
840 challenge: i64,
841 secure_user_id: i64,
842 auth_token_max_age_millis: i64,
843 ) -> Result<(HardwareAuthToken, TimeStampToken)> {
844 let auth_type = HardwareAuthenticatorType::ANY;
845 let sids: Vec<i64> = vec![secure_user_id];
846 // Filter the matching auth tokens by challenge
847 let result = Self::find_auth_token(|hat: &AuthTokenEntry| {
848 (challenge == hat.challenge()) && hat.satisfies(&sids, auth_type)
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700849 });
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000850
851 let auth_token = if let Some((auth_token_entry, _)) = result {
852 auth_token_entry.take_auth_token()
853 } else {
854 // Filter the matching auth tokens by age.
855 if auth_token_max_age_millis != 0 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000856 let now_in_millis = MonotonicRawTime::now();
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000857 let result = Self::find_auth_token(|auth_token_entry: &AuthTokenEntry| {
858 let token_valid = now_in_millis
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000859 .checked_sub(&auth_token_entry.time_received())
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000860 .map_or(false, |token_age_in_millis| {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000861 auth_token_max_age_millis > token_age_in_millis.milliseconds()
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000862 });
863 token_valid && auth_token_entry.satisfies(&sids, auth_type)
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700864 });
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000865
866 if let Some((auth_token_entry, _)) = result {
867 auth_token_entry.take_auth_token()
868 } else {
869 return Err(AuthzError::Rc(AuthzResponseCode::NO_AUTH_TOKEN_FOUND))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000870 .context(ks_err!("No auth token found."));
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000871 }
872 } else {
Hasini Gunasinghe1ce72932021-09-14 15:43:19 +0000873 return Err(AuthzError::Rc(AuthzResponseCode::NO_AUTH_TOKEN_FOUND)).context(
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000874 ks_err!(
875 "No auth token found for \
876 the given challenge and passed-in auth token max age is zero."
Hasini Gunasinghe1ce72932021-09-14 15:43:19 +0000877 ),
878 );
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000879 }
880 };
881 // Wait and obtain the timestamp token from secure clock service.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000882 let tst =
883 get_timestamp_token(challenge).context(ks_err!("Error in getting timestamp token."))?;
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000884 Ok((auth_token, tst))
885 }
James Willcoxd215da82023-10-03 21:31:31 +0000886
887 /// Finds the most recent received time for an auth token that matches the given secure user id and authenticator
888 pub fn get_last_auth_time(
889 &self,
890 secure_user_id: i64,
891 auth_type: HardwareAuthenticatorType,
892 ) -> Option<MonotonicRawTime> {
893 let sids: Vec<i64> = vec![secure_user_id];
894
895 let result =
896 Self::find_auth_token(|entry: &AuthTokenEntry| entry.satisfies(&sids, auth_type));
897
898 if let Some((auth_token_entry, _)) = result {
899 Some(auth_token_entry.time_received())
900 } else {
901 None
902 }
903 }
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000904}
905
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000906// TODO: Add tests to enforcement module (b/175578618).