1 // Copyright 2020, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 //! This is the Keystore 2.0 Enforcements module.
16 // TODO: more description to follow.
17 use crate::ks_err;
18 use crate::error::{map_binder_status, Error, ErrorCode};
19 use crate::globals::{get_timestamp_service, ASYNC_TASK, DB, ENFORCEMENTS};
20 use crate::key_parameter::{KeyParameter, KeyParameterValue};
21 use crate::{authorization::Error as AuthzError, super_key::SuperEncryptionType};
22 use crate::{
23     database::{AuthTokenEntry, BootTime},
24     globals::SUPER_KEY,
25 };
26 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
27     Algorithm::Algorithm, ErrorCode::ErrorCode as Ec, HardwareAuthToken::HardwareAuthToken,
28     HardwareAuthenticatorType::HardwareAuthenticatorType,
29     KeyParameter::KeyParameter as KmKeyParameter, KeyPurpose::KeyPurpose, Tag::Tag,
30 };
31 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
32     TimeStampToken::TimeStampToken,
33 };
34 use android_security_authorization::aidl::android::security::authorization::ResponseCode::ResponseCode as AuthzResponseCode;
35 use android_system_keystore2::aidl::android::system::keystore2::{
36     Domain::Domain, IKeystoreSecurityLevel::KEY_FLAG_AUTH_BOUND_WITHOUT_CRYPTOGRAPHIC_LSKF_BINDING,
37     OperationChallenge::OperationChallenge,
38 };
39 use anyhow::{Context, Result};
40 use std::{
41     collections::{HashMap, HashSet},
42     sync::{
43         mpsc::{channel, Receiver, Sender, TryRecvError},
44         Arc, Mutex, Weak,
45     },
46     time::SystemTime,
47 };
48 
49 #[derive(Debug)]
50 enum AuthRequestState {
51     /// An outstanding per operation authorization request.
52     OpAuth,
53     /// An outstanding request for per operation authorization and secure timestamp.
54     TimeStampedOpAuth(Mutex<Receiver<Result<TimeStampToken, Error>>>),
55     /// An outstanding request for a timestamp token.
56     TimeStamp(Mutex<Receiver<Result<TimeStampToken, Error>>>),
57 }
58 
59 #[derive(Debug)]
60 struct AuthRequest {
61     state: AuthRequestState,
62     /// This need to be set to Some to fulfill a AuthRequestState::OpAuth or
63     /// AuthRequestState::TimeStampedOpAuth.
64     hat: Mutex<Option<HardwareAuthToken>>,
65 }
66 
67 impl AuthRequest {
op_auth() -> Arc<Self>68     fn op_auth() -> Arc<Self> {
69         Arc::new(Self { state: AuthRequestState::OpAuth, hat: Mutex::new(None) })
70     }
71 
timestamped_op_auth(receiver: Receiver<Result<TimeStampToken, Error>>) -> Arc<Self>72     fn timestamped_op_auth(receiver: Receiver<Result<TimeStampToken, Error>>) -> Arc<Self> {
73         Arc::new(Self {
74             state: AuthRequestState::TimeStampedOpAuth(Mutex::new(receiver)),
75             hat: Mutex::new(None),
76         })
77     }
78 
timestamp( hat: HardwareAuthToken, receiver: Receiver<Result<TimeStampToken, Error>>, ) -> Arc<Self>79     fn timestamp(
80         hat: HardwareAuthToken,
81         receiver: Receiver<Result<TimeStampToken, Error>>,
82     ) -> Arc<Self> {
83         Arc::new(Self {
84             state: AuthRequestState::TimeStamp(Mutex::new(receiver)),
85             hat: Mutex::new(Some(hat)),
86         })
87     }
88 
add_auth_token(&self, hat: HardwareAuthToken)89     fn add_auth_token(&self, hat: HardwareAuthToken) {
90         *self.hat.lock().unwrap() = Some(hat)
91     }
92 
get_auth_tokens(&self) -> Result<(HardwareAuthToken, Option<TimeStampToken>)>93     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))
100             .context(ks_err!("No operation auth token received."))?;
101 
102         let tst = match &self.state {
103             AuthRequestState::TimeStampedOpAuth(recv) | AuthRequestState::TimeStamp(recv) => {
104                 let result = recv
105                     .lock()
106                     .unwrap()
107                     .recv()
108                     .context("In get_auth_tokens: Sender disconnected.")?;
109                 Some(result.context(ks_err!(
110                     "Worker responded with error \
111                     from generating timestamp token.",
112                 ))?)
113             }
114             AuthRequestState::OpAuth => None,
115         };
116         Ok((hat, tst))
117     }
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)]
123 enum 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.
142     Waiting(Arc<AuthRequest>),
143     /// 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)]
152 pub struct AuthInfo {
153     state: DeferredAuthState,
154     /// An optional key id required to update the usage count if the key usage is limited.
155     key_usage_limited: Option<i64>,
156     confirmation_token_receiver: Option<Arc<Mutex<Option<Receiver<Vec<u8>>>>>>,
157 }
158 
159 struct 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 
170 impl Default for TokenReceiverMap {
default() -> Self171     fn default() -> Self {
172         Self { map_and_cleanup_counter: Mutex::new((HashMap::new(), Self::CLEANUP_PERIOD + 1)) }
173     }
174 }
175 
176 impl 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 
add_auth_token(&self, hat: HardwareAuthToken)183     pub fn add_auth_token(&self, hat: HardwareAuthToken) {
184         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 {
193             recv.add_auth_token(hat);
194         }
195     }
196 
add_receiver(&self, challenge: i64, recv: TokenReceiver)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)]
212 struct TokenReceiver(Weak<AuthRequest>);
213 
214 impl TokenReceiver {
is_obsolete(&self) -> bool215     fn is_obsolete(&self) -> bool {
216         self.0.upgrade().is_none()
217     }
218 
add_auth_token(&self, hat: HardwareAuthToken)219     fn add_auth_token(&self, hat: HardwareAuthToken) {
220         if let Some(state_arc) = self.0.upgrade() {
221             state_arc.add_auth_token(hat);
222         }
223     }
224 }
225 
get_timestamp_token(challenge: i64) -> Result<TimeStampToken, Error>226 fn get_timestamp_token(challenge: i64) -> Result<TimeStampToken, Error> {
227     let dev = get_timestamp_service().expect(concat!(
228         "Secure Clock service must be present ",
229         "if TimeStampTokens are required."
230     ));
231     map_binder_status(dev.generateTimeStamp(challenge))
232 }
233 
timestamp_token_request(challenge: i64, sender: Sender<Result<TimeStampToken, Error>>)234 fn timestamp_token_request(challenge: i64, sender: Sender<Result<TimeStampToken, Error>>) {
235     if let Err(e) = sender.send(get_timestamp_token(challenge)) {
236         log::info!(
237             concat!("Receiver hung up ", "before timestamp token could be delivered. {:?}"),
238             e
239         );
240     }
241 }
242 
243 impl 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.
finalize_create_authorization(&mut self, challenge: i64) -> Option<OperationChallenge>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 
263                 ASYNC_TASK.queue_hi(move |_| timestamp_token_request(challenge, sender));
264                 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);
271                 ASYNC_TASK.queue_hi(move |_| timestamp_token_request(challenge, sender));
272                 self.state = DeferredAuthState::Waiting(auth_request);
273                 None
274             }
275             _ => None,
276         }
277     }
278 
279     /// This function is the authorization hook called before operation update.
280     /// It returns the auth tokens required by the operation to commence update.
before_update(&mut self) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>)>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.
287     /// The third token is a confirmation token.
before_finish( &mut self, ) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>, Option<Vec<u8>>)>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))
313     }
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.
after_finish(&self) -> Result<()>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.
323             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             })
328             .context(ks_err!())?;
329         }
330         Ok(())
331     }
332 
333     /// 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.
get_auth_tokens(&mut self) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>)>338     fn get_auth_tokens(&mut self) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>)> {
339         let deferred_tokens = if let DeferredAuthState::Waiting(ref auth_request) = self.state {
340             Some(auth_request.get_auth_tokens().context("In AuthInfo::get_auth_tokens.")?)
341         } 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(_) => {
355                 Err(Error::Km(ErrorCode::KEY_USER_NOT_AUTHENTICATED)).context(ks_err!(
356                     "No operation auth token requested??? \
357                     This should not happen."
358                 ))
359             }
360             // This should not be reachable, because it should have been handled above.
361             DeferredAuthState::Waiting(_) => {
362                 Err(Error::sys()).context(ks_err!("AuthInfo::get_auth_tokens: Cannot be reached.",))
363             }
364         }
365     }
366 }
367 
368 /// Enforcements data structure
369 #[derive(Default)]
370 pub struct Enforcements {
371     /// 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.
373     device_unlocked_set: Mutex<HashSet<i32>>,
374     /// 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,
380     /// 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>>>>>,
383 }
384 
385 impl Enforcements {
386     /// 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.
install_confirmation_token_receiver( &self, confirmation_token_receiver: Receiver<Vec<u8>>, )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 
396     /// Checks if a create call is authorized, given key parameters and operation parameters.
397     /// 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.
400     /// With regard to auth tokens, the following steps are taken:
401     ///
402     /// If no key parameters are given (typically when the client is self managed
403     /// (see Domain.Blob)) nothing is enforced.
404     /// If the key is time-bound, find a matching auth token from the database.
405     /// If the above step is successful, and if requires_timestamp is given, the returned
406     /// AuthInfo will provide a Timestamp token as appropriate.
authorize_create( &self, purpose: KeyPurpose, key_properties: Option<&(i64, Vec<KeyParameter>)>, op_params: &[KmKeyParameter], requires_timestamp: bool, ) -> Result<(Option<HardwareAuthToken>, AuthInfo)>407     pub fn authorize_create(
408         &self,
409         purpose: KeyPurpose,
410         key_properties: Option<&(i64, Vec<KeyParameter>)>,
411         op_params: &[KmKeyParameter],
412         requires_timestamp: bool,
413     ) -> Result<(Option<HardwareAuthToken>, AuthInfo)> {
414         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,
419                     AuthInfo {
420                         state: DeferredAuthState::NoAuthRequired,
421                         key_usage_limited: None,
422                         confirmation_token_receiver: None,
423                     },
424                 ));
425             }
426         };
427 
428         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 => {
433                 return Err(Error::Km(Ec::INCOMPATIBLE_PURPOSE))
434                     .context(ks_err!("WRAP_KEY purpose is not allowed here.",));
435             }
436             // 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                     {
442                         return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE))
443                             .context(ks_err!("key agreement is only supported for EC keys.",));
444                     }
445                 }
446             }
447             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) => {
454                             return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE)).context(ks_err!(
455                                 "public operations on asymmetric keys are \
456                                  not supported."
457                             ));
458                         }
459                         _ => {}
460                     }
461                 }
462             }
463             _ => {
464                 return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE))
465                     .context(ks_err!("authorize_create: specified purpose is not supported."));
466             }
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;
473         let mut user_auth_type: Option<HardwareAuthenticatorType> = None;
474         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();
478         let mut key_time_out: Option<i64> = None;
479         let mut unlocked_device_required = false;
480         let mut key_usage_limited: Option<i64> = None;
481         let mut confirmation_token_receiver: Option<Arc<Mutex<Option<Receiver<Vec<u8>>>>>> = None;
482         let mut max_boot_level: Option<i32> = None;
483 
484         // iterate through key parameters, recording information we need for authorization
485         // enforcements later, or enforcing authorizations in place, where applicable
486         for key_param in key_params.iter() {
487             match key_param.key_parameter_value() {
488                 KeyParameterValue::NoAuthRequired => {
489                     no_auth_required = true;
490                 }
491                 KeyParameterValue::AuthTimeout(t) => {
492                     key_time_out = Some(*t as i64);
493                 }
494                 KeyParameterValue::HardwareAuthenticatorType(a) => {
495                     user_auth_type = Some(*a);
496                 }
497                 KeyParameterValue::KeyPurpose(p) => {
498                     // The following check has the effect of key_params.contains(purpose)
499                     // Also, authorizing purpose can not be completed here, if there can be multiple
500                     // key parameters for KeyPurpose.
501                     key_purpose_authorized = key_purpose_authorized || *p == purpose;
502                 }
503                 KeyParameterValue::CallerNonce => {
504                     caller_nonce_allowed = true;
505                 }
506                 KeyParameterValue::ActiveDateTime(a) => {
507                     if !Enforcements::is_given_time_passed(*a, true) {
508                         return Err(Error::Km(Ec::KEY_NOT_YET_VALID))
509                             .context(ks_err!("key is not yet active."));
510                     }
511                 }
512                 KeyParameterValue::OriginationExpireDateTime(o) => {
513                     if (purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN)
514                         && Enforcements::is_given_time_passed(*o, false)
515                     {
516                         return Err(Error::Km(Ec::KEY_EXPIRED)).context(ks_err!("key is expired."));
517                     }
518                 }
519                 KeyParameterValue::UsageExpireDateTime(u) => {
520                     if (purpose == KeyPurpose::DECRYPT || purpose == KeyPurpose::VERIFY)
521                         && Enforcements::is_given_time_passed(*u, false)
522                     {
523                         return Err(Error::Km(Ec::KEY_EXPIRED)).context(ks_err!("key is expired."));
524                     }
525                 }
526                 KeyParameterValue::UserSecureID(s) => {
527                     user_secure_ids.push(*s);
528                 }
529                 KeyParameterValue::UserID(u) => {
530                     user_id = *u;
531                 }
532                 KeyParameterValue::UnlockedDeviceRequired => {
533                     unlocked_device_required = true;
534                 }
535                 KeyParameterValue::UsageCountLimit(_) => {
536                     // We don't examine the limit here because this is enforced on finish.
537                     // Instead, we store the key_id so that finish can look up the key
538                     // in the database again and check and update the counter.
539                     key_usage_limited = Some(key_id);
540                 }
541                 KeyParameterValue::TrustedConfirmationRequired => {
542                     confirmation_token_receiver = Some(self.confirmation_token_receiver.clone());
543                 }
544                 KeyParameterValue::MaxBootLevel(level) => {
545                     max_boot_level = Some(*level);
546                 }
547                 // NOTE: as per offline discussion, sanitizing key parameters and rejecting
548                 // create operation if any non-allowed tags are present, is not done in
549                 // authorize_create (unlike in legacy keystore where AuthorizeBegin is rejected if
550                 // a subset of non-allowed tags are present). Because sanitizing key parameters
551                 // should have been done during generate/import key, by KeyMint.
552                 _ => { /*Do nothing on all the other key parameters, as in legacy keystore*/ }
553             }
554         }
555 
556         // authorize the purpose
557         if !key_purpose_authorized {
558             return Err(Error::Km(Ec::INCOMPATIBLE_PURPOSE))
559                 .context(ks_err!("the purpose is not authorized."));
560         }
561 
562         // if both NO_AUTH_REQUIRED and USER_SECURE_ID tags are present, return error
563         if !user_secure_ids.is_empty() && no_auth_required {
564             return Err(Error::Km(Ec::INVALID_KEY_BLOB))
565                 .context(ks_err!("key has both NO_AUTH_REQUIRED and USER_SECURE_ID tags."));
566         }
567 
568         // if either of auth_type or secure_id is present and the other is not present, return error
569         if (user_auth_type.is_some() && user_secure_ids.is_empty())
570             || (user_auth_type.is_none() && !user_secure_ids.is_empty())
571         {
572             return Err(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED)).context(ks_err!(
573                 "Auth required, but either auth type or secure ids \
574                  are not present."
575             ));
576         }
577 
578         // validate caller nonce for origination purposes
579         if (purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN)
580             && !caller_nonce_allowed
581             && op_params.iter().any(|kp| kp.tag == Tag::NONCE)
582         {
583             return Err(Error::Km(Ec::CALLER_NONCE_PROHIBITED))
584                 .context(ks_err!("NONCE is present, although CALLER_NONCE is not present"));
585         }
586 
587         if unlocked_device_required {
588             // check the device locked status. If locked, operations on the key are not
589             // allowed.
590             if self.is_device_locked(user_id) {
591                 return Err(Error::Km(Ec::DEVICE_LOCKED)).context(ks_err!("device is locked."));
592             }
593         }
594 
595         if let Some(level) = max_boot_level {
596             if !SUPER_KEY.read().unwrap().level_accessible(level) {
597                 return Err(Error::Km(Ec::BOOT_LEVEL_EXCEEDED))
598                     .context(ks_err!("boot level is too late."));
599             }
600         }
601 
602         if android_security_flags::fix_unlocked_device_required_keys_v2() {
603             let (hat, state) = if user_secure_ids.is_empty() {
604                 (None, DeferredAuthState::NoAuthRequired)
605             } else if let Some(key_time_out) = key_time_out {
606                 let hat = Self::find_auth_token(|hat: &AuthTokenEntry| match user_auth_type {
607                     Some(auth_type) => hat.satisfies(&user_secure_ids, auth_type),
608                     None => false, // not reachable due to earlier check
609                 })
610                 .ok_or(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
611                 .context(ks_err!("No suitable auth token found."))?;
612                 let now = BootTime::now();
613                 let token_age = now
614                     .checked_sub(&hat.time_received())
615                     .ok_or_else(Error::sys)
616                     .context(ks_err!(
617                         "Overflow while computing Auth token validity. \
618                     Validity cannot be established."
619                     ))?;
620 
621                 if token_age.seconds() > key_time_out {
622                     return Err(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
623                         .context(ks_err!("matching auth token is expired."));
624                 }
625                 let state = if requires_timestamp {
626                     DeferredAuthState::TimeStampRequired(hat.auth_token().clone())
627                 } else {
628                     DeferredAuthState::NoAuthRequired
629                 };
630                 (Some(hat.take_auth_token()), state)
631             } else {
632                 (None, DeferredAuthState::OpAuthRequired)
633             };
634             return Ok((hat, AuthInfo { state, key_usage_limited, confirmation_token_receiver }));
635         }
636 
637         if !unlocked_device_required && no_auth_required {
638             return Ok((
639                 None,
640                 AuthInfo {
641                     state: DeferredAuthState::NoAuthRequired,
642                     key_usage_limited,
643                     confirmation_token_receiver,
644                 },
645             ));
646         }
647 
648         let has_sids = !user_secure_ids.is_empty();
649 
650         let timeout_bound = key_time_out.is_some() && has_sids;
651 
652         let per_op_bound = key_time_out.is_none() && has_sids;
653 
654         let need_auth_token = timeout_bound || unlocked_device_required;
655 
656         let hat = if need_auth_token {
657             let hat = Self::find_auth_token(|hat: &AuthTokenEntry| {
658                 if let (Some(auth_type), true) = (user_auth_type, timeout_bound) {
659                     hat.satisfies(&user_secure_ids, auth_type)
660                 } else {
661                     unlocked_device_required
662                 }
663             });
664             Some(
665                 hat.ok_or(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
666                     .context(ks_err!("No suitable auth token found."))?,
667             )
668         } else {
669             None
670         };
671 
672         // Now check the validity of the auth token if the key is timeout bound.
673         let hat = match (hat, key_time_out) {
674             (Some(hat), Some(key_time_out)) => {
675                 let now = BootTime::now();
676                 let token_age = now
677                     .checked_sub(&hat.time_received())
678                     .ok_or_else(Error::sys)
679                     .context(ks_err!(
680                         "Overflow while computing Auth token validity. \
681                     Validity cannot be established."
682                     ))?;
683 
684                 if token_age.seconds() > key_time_out {
685                     return Err(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
686                         .context(ks_err!("matching auth token is expired."));
687                 }
688                 Some(hat)
689             }
690             (Some(hat), None) => Some(hat),
691             // If timeout_bound is true, above code must have retrieved a HAT or returned with
692             // KEY_USER_NOT_AUTHENTICATED. This arm should not be reachable.
693             (None, Some(_)) => panic!("Logical error."),
694             _ => None,
695         };
696 
697         Ok(match (hat, requires_timestamp, per_op_bound) {
698             // Per-op-bound and Some(hat) can only happen if we are both per-op bound and unlocked
699             // device required. In addition, this KM instance needs a timestamp token.
700             // So the HAT cannot be presented on create. So on update/finish we present both
701             // an per-op-bound auth token and a timestamp token.
702             (Some(_), true, true) => (None, DeferredAuthState::TimeStampedOpAuthRequired),
703             (Some(hat), true, false) => (
704                 Some(hat.auth_token().clone()),
705                 DeferredAuthState::TimeStampRequired(hat.take_auth_token()),
706             ),
707             (Some(hat), false, true) => {
708                 (Some(hat.take_auth_token()), DeferredAuthState::OpAuthRequired)
709             }
710             (Some(hat), false, false) => {
711                 (Some(hat.take_auth_token()), DeferredAuthState::NoAuthRequired)
712             }
713             (None, _, true) => (None, DeferredAuthState::OpAuthRequired),
714             (None, _, false) => (None, DeferredAuthState::NoAuthRequired),
715         })
716         .map(|(hat, state)| {
717             (hat, AuthInfo { state, key_usage_limited, confirmation_token_receiver })
718         })
719     }
720 
find_auth_token<F>(p: F) -> Option<AuthTokenEntry> where F: Fn(&AuthTokenEntry) -> bool,721     fn find_auth_token<F>(p: F) -> Option<AuthTokenEntry>
722     where
723         F: Fn(&AuthTokenEntry) -> bool,
724     {
725         DB.with(|db| db.borrow().find_auth_token_entry(p))
726     }
727 
728     /// Checks if the time now since epoch is greater than (or equal, if is_given_time_inclusive is
729     /// set) the given time (in milliseconds)
is_given_time_passed(given_time: i64, is_given_time_inclusive: bool) -> bool730     fn is_given_time_passed(given_time: i64, is_given_time_inclusive: bool) -> bool {
731         let duration_since_epoch = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH);
732 
733         let time_since_epoch = match duration_since_epoch {
734             Ok(duration) => duration.as_millis(),
735             Err(_) => return false,
736         };
737 
738         if is_given_time_inclusive {
739             time_since_epoch >= (given_time as u128)
740         } else {
741             time_since_epoch > (given_time as u128)
742         }
743     }
744 
745     /// Check if the device is locked for the given user. If there's no entry yet for the user,
746     /// we assume that the device is locked
is_device_locked(&self, user_id: i32) -> bool747     fn is_device_locked(&self, user_id: i32) -> bool {
748         // unwrap here because there's no way this mutex guard can be poisoned and
749         // because there's no way to recover, even if it is poisoned.
750         let set = self.device_unlocked_set.lock().unwrap();
751         !set.contains(&user_id)
752     }
753 
754     /// Sets the device locked status for the user. This method is called externally.
set_device_locked(&self, user_id: i32, device_locked_status: bool)755     pub fn set_device_locked(&self, user_id: i32, device_locked_status: bool) {
756         // unwrap here because there's no way this mutex guard can be poisoned and
757         // because there's no way to recover, even if it is poisoned.
758         let mut set = self.device_unlocked_set.lock().unwrap();
759         if device_locked_status {
760             set.remove(&user_id);
761         } else {
762             set.insert(user_id);
763         }
764     }
765 
766     /// Add this auth token to the database.
767     /// Then present the auth token to the op auth map. If an operation is waiting for this
768     /// auth token this fulfills the request and removes the receiver from the map.
add_auth_token(&self, hat: HardwareAuthToken)769     pub fn add_auth_token(&self, hat: HardwareAuthToken) {
770         DB.with(|db| db.borrow_mut().insert_auth_token(&hat));
771         self.op_auth_map.add_auth_token(hat);
772     }
773 
774     /// This allows adding an entry to the op_auth_map, indexed by the operation challenge.
775     /// This is to be called by create_operation, once it has received the operation challenge
776     /// from keymint for an operation whose authorization decision is OpAuthRequired, as signalled
777     /// by the DeferredAuthState.
register_op_auth_receiver(&self, challenge: i64, recv: TokenReceiver)778     fn register_op_auth_receiver(&self, challenge: i64, recv: TokenReceiver) {
779         self.op_auth_map.add_receiver(challenge, recv);
780     }
781 
782     /// Given the set of key parameters and flags, check if super encryption is required.
super_encryption_required( domain: &Domain, key_parameters: &[KeyParameter], flags: Option<i32>, ) -> SuperEncryptionType783     pub fn super_encryption_required(
784         domain: &Domain,
785         key_parameters: &[KeyParameter],
786         flags: Option<i32>,
787     ) -> SuperEncryptionType {
788         if let Some(flags) = flags {
789             if (flags & KEY_FLAG_AUTH_BOUND_WITHOUT_CRYPTOGRAPHIC_LSKF_BINDING) != 0 {
790                 return SuperEncryptionType::None;
791             }
792         }
793         // Each answer has a priority, numerically largest priority wins.
794         struct Candidate {
795             priority: u32,
796             enc_type: SuperEncryptionType,
797         }
798         let mut result = Candidate { priority: 0, enc_type: SuperEncryptionType::None };
799         for kp in key_parameters {
800             let t = match kp.key_parameter_value() {
801                 KeyParameterValue::MaxBootLevel(level) => {
802                     Candidate { priority: 3, enc_type: SuperEncryptionType::BootLevel(*level) }
803                 }
804                 KeyParameterValue::UnlockedDeviceRequired if *domain == Domain::APP => {
805                     Candidate { priority: 2, enc_type: SuperEncryptionType::UnlockedDeviceRequired }
806                 }
807                 KeyParameterValue::UserSecureID(_) if *domain == Domain::APP => {
808                     Candidate { priority: 1, enc_type: SuperEncryptionType::AfterFirstUnlock }
809                 }
810                 _ => Candidate { priority: 0, enc_type: SuperEncryptionType::None },
811             };
812             if t.priority > result.priority {
813                 result = t;
814             }
815         }
816         result.enc_type
817     }
818 
819     /// Finds a matching auth token along with a timestamp token.
820     /// This method looks through auth-tokens cached by keystore which satisfy the given
821     /// authentication information (i.e. |secureUserId|).
822     /// The most recent matching auth token which has a |challenge| field which matches
823     /// the passed-in |challenge| parameter is returned.
824     /// In this case the |authTokenMaxAgeMillis| parameter is not used.
825     ///
826     /// Otherwise, the most recent matching auth token which is younger than |authTokenMaxAgeMillis|
827     /// is returned.
get_auth_tokens( &self, challenge: i64, secure_user_id: i64, auth_token_max_age_millis: i64, ) -> Result<(HardwareAuthToken, TimeStampToken)>828     pub fn get_auth_tokens(
829         &self,
830         challenge: i64,
831         secure_user_id: i64,
832         auth_token_max_age_millis: i64,
833     ) -> Result<(HardwareAuthToken, TimeStampToken)> {
834         let auth_type = HardwareAuthenticatorType::ANY;
835         let sids: Vec<i64> = vec![secure_user_id];
836         // Filter the matching auth tokens by challenge
837         let result = Self::find_auth_token(|hat: &AuthTokenEntry| {
838             (challenge == hat.challenge()) && hat.satisfies(&sids, auth_type)
839         });
840 
841         let auth_token = if let Some(auth_token_entry) = result {
842             auth_token_entry.take_auth_token()
843         } else {
844             // Filter the matching auth tokens by age.
845             if auth_token_max_age_millis != 0 {
846                 let now_in_millis = BootTime::now();
847                 let result = Self::find_auth_token(|auth_token_entry: &AuthTokenEntry| {
848                     let token_valid = now_in_millis
849                         .checked_sub(&auth_token_entry.time_received())
850                         .map_or(false, |token_age_in_millis| {
851                             auth_token_max_age_millis > token_age_in_millis.milliseconds()
852                         });
853                     token_valid && auth_token_entry.satisfies(&sids, auth_type)
854                 });
855 
856                 if let Some(auth_token_entry) = result {
857                     auth_token_entry.take_auth_token()
858                 } else {
859                     return Err(AuthzError::Rc(AuthzResponseCode::NO_AUTH_TOKEN_FOUND))
860                         .context(ks_err!("No auth token found."));
861                 }
862             } else {
863                 return Err(AuthzError::Rc(AuthzResponseCode::NO_AUTH_TOKEN_FOUND)).context(
864                     ks_err!(
865                         "No auth token found for \
866                     the given challenge and passed-in auth token max age is zero."
867                     ),
868                 );
869             }
870         };
871         // Wait and obtain the timestamp token from secure clock service.
872         let tst =
873             get_timestamp_token(challenge).context(ks_err!("Error in getting timestamp token."))?;
874         Ok((auth_token, tst))
875     }
876 
877     /// Finds the most recent received time for an auth token that matches the given secure user id and authenticator
get_last_auth_time( &self, secure_user_id: i64, auth_type: HardwareAuthenticatorType, ) -> Option<BootTime>878     pub fn get_last_auth_time(
879         &self,
880         secure_user_id: i64,
881         auth_type: HardwareAuthenticatorType,
882     ) -> Option<BootTime> {
883         let sids: Vec<i64> = vec![secure_user_id];
884 
885         let result =
886             Self::find_auth_token(|entry: &AuthTokenEntry| entry.satisfies(&sids, auth_type));
887 
888         result.map(|auth_token_entry| auth_token_entry.time_received())
889     }
890 }
891 
892 // TODO: Add tests to enforcement module (b/175578618).
893