blob: 8d5e9855a1d3988e9bed6a2fe3fc51aa71080851 [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.
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)]
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
Janis Danisevskisbe1969e2021-04-20 15:16:24 -070067unsafe impl Sync for AuthRequest {}
68
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080069impl AuthRequest {
Janis Danisevskisbe1969e2021-04-20 15:16:24 -070070 fn op_auth() -> Arc<Self> {
71 Arc::new(Self { state: AuthRequestState::OpAuth, hat: Mutex::new(None) })
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080072 }
73
Janis Danisevskisbe1969e2021-04-20 15:16:24 -070074 fn timestamped_op_auth(receiver: Receiver<Result<TimeStampToken, Error>>) -> Arc<Self> {
75 Arc::new(Self {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080076 state: AuthRequestState::TimeStampedOpAuth(receiver),
Janis Danisevskisbe1969e2021-04-20 15:16:24 -070077 hat: Mutex::new(None),
78 })
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080079 }
80
81 fn timestamp(
82 hat: HardwareAuthToken,
83 receiver: Receiver<Result<TimeStampToken, Error>>,
Janis Danisevskisbe1969e2021-04-20 15:16:24 -070084 ) -> Arc<Self> {
85 Arc::new(Self { state: AuthRequestState::TimeStamp(receiver), hat: Mutex::new(Some(hat)) })
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080086 }
87
Janis Danisevskisbe1969e2021-04-20 15:16:24 -070088 fn add_auth_token(&self, hat: HardwareAuthToken) {
89 *self.hat.lock().unwrap() = Some(hat)
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080090 }
91
Janis Danisevskisbe1969e2021-04-20 15:16:24 -070092 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 Johnson9da2e1c2022-09-19 12:39:01 +000099 .context(ks_err!("No operation auth token received."))?;
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700100
101 let tst = match &self.state {
102 AuthRequestState::TimeStampedOpAuth(recv) | AuthRequestState::TimeStamp(recv) => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800103 let result = recv.recv().context("In get_auth_tokens: Sender disconnected.")?;
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000104 Some(result.context(ks_err!(
105 "Worker responded with error \
106 from generating timestamp token.",
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700107 ))?)
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800108 }
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700109 AuthRequestState::OpAuth => None,
110 };
111 Ok((hat, tst))
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800112 }
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)]
118enum 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 Danisevskisbe1969e2021-04-20 15:16:24 -0700137 Waiting(Arc<AuthRequest>),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800138 /// 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)]
147pub struct AuthInfo {
148 state: DeferredAuthState,
Qi Wub9433b52020-12-01 14:52:46 +0800149 /// An optional key id required to update the usage count if the key usage is limited.
150 key_usage_limited: Option<i64>,
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800151 confirmation_token_receiver: Option<Arc<Mutex<Option<Receiver<Vec<u8>>>>>>,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800152}
153
154struct 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
165impl Default for TokenReceiverMap {
166 fn default() -> Self {
167 Self { map_and_cleanup_counter: Mutex::new((HashMap::new(), Self::CLEANUP_PERIOD + 1)) }
168 }
169}
170
171impl 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 Danisevskisbe1969e2021-04-20 15:16:24 -0700179 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 Danisevskis5ed8c532021-01-11 14:19:42 -0800188 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 Danisevskisbe1969e2021-04-20 15:16:24 -0700207struct TokenReceiver(Weak<AuthRequest>);
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800208
209impl 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 Danisevskisbe1969e2021-04-20 15:16:24 -0700216 state_arc.add_auth_token(hat);
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800217 }
218 }
219}
220
221fn get_timestamp_token(challenge: i64) -> Result<TimeStampToken, Error> {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700222 let dev = get_timestamp_service().expect(concat!(
223 "Secure Clock service must be present ",
224 "if TimeStampTokens are required."
225 ));
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800226 map_binder_status(dev.generateTimeStamp(challenge))
227}
228
229fn 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 Johnson9da2e1c2022-09-19 12:39:01 +0000232 concat!("Receiver hung up ", "before timestamp token could be delivered. {:?}"),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800233 e
234 );
235 }
236}
237
238impl 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 Danisevskis40f0e6b2021-02-10 15:48:44 -0800258 ASYNC_TASK.queue_hi(move |_| timestamp_token_request(challenge, sender));
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800259 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 Danisevskis40f0e6b2021-02-10 15:48:44 -0800266 ASYNC_TASK.queue_hi(move |_| timestamp_token_request(challenge, sender));
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800267 self.state = DeferredAuthState::Waiting(auth_request);
268 None
269 }
270 _ => None,
271 }
272 }
273
Qi Wub9433b52020-12-01 14:52:46 +0800274 /// 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 Danisevskisb1673db2021-02-08 18:11:57 -0800282 /// 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 Wub9433b52020-12-01 14:52:46 +0800308 }
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 Danisevskis7e8b4622021-02-13 10:01:59 -0800318 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 Johnson9da2e1c2022-09-19 12:39:01 +0000323 .context(ks_err!())?;
Qi Wub9433b52020-12-01 14:52:46 +0800324 }
325 Ok(())
326 }
327
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800328 /// 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 Wub9433b52020-12-01 14:52:46 +0800333 fn get_auth_tokens(&mut self) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>)> {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800334 let deferred_tokens = if let DeferredAuthState::Waiting(ref auth_request) = self.state {
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700335 Some(auth_request.get_auth_tokens().context("In AuthInfo::get_auth_tokens.")?)
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800336 } 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 Johnson9da2e1c2022-09-19 12:39:01 +0000350 Err(Error::Km(ErrorCode::KEY_USER_NOT_AUTHENTICATED)).context(ks_err!(
351 "No operation auth token requested??? \
352 This should not happen."
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800353 ))
354 }
355 // This should not be reachable, because it should have been handled above.
356 DeferredAuthState::Waiting(_) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000357 Err(Error::sys()).context(ks_err!("AuthInfo::get_auth_tokens: Cannot be reached.",))
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800358 }
359 }
360 }
361}
362
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000363/// Enforcements data structure
Paul Crowley7c57bf12021-02-02 16:26:57 -0800364#[derive(Default)]
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000365pub struct Enforcements {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800366 /// 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 Gunasinghe3410f792020-09-14 17:55:21 +0000368 device_unlocked_set: Mutex<HashSet<i32>>,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800369 /// 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 Danisevskisb1673db2021-02-08 18:11:57 -0800375 /// 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 Gunasinghe3410f792020-09-14 17:55:21 +0000378}
379
380impl Enforcements {
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800381 /// 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 Gunasinghe5112c702020-11-09 22:13:25 +0000391 /// Checks if a create call is authorized, given key parameters and operation parameters.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800392 /// 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 Gunasinghe5112c702020-11-09 22:13:25 +0000395 /// With regard to auth tokens, the following steps are taken:
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800396 ///
397 /// If no key parameters are given (typically when the client is self managed
398 /// (see Domain.Blob)) nothing is enforced.
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000399 /// If the key is time-bound, find a matching auth token from the database.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800400 /// If the above step is successful, and if requires_timestamp is given, the returned
401 /// AuthInfo will provide a Timestamp token as appropriate.
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000402 pub fn authorize_create(
403 &self,
404 purpose: KeyPurpose,
Qi Wub9433b52020-12-01 14:52:46 +0800405 key_properties: Option<&(i64, Vec<KeyParameter>)>,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800406 op_params: &[KmKeyParameter],
407 requires_timestamp: bool,
408 ) -> Result<(Option<HardwareAuthToken>, AuthInfo)> {
Qi Wub9433b52020-12-01 14:52:46 +0800409 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 Danisevskisb1673db2021-02-08 18:11:57 -0800414 AuthInfo {
415 state: DeferredAuthState::NoAuthRequired,
416 key_usage_limited: None,
417 confirmation_token_receiver: None,
418 },
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000419 ));
Qi Wub9433b52020-12-01 14:52:46 +0800420 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800421 };
422
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000423 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 Danisevskis5ed8c532021-01-11 14:19:42 -0800428 return Err(Error::Km(Ec::INCOMPATIBLE_PURPOSE))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000429 .context(ks_err!("WRAP_KEY purpose is not allowed here.",));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000430 }
Bram Bonnéa6b83822021-01-20 11:10:05 +0100431 // 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 Johnson9da2e1c2022-09-19 12:39:01 +0000437 return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE))
438 .context(ks_err!("key agreement is only supported for EC keys.",));
Bram Bonnéa6b83822021-01-20 11:10:05 +0100439 }
440 }
441 }
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000442 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 Johnson9da2e1c2022-09-19 12:39:01 +0000449 return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE)).context(ks_err!(
450 "public operations on asymmetric keys are \
451 not supported."
452 ));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000453 }
454 _ => {}
455 }
456 }
457 }
458 _ => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800459 return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000460 .context(ks_err!("authorize_create: specified purpose is not supported."));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000461 }
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 Gunasinghef70cf8e2020-11-11 01:02:41 +0000468 let mut user_auth_type: Option<HardwareAuthenticatorType> = None;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000469 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 Gunasinghef70cf8e2020-11-11 01:02:41 +0000473 let mut key_time_out: Option<i64> = None;
474 let mut allow_while_on_body = false;
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000475 let mut unlocked_device_required = false;
Qi Wub9433b52020-12-01 14:52:46 +0800476 let mut key_usage_limited: Option<i64> = None;
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800477 let mut confirmation_token_receiver: Option<Arc<Mutex<Option<Receiver<Vec<u8>>>>>> = None;
Paul Crowley7c57bf12021-02-02 16:26:57 -0800478 let mut max_boot_level: Option<i32> = None;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000479
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 Gunasinghef70cf8e2020-11-11 01:02:41 +0000487 KeyParameterValue::AuthTimeout(t) => {
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000488 key_time_out = Some(*t as i64);
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000489 }
490 KeyParameterValue::HardwareAuthenticatorType(a) => {
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000491 user_auth_type = Some(*a);
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000492 }
493 KeyParameterValue::KeyPurpose(p) => {
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800494 // The following check has the effect of key_params.contains(purpose)
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000495 // Also, authorizing purpose can not be completed here, if there can be multiple
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800496 // key parameters for KeyPurpose.
497 key_purpose_authorized = key_purpose_authorized || *p == purpose;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000498 }
499 KeyParameterValue::CallerNonce => {
500 caller_nonce_allowed = true;
501 }
502 KeyParameterValue::ActiveDateTime(a) => {
503 if !Enforcements::is_given_time_passed(*a, true) {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800504 return Err(Error::Km(Ec::KEY_NOT_YET_VALID))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000505 .context(ks_err!("key is not yet active."));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000506 }
507 }
508 KeyParameterValue::OriginationExpireDateTime(o) => {
509 if (purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN)
510 && Enforcements::is_given_time_passed(*o, false)
511 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000512 return Err(Error::Km(Ec::KEY_EXPIRED)).context(ks_err!("key is expired."));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000513 }
514 }
515 KeyParameterValue::UsageExpireDateTime(u) => {
516 if (purpose == KeyPurpose::DECRYPT || purpose == KeyPurpose::VERIFY)
517 && Enforcements::is_given_time_passed(*u, false)
518 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000519 return Err(Error::Km(Ec::KEY_EXPIRED)).context(ks_err!("key is expired."));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000520 }
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 Gunasinghea020b532021-01-07 21:42:35 +0000529 unlocked_device_required = true;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000530 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000531 KeyParameterValue::AllowWhileOnBody => {
532 allow_while_on_body = true;
533 }
Qi Wub9433b52020-12-01 14:52:46 +0800534 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 Danisevskisb1673db2021-02-08 18:11:57 -0800540 KeyParameterValue::TrustedConfirmationRequired => {
541 confirmation_token_receiver = Some(self.confirmation_token_receiver.clone());
542 }
Paul Crowley7c57bf12021-02-02 16:26:57 -0800543 KeyParameterValue::MaxBootLevel(level) => {
544 max_boot_level = Some(*level);
545 }
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000546 // 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 Danisevskis5ed8c532021-01-11 14:19:42 -0800549 // a subset of non-allowed tags are present). Because sanitizing key parameters
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000550 // 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 Danisevskis5ed8c532021-01-11 14:19:42 -0800557 return Err(Error::Km(Ec::INCOMPATIBLE_PURPOSE))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000558 .context(ks_err!("the purpose is not authorized."));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000559 }
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 Johnson9da2e1c2022-09-19 12:39:01 +0000563 return Err(Error::Km(Ec::INVALID_KEY_BLOB))
564 .context(ks_err!("key has both NO_AUTH_REQUIRED and USER_SECURE_ID tags."));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000565 }
566
567 // 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 +0000568 if (user_auth_type.is_some() && user_secure_ids.is_empty())
569 || (user_auth_type.is_none() && !user_secure_ids.is_empty())
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000570 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000571 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 Gunasinghe5112c702020-11-09 22:13:25 +0000575 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800576
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000577 // validate caller nonce for origination purposes
578 if (purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN)
579 && !caller_nonce_allowed
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800580 && op_params.iter().any(|kp| kp.tag == Tag::NONCE)
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000581 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000582 return Err(Error::Km(Ec::CALLER_NONCE_PROHIBITED))
583 .context(ks_err!("NONCE is present, although CALLER_NONCE is not present"));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000584 }
585
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000586 if unlocked_device_required {
587 // check the device locked status. If locked, operations on the key are not
588 // allowed.
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000589 if self.is_device_locked(user_id) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000590 return Err(Error::Km(Ec::DEVICE_LOCKED)).context(ks_err!("device is locked."));
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000591 }
592 }
593
Paul Crowley7c57bf12021-02-02 16:26:57 -0800594 if let Some(level) = max_boot_level {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800595 if !SUPER_KEY.read().unwrap().level_accessible(level) {
Paul Crowley7c57bf12021-02-02 16:26:57 -0800596 return Err(Error::Km(Ec::BOOT_LEVEL_EXCEEDED))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000597 .context(ks_err!("boot level is too late."));
Paul Crowley7c57bf12021-02-02 16:26:57 -0800598 }
599 }
600
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800601 if !unlocked_device_required && no_auth_required {
Qi Wub9433b52020-12-01 14:52:46 +0800602 return Ok((
603 None,
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800604 AuthInfo {
605 state: DeferredAuthState::NoAuthRequired,
606 key_usage_limited,
607 confirmation_token_receiver,
608 },
Qi Wub9433b52020-12-01 14:52:46 +0800609 ));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000610 }
611
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800612 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 Moore653eca52021-11-19 16:52:19 -0800622 if let (Some(auth_type), true) = (user_auth_type, timeout_bound) {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800623 hat.satisfies(&user_secure_ids, auth_type)
624 } else {
625 unlocked_device_required
626 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700627 });
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800628 Some(
629 hat_and_last_off_body
630 .ok_or(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000631 .context(ks_err!("No suitable auth token found."))?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800632 )
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 Johnson9da2e1c2022-09-19 12:39:01 +0000644 .context(ks_err!(
645 "Overflow while computing Auth token validity. \
646 Validity cannot be established."
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800647 ))?;
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 Johnson9da2e1c2022-09-19 12:39:01 +0000653 .context(ks_err!("matching auth token is expired."));
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800654 }
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 Gunasinghee093b552021-04-30 20:05:31 +0000670 (Some(hat), true, false) => (
671 Some(hat.auth_token().clone()),
672 DeferredAuthState::TimeStampRequired(hat.take_auth_token()),
673 ),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800674 (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 Danisevskisb1673db2021-02-08 18:11:57 -0800683 .map(|(hat, state)| {
684 (hat, AuthInfo { state, key_usage_limited, confirmation_token_receiver })
685 })
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800686 }
687
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700688 fn find_auth_token<F>(p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800689 where
690 F: Fn(&AuthTokenEntry) -> bool,
691 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700692 DB.with(|db| db.borrow().find_auth_token_entry(p))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000693 }
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 Gunasinghe557b1032020-11-10 01:35:30 +0000720
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 Danisevskis5ed8c532021-01-11 14:19:42 -0800734 /// 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 Maurerd7815ca2021-05-06 21:58:45 -0700736 pub fn add_auth_token(&self, hat: HardwareAuthToken) {
737 DB.with(|db| db.borrow_mut().insert_auth_token(&hat));
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800738 self.op_auth_map.add_auth_token(hat);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000739 }
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000740
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 Danisevskis5ed8c532021-01-11 14:19:42 -0800744 /// by the DeferredAuthState.
745 fn register_op_auth_receiver(&self, challenge: i64, recv: TokenReceiver) {
746 self.op_auth_map.add_receiver(challenge, recv);
Hasini Gunasinghef04d07a2020-11-25 22:41:35 +0000747 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000748
749 /// Given the set of key parameters and flags, check if super encryption is required.
Paul Crowley7a658392021-03-18 17:08:20 -0700750 pub fn super_encryption_required(
751 domain: &Domain,
752 key_parameters: &[KeyParameter],
753 flags: Option<i32>,
754 ) -> SuperEncryptionType {
Paul Crowley7a658392021-03-18 17:08:20 -0700755 if let Some(flags) = flags {
756 if (flags & KEY_FLAG_AUTH_BOUND_WITHOUT_CRYPTOGRAPHIC_LSKF_BINDING) != 0 {
757 return SuperEncryptionType::None;
758 }
759 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000760 // Each answer has a priority, numerically largest priority wins.
761 struct Candidate {
762 priority: u32,
763 enc_type: SuperEncryptionType,
Paul Crowley7a658392021-03-18 17:08:20 -0700764 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000765 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 Trafimovich229f2c02021-04-06 16:07:07 +0000782 }
Paul Crowley44c02da2021-04-08 17:04:43 +0000783 result.enc_type
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000784 }
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000785
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000786 /// 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 Maurerd7815ca2021-05-06 21:58:45 -0700806 });
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000807
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 Gunasinghe66a24602021-05-12 19:03:12 +0000813 let now_in_millis = MonotonicRawTime::now();
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000814 let result = Self::find_auth_token(|auth_token_entry: &AuthTokenEntry| {
815 let token_valid = now_in_millis
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000816 .checked_sub(&auth_token_entry.time_received())
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000817 .map_or(false, |token_age_in_millis| {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000818 auth_token_max_age_millis > token_age_in_millis.milliseconds()
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000819 });
820 token_valid && auth_token_entry.satisfies(&sids, auth_type)
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700821 });
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000822
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 Johnson9da2e1c2022-09-19 12:39:01 +0000827 .context(ks_err!("No auth token found."));
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000828 }
829 } else {
Hasini Gunasinghe1ce72932021-09-14 15:43:19 +0000830 return Err(AuthzError::Rc(AuthzResponseCode::NO_AUTH_TOKEN_FOUND)).context(
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000831 ks_err!(
832 "No auth token found for \
833 the given challenge and passed-in auth token max age is zero."
Hasini Gunasinghe1ce72932021-09-14 15:43:19 +0000834 ),
835 );
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000836 }
837 };
838 // Wait and obtain the timestamp token from secure clock service.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000839 let tst =
840 get_timestamp_token(challenge).context(ks_err!("Error in getting timestamp token."))?;
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000841 Ok((auth_token, tst))
842 }
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000843}
844
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000845// TODO: Add tests to enforcement module (b/175578618).