• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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, MonotonicRawTime},
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(Receiver<Result<TimeStampToken, Error>>),
55     /// An outstanding request for a timestamp token.
56     TimeStamp(Receiver<Result<TimeStampToken, Error>>),
57 }
58 
59 #[derive(Debug)]
60 struct AuthRequest {
61     state: AuthRequestState,
62     /// This need to be set to Some to fulfill a AuthRequestState::OpAuth or
63     /// AuthRequestState::TimeStampedOpAuth.
64     hat: Mutex<Option<HardwareAuthToken>>,
65 }
66 
67 unsafe impl Sync for AuthRequest {}
68 
69 impl AuthRequest {
op_auth() -> Arc<Self>70     fn op_auth() -> Arc<Self> {
71         Arc::new(Self { state: AuthRequestState::OpAuth, hat: Mutex::new(None) })
72     }
73 
timestamped_op_auth(receiver: Receiver<Result<TimeStampToken, Error>>) -> Arc<Self>74     fn timestamped_op_auth(receiver: Receiver<Result<TimeStampToken, Error>>) -> Arc<Self> {
75         Arc::new(Self {
76             state: AuthRequestState::TimeStampedOpAuth(receiver),
77             hat: Mutex::new(None),
78         })
79     }
80 
timestamp( hat: HardwareAuthToken, receiver: Receiver<Result<TimeStampToken, Error>>, ) -> Arc<Self>81     fn timestamp(
82         hat: HardwareAuthToken,
83         receiver: Receiver<Result<TimeStampToken, Error>>,
84     ) -> Arc<Self> {
85         Arc::new(Self { state: AuthRequestState::TimeStamp(receiver), hat: Mutex::new(Some(hat)) })
86     }
87 
add_auth_token(&self, hat: HardwareAuthToken)88     fn add_auth_token(&self, hat: HardwareAuthToken) {
89         *self.hat.lock().unwrap() = Some(hat)
90     }
91 
get_auth_tokens(&self) -> Result<(HardwareAuthToken, Option<TimeStampToken>)>92     fn get_auth_tokens(&self) -> Result<(HardwareAuthToken, Option<TimeStampToken>)> {
93         let hat = self
94             .hat
95             .lock()
96             .unwrap()
97             .take()
98             .ok_or(Error::Km(ErrorCode::KEY_USER_NOT_AUTHENTICATED))
99             .context(ks_err!("No operation auth token received."))?;
100 
101         let tst = match &self.state {
102             AuthRequestState::TimeStampedOpAuth(recv) | AuthRequestState::TimeStamp(recv) => {
103                 let result = recv.recv().context("In get_auth_tokens: Sender disconnected.")?;
104                 Some(result.context(ks_err!(
105                     "Worker responded with error \
106                     from generating timestamp token.",
107                 ))?)
108             }
109             AuthRequestState::OpAuth => None,
110         };
111         Ok((hat, tst))
112     }
113 }
114 
115 /// DeferredAuthState describes how auth tokens and timestamp tokens need to be provided when
116 /// updating and finishing an operation.
117 #[derive(Debug)]
118 enum DeferredAuthState {
119     /// Used when an operation does not require further authorization.
120     NoAuthRequired,
121     /// Indicates that the operation requires an operation specific token. This means we have
122     /// to return an operation challenge to the client which should reward us with an
123     /// operation specific auth token. If it is not provided before the client calls update
124     /// or finish, the operation fails as not authorized.
125     OpAuthRequired,
126     /// Indicates that the operation requires a time stamp token. The auth token was already
127     /// loaded from the database, but it has to be accompanied by a time stamp token to inform
128     /// the target KM with a different clock about the time on the authenticators.
129     TimeStampRequired(HardwareAuthToken),
130     /// Indicates that both an operation bound auth token and a verification token are
131     /// before the operation can commence.
132     TimeStampedOpAuthRequired,
133     /// In this state the auth info is waiting for the deferred authorizations to come in.
134     /// We block on timestamp tokens, because we can always make progress on these requests.
135     /// The per-op auth tokens might never come, which means we fail if the client calls
136     /// update or finish before we got a per-op auth token.
137     Waiting(Arc<AuthRequest>),
138     /// In this state we have gotten all of the required tokens, we just cache them to
139     /// be used when the operation progresses.
140     Token(HardwareAuthToken, Option<TimeStampToken>),
141 }
142 
143 /// Auth info hold all of the authorization related information of an operation. It is stored
144 /// in and owned by the operation. It is constructed by authorize_create and stays with the
145 /// operation until it completes.
146 #[derive(Debug)]
147 pub struct AuthInfo {
148     state: DeferredAuthState,
149     /// An optional key id required to update the usage count if the key usage is limited.
150     key_usage_limited: Option<i64>,
151     confirmation_token_receiver: Option<Arc<Mutex<Option<Receiver<Vec<u8>>>>>>,
152 }
153 
154 struct TokenReceiverMap {
155     /// The map maps an outstanding challenge to a TokenReceiver. If an incoming Hardware Auth
156     /// Token (HAT) has the map key in its challenge field, it gets passed to the TokenReceiver
157     /// and the entry is removed from the map. In the case where no HAT is received before the
158     /// corresponding operation gets dropped, the entry goes stale. So every time the cleanup
159     /// counter (second field in the tuple) turns 0, the map is cleaned from stale entries.
160     /// The cleanup counter is decremented every time a new receiver is added.
161     /// and reset to TokenReceiverMap::CLEANUP_PERIOD + 1 after each cleanup.
162     map_and_cleanup_counter: Mutex<(HashMap<i64, TokenReceiver>, u8)>,
163 }
164 
165 impl Default for TokenReceiverMap {
default() -> Self166     fn default() -> Self {
167         Self { map_and_cleanup_counter: Mutex::new((HashMap::new(), Self::CLEANUP_PERIOD + 1)) }
168     }
169 }
170 
171 impl TokenReceiverMap {
172     /// There is a chance that receivers may become stale because their operation is dropped
173     /// without ever being authorized. So occasionally we iterate through the map and throw
174     /// out obsolete entries.
175     /// This is the number of calls to add_receiver between cleanups.
176     const CLEANUP_PERIOD: u8 = 25;
177 
add_auth_token(&self, hat: HardwareAuthToken)178     pub fn add_auth_token(&self, hat: HardwareAuthToken) {
179         let recv = {
180             // Limit the scope of the mutex guard, so that it is not held while the auth token is
181             // added.
182             let mut map = self.map_and_cleanup_counter.lock().unwrap();
183             let (ref mut map, _) = *map;
184             map.remove_entry(&hat.challenge)
185         };
186 
187         if let Some((_, recv)) = recv {
188             recv.add_auth_token(hat);
189         }
190     }
191 
add_receiver(&self, challenge: i64, recv: TokenReceiver)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)]
207 struct TokenReceiver(Weak<AuthRequest>);
208 
209 impl TokenReceiver {
is_obsolete(&self) -> bool210     fn is_obsolete(&self) -> bool {
211         self.0.upgrade().is_none()
212     }
213 
add_auth_token(&self, hat: HardwareAuthToken)214     fn add_auth_token(&self, hat: HardwareAuthToken) {
215         if let Some(state_arc) = self.0.upgrade() {
216             state_arc.add_auth_token(hat);
217         }
218     }
219 }
220 
get_timestamp_token(challenge: i64) -> Result<TimeStampToken, Error>221 fn get_timestamp_token(challenge: i64) -> Result<TimeStampToken, Error> {
222     let dev = get_timestamp_service().expect(concat!(
223         "Secure Clock service must be present ",
224         "if TimeStampTokens are required."
225     ));
226     map_binder_status(dev.generateTimeStamp(challenge))
227 }
228 
timestamp_token_request(challenge: i64, sender: Sender<Result<TimeStampToken, Error>>)229 fn timestamp_token_request(challenge: i64, sender: Sender<Result<TimeStampToken, Error>>) {
230     if let Err(e) = sender.send(get_timestamp_token(challenge)) {
231         log::info!(
232             concat!("Receiver hung up ", "before timestamp token could be delivered. {:?}"),
233             e
234         );
235     }
236 }
237 
238 impl AuthInfo {
239     /// This function gets called after an operation was successfully created.
240     /// It makes all the preparations required, so that the operation has all the authentication
241     /// related artifacts to advance on update and finish.
finalize_create_authorization(&mut self, challenge: i64) -> Option<OperationChallenge>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 
258                 ASYNC_TASK.queue_hi(move |_| timestamp_token_request(challenge, sender));
259                 self.state = DeferredAuthState::Waiting(auth_request);
260                 Some(OperationChallenge { challenge })
261             }
262             DeferredAuthState::TimeStampRequired(hat) => {
263                 let hat = (*hat).clone();
264                 let (sender, receiver) = channel::<Result<TimeStampToken, Error>>();
265                 let auth_request = AuthRequest::timestamp(hat, receiver);
266                 ASYNC_TASK.queue_hi(move |_| timestamp_token_request(challenge, sender));
267                 self.state = DeferredAuthState::Waiting(auth_request);
268                 None
269             }
270             _ => None,
271         }
272     }
273 
274     /// This function is the authorization hook called before operation update.
275     /// It returns the auth tokens required by the operation to commence update.
before_update(&mut self) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>)>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.
282     /// The third token is a confirmation token.
before_finish( &mut self, ) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>, Option<Vec<u8>>)>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))
308     }
309 
310     /// This function is the authorization hook called after finish succeeded.
311     /// As of this writing it checks if the key was a limited use key. If so it updates the
312     /// use counter of the key in the database. When the use counter is depleted, the key gets
313     /// marked for deletion and the garbage collector is notified.
after_finish(&self) -> Result<()>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.
318             DB.with(|db| {
319                 db.borrow_mut()
320                     .check_and_update_key_usage_count(key_id)
321                     .context("Trying to update key usage count.")
322             })
323             .context(ks_err!())?;
324         }
325         Ok(())
326     }
327 
328     /// This function returns the auth tokens as needed by the ongoing operation or fails
329     /// with ErrorCode::KEY_USER_NOT_AUTHENTICATED. If this was called for the first time
330     /// after a deferred authorization was requested by finalize_create_authorization, this
331     /// function may block on the generation of a time stamp token. It then moves the
332     /// tokens into the DeferredAuthState::Token state for future use.
get_auth_tokens(&mut self) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>)>333     fn get_auth_tokens(&mut self) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>)> {
334         let deferred_tokens = if let DeferredAuthState::Waiting(ref auth_request) = self.state {
335             Some(auth_request.get_auth_tokens().context("In AuthInfo::get_auth_tokens.")?)
336         } else {
337             None
338         };
339 
340         if let Some((hat, tst)) = deferred_tokens {
341             self.state = DeferredAuthState::Token(hat, tst);
342         }
343 
344         match &self.state {
345             DeferredAuthState::NoAuthRequired => Ok((None, None)),
346             DeferredAuthState::Token(hat, tst) => Ok((Some((*hat).clone()), (*tst).clone())),
347             DeferredAuthState::OpAuthRequired
348             | DeferredAuthState::TimeStampedOpAuthRequired
349             | DeferredAuthState::TimeStampRequired(_) => {
350                 Err(Error::Km(ErrorCode::KEY_USER_NOT_AUTHENTICATED)).context(ks_err!(
351                     "No operation auth token requested??? \
352                     This should not happen."
353                 ))
354             }
355             // This should not be reachable, because it should have been handled above.
356             DeferredAuthState::Waiting(_) => {
357                 Err(Error::sys()).context(ks_err!("AuthInfo::get_auth_tokens: Cannot be reached.",))
358             }
359         }
360     }
361 }
362 
363 /// Enforcements data structure
364 #[derive(Default)]
365 pub struct Enforcements {
366     /// This hash set contains the user ids for whom the device is currently unlocked. If a user id
367     /// is not in the set, it implies that the device is locked for the user.
368     device_unlocked_set: Mutex<HashSet<i32>>,
369     /// This field maps outstanding auth challenges to their operations. When an auth token
370     /// with the right challenge is received it is passed to the map using
371     /// TokenReceiverMap::add_auth_token() which removes the entry from the map. If an entry goes
372     /// stale, because the operation gets dropped before an auth token is received, the map
373     /// is cleaned up in regular intervals.
374     op_auth_map: TokenReceiverMap,
375     /// The enforcement module will try to get a confirmation token from this channel whenever
376     /// an operation that requires confirmation finishes.
377     confirmation_token_receiver: Arc<Mutex<Option<Receiver<Vec<u8>>>>>,
378 }
379 
380 impl Enforcements {
381     /// Install the confirmation token receiver. The enforcement module will try to get a
382     /// confirmation token from this channel whenever an operation that requires confirmation
383     /// finishes.
install_confirmation_token_receiver( &self, confirmation_token_receiver: Receiver<Vec<u8>>, )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 
391     /// Checks if a create call is authorized, given key parameters and operation parameters.
392     /// It returns an optional immediate auth token which can be presented to begin, and an
393     /// AuthInfo object which stays with the authorized operation and is used to obtain
394     /// auth tokens and timestamp tokens as required by the operation.
395     /// With regard to auth tokens, the following steps are taken:
396     ///
397     /// If no key parameters are given (typically when the client is self managed
398     /// (see Domain.Blob)) nothing is enforced.
399     /// If the key is time-bound, find a matching auth token from the database.
400     /// If the above step is successful, and if requires_timestamp is given, the returned
401     /// 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)>402     pub fn authorize_create(
403         &self,
404         purpose: KeyPurpose,
405         key_properties: Option<&(i64, Vec<KeyParameter>)>,
406         op_params: &[KmKeyParameter],
407         requires_timestamp: bool,
408     ) -> Result<(Option<HardwareAuthToken>, AuthInfo)> {
409         let (key_id, key_params) = match key_properties {
410             Some((key_id, key_params)) => (*key_id, key_params),
411             None => {
412                 return Ok((
413                     None,
414                     AuthInfo {
415                         state: DeferredAuthState::NoAuthRequired,
416                         key_usage_limited: None,
417                         confirmation_token_receiver: None,
418                     },
419                 ));
420             }
421         };
422 
423         match purpose {
424             // Allow SIGN, DECRYPT for both symmetric and asymmetric keys.
425             KeyPurpose::SIGN | KeyPurpose::DECRYPT => {}
426             // Rule out WRAP_KEY purpose
427             KeyPurpose::WRAP_KEY => {
428                 return Err(Error::Km(Ec::INCOMPATIBLE_PURPOSE))
429                     .context(ks_err!("WRAP_KEY purpose is not allowed here.",));
430             }
431             // Allow AGREE_KEY for EC keys only.
432             KeyPurpose::AGREE_KEY => {
433                 for kp in key_params.iter() {
434                     if kp.get_tag() == Tag::ALGORITHM
435                         && *kp.key_parameter_value() != KeyParameterValue::Algorithm(Algorithm::EC)
436                     {
437                         return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE))
438                             .context(ks_err!("key agreement is only supported for EC keys.",));
439                     }
440                 }
441             }
442             KeyPurpose::VERIFY | KeyPurpose::ENCRYPT => {
443                 // We do not support ENCRYPT and VERIFY (the remaining two options of purpose) for
444                 // asymmetric keys.
445                 for kp in key_params.iter() {
446                     match *kp.key_parameter_value() {
447                         KeyParameterValue::Algorithm(Algorithm::RSA)
448                         | KeyParameterValue::Algorithm(Algorithm::EC) => {
449                             return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE)).context(ks_err!(
450                                 "public operations on asymmetric keys are \
451                                  not supported."
452                             ));
453                         }
454                         _ => {}
455                     }
456                 }
457             }
458             _ => {
459                 return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE))
460                     .context(ks_err!("authorize_create: specified purpose is not supported."));
461             }
462         }
463         // The following variables are to record information from key parameters to be used in
464         // enforcements, when two or more such pieces of information are required for enforcements.
465         // There is only one additional variable than what legacy keystore has, but this helps
466         // reduce the number of for loops on key parameters from 3 to 1, compared to legacy keystore
467         let mut key_purpose_authorized: bool = false;
468         let mut user_auth_type: Option<HardwareAuthenticatorType> = None;
469         let mut no_auth_required: bool = false;
470         let mut caller_nonce_allowed = false;
471         let mut user_id: i32 = -1;
472         let mut user_secure_ids = Vec::<i64>::new();
473         let mut key_time_out: Option<i64> = None;
474         let mut allow_while_on_body = false;
475         let mut unlocked_device_required = false;
476         let mut key_usage_limited: Option<i64> = None;
477         let mut confirmation_token_receiver: Option<Arc<Mutex<Option<Receiver<Vec<u8>>>>>> = None;
478         let mut max_boot_level: Option<i32> = None;
479 
480         // iterate through key parameters, recording information we need for authorization
481         // enforcements later, or enforcing authorizations in place, where applicable
482         for key_param in key_params.iter() {
483             match key_param.key_parameter_value() {
484                 KeyParameterValue::NoAuthRequired => {
485                     no_auth_required = true;
486                 }
487                 KeyParameterValue::AuthTimeout(t) => {
488                     key_time_out = Some(*t as i64);
489                 }
490                 KeyParameterValue::HardwareAuthenticatorType(a) => {
491                     user_auth_type = Some(*a);
492                 }
493                 KeyParameterValue::KeyPurpose(p) => {
494                     // The following check has the effect of key_params.contains(purpose)
495                     // Also, authorizing purpose can not be completed here, if there can be multiple
496                     // key parameters for KeyPurpose.
497                     key_purpose_authorized = key_purpose_authorized || *p == purpose;
498                 }
499                 KeyParameterValue::CallerNonce => {
500                     caller_nonce_allowed = true;
501                 }
502                 KeyParameterValue::ActiveDateTime(a) => {
503                     if !Enforcements::is_given_time_passed(*a, true) {
504                         return Err(Error::Km(Ec::KEY_NOT_YET_VALID))
505                             .context(ks_err!("key is not yet active."));
506                     }
507                 }
508                 KeyParameterValue::OriginationExpireDateTime(o) => {
509                     if (purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN)
510                         && Enforcements::is_given_time_passed(*o, false)
511                     {
512                         return Err(Error::Km(Ec::KEY_EXPIRED)).context(ks_err!("key is expired."));
513                     }
514                 }
515                 KeyParameterValue::UsageExpireDateTime(u) => {
516                     if (purpose == KeyPurpose::DECRYPT || purpose == KeyPurpose::VERIFY)
517                         && Enforcements::is_given_time_passed(*u, false)
518                     {
519                         return Err(Error::Km(Ec::KEY_EXPIRED)).context(ks_err!("key is expired."));
520                     }
521                 }
522                 KeyParameterValue::UserSecureID(s) => {
523                     user_secure_ids.push(*s);
524                 }
525                 KeyParameterValue::UserID(u) => {
526                     user_id = *u;
527                 }
528                 KeyParameterValue::UnlockedDeviceRequired => {
529                     unlocked_device_required = true;
530                 }
531                 KeyParameterValue::AllowWhileOnBody => {
532                     allow_while_on_body = true;
533                 }
534                 KeyParameterValue::UsageCountLimit(_) => {
535                     // We don't examine the limit here because this is enforced on finish.
536                     // Instead, we store the key_id so that finish can look up the key
537                     // in the database again and check and update the counter.
538                     key_usage_limited = Some(key_id);
539                 }
540                 KeyParameterValue::TrustedConfirmationRequired => {
541                     confirmation_token_receiver = Some(self.confirmation_token_receiver.clone());
542                 }
543                 KeyParameterValue::MaxBootLevel(level) => {
544                     max_boot_level = Some(*level);
545                 }
546                 // NOTE: as per offline discussion, sanitizing key parameters and rejecting
547                 // create operation if any non-allowed tags are present, is not done in
548                 // authorize_create (unlike in legacy keystore where AuthorizeBegin is rejected if
549                 // a subset of non-allowed tags are present). Because sanitizing key parameters
550                 // should have been done during generate/import key, by KeyMint.
551                 _ => { /*Do nothing on all the other key parameters, as in legacy keystore*/ }
552             }
553         }
554 
555         // authorize the purpose
556         if !key_purpose_authorized {
557             return Err(Error::Km(Ec::INCOMPATIBLE_PURPOSE))
558                 .context(ks_err!("the purpose is not authorized."));
559         }
560 
561         // if both NO_AUTH_REQUIRED and USER_SECURE_ID tags are present, return error
562         if !user_secure_ids.is_empty() && no_auth_required {
563             return Err(Error::Km(Ec::INVALID_KEY_BLOB))
564                 .context(ks_err!("key has both NO_AUTH_REQUIRED and USER_SECURE_ID tags."));
565         }
566 
567         // if either of auth_type or secure_id is present and the other is not present, return error
568         if (user_auth_type.is_some() && user_secure_ids.is_empty())
569             || (user_auth_type.is_none() && !user_secure_ids.is_empty())
570         {
571             return Err(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED)).context(ks_err!(
572                 "Auth required, but either auth type or secure ids \
573                  are not present."
574             ));
575         }
576 
577         // validate caller nonce for origination purposes
578         if (purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN)
579             && !caller_nonce_allowed
580             && op_params.iter().any(|kp| kp.tag == Tag::NONCE)
581         {
582             return Err(Error::Km(Ec::CALLER_NONCE_PROHIBITED))
583                 .context(ks_err!("NONCE is present, although CALLER_NONCE is not present"));
584         }
585 
586         if unlocked_device_required {
587             // check the device locked status. If locked, operations on the key are not
588             // allowed.
589             if self.is_device_locked(user_id) {
590                 return Err(Error::Km(Ec::DEVICE_LOCKED)).context(ks_err!("device is locked."));
591             }
592         }
593 
594         if let Some(level) = max_boot_level {
595             if !SUPER_KEY.read().unwrap().level_accessible(level) {
596                 return Err(Error::Km(Ec::BOOT_LEVEL_EXCEEDED))
597                     .context(ks_err!("boot level is too late."));
598             }
599         }
600 
601         if !unlocked_device_required && no_auth_required {
602             return Ok((
603                 None,
604                 AuthInfo {
605                     state: DeferredAuthState::NoAuthRequired,
606                     key_usage_limited,
607                     confirmation_token_receiver,
608                 },
609             ));
610         }
611 
612         let has_sids = !user_secure_ids.is_empty();
613 
614         let timeout_bound = key_time_out.is_some() && has_sids;
615 
616         let per_op_bound = key_time_out.is_none() && has_sids;
617 
618         let need_auth_token = timeout_bound || unlocked_device_required;
619 
620         let hat_and_last_off_body = if need_auth_token {
621             let hat_and_last_off_body = Self::find_auth_token(|hat: &AuthTokenEntry| {
622                 if let (Some(auth_type), true) = (user_auth_type, timeout_bound) {
623                     hat.satisfies(&user_secure_ids, auth_type)
624                 } else {
625                     unlocked_device_required
626                 }
627             });
628             Some(
629                 hat_and_last_off_body
630                     .ok_or(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
631                     .context(ks_err!("No suitable auth token found."))?,
632             )
633         } else {
634             None
635         };
636 
637         // Now check the validity of the auth token if the key is timeout bound.
638         let hat = match (hat_and_last_off_body, key_time_out) {
639             (Some((hat, last_off_body)), Some(key_time_out)) => {
640                 let now = MonotonicRawTime::now();
641                 let token_age = now
642                     .checked_sub(&hat.time_received())
643                     .ok_or_else(Error::sys)
644                     .context(ks_err!(
645                         "Overflow while computing Auth token validity. \
646                     Validity cannot be established."
647                     ))?;
648 
649                 let on_body_extended = allow_while_on_body && last_off_body < hat.time_received();
650 
651                 if token_age.seconds() > key_time_out && !on_body_extended {
652                     return Err(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
653                         .context(ks_err!("matching auth token is expired."));
654                 }
655                 Some(hat)
656             }
657             (Some((hat, _)), None) => Some(hat),
658             // If timeout_bound is true, above code must have retrieved a HAT or returned with
659             // KEY_USER_NOT_AUTHENTICATED. This arm should not be reachable.
660             (None, Some(_)) => panic!("Logical error."),
661             _ => None,
662         };
663 
664         Ok(match (hat, requires_timestamp, per_op_bound) {
665             // Per-op-bound and Some(hat) can only happen if we are both per-op bound and unlocked
666             // device required. In addition, this KM instance needs a timestamp token.
667             // So the HAT cannot be presented on create. So on update/finish we present both
668             // an per-op-bound auth token and a timestamp token.
669             (Some(_), true, true) => (None, DeferredAuthState::TimeStampedOpAuthRequired),
670             (Some(hat), true, false) => (
671                 Some(hat.auth_token().clone()),
672                 DeferredAuthState::TimeStampRequired(hat.take_auth_token()),
673             ),
674             (Some(hat), false, true) => {
675                 (Some(hat.take_auth_token()), DeferredAuthState::OpAuthRequired)
676             }
677             (Some(hat), false, false) => {
678                 (Some(hat.take_auth_token()), DeferredAuthState::NoAuthRequired)
679             }
680             (None, _, true) => (None, DeferredAuthState::OpAuthRequired),
681             (None, _, false) => (None, DeferredAuthState::NoAuthRequired),
682         })
683         .map(|(hat, state)| {
684             (hat, AuthInfo { state, key_usage_limited, confirmation_token_receiver })
685         })
686     }
687 
find_auth_token<F>(p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)> where F: Fn(&AuthTokenEntry) -> bool,688     fn find_auth_token<F>(p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
689     where
690         F: Fn(&AuthTokenEntry) -> bool,
691     {
692         DB.with(|db| db.borrow().find_auth_token_entry(p))
693     }
694 
695     /// Checks if the time now since epoch is greater than (or equal, if is_given_time_inclusive is
696     /// set) the given time (in milliseconds)
is_given_time_passed(given_time: i64, is_given_time_inclusive: bool) -> bool697     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
is_device_locked(&self, user_id: i32) -> bool714     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     }
720 
721     /// Sets the device locked status for the user. This method is called externally.
set_device_locked(&self, user_id: i32, device_locked_status: bool)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.
734     /// Then present the auth token to the op auth map. If an operation is waiting for this
735     /// auth token this fulfills the request and removes the receiver from the map.
add_auth_token(&self, hat: HardwareAuthToken)736     pub fn add_auth_token(&self, hat: HardwareAuthToken) {
737         DB.with(|db| db.borrow_mut().insert_auth_token(&hat));
738         self.op_auth_map.add_auth_token(hat);
739     }
740 
741     /// This allows adding an entry to the op_auth_map, indexed by the operation challenge.
742     /// This is to be called by create_operation, once it has received the operation challenge
743     /// from keymint for an operation whose authorization decision is OpAuthRequired, as signalled
744     /// by the DeferredAuthState.
register_op_auth_receiver(&self, challenge: i64, recv: TokenReceiver)745     fn register_op_auth_receiver(&self, challenge: i64, recv: TokenReceiver) {
746         self.op_auth_map.add_receiver(challenge, recv);
747     }
748 
749     /// 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>, ) -> SuperEncryptionType750     pub fn super_encryption_required(
751         domain: &Domain,
752         key_parameters: &[KeyParameter],
753         flags: Option<i32>,
754     ) -> SuperEncryptionType {
755         if let Some(flags) = flags {
756             if (flags & KEY_FLAG_AUTH_BOUND_WITHOUT_CRYPTOGRAPHIC_LSKF_BINDING) != 0 {
757                 return SuperEncryptionType::None;
758             }
759         }
760         // Each answer has a priority, numerically largest priority wins.
761         struct Candidate {
762             priority: u32,
763             enc_type: SuperEncryptionType,
764         }
765         let mut result = Candidate { priority: 0, enc_type: SuperEncryptionType::None };
766         for kp in key_parameters {
767             let t = match kp.key_parameter_value() {
768                 KeyParameterValue::MaxBootLevel(level) => {
769                     Candidate { priority: 3, enc_type: SuperEncryptionType::BootLevel(*level) }
770                 }
771                 KeyParameterValue::UnlockedDeviceRequired if *domain == Domain::APP => {
772                     Candidate { priority: 2, enc_type: SuperEncryptionType::ScreenLockBound }
773                 }
774                 KeyParameterValue::UserSecureID(_) if *domain == Domain::APP => {
775                     Candidate { priority: 1, enc_type: SuperEncryptionType::LskfBound }
776                 }
777                 _ => Candidate { priority: 0, enc_type: SuperEncryptionType::None },
778             };
779             if t.priority > result.priority {
780                 result = t;
781             }
782         }
783         result.enc_type
784     }
785 
786     /// Finds a matching auth token along with a timestamp token.
787     /// This method looks through auth-tokens cached by keystore which satisfy the given
788     /// authentication information (i.e. |secureUserId|).
789     /// The most recent matching auth token which has a |challenge| field which matches
790     /// the passed-in |challenge| parameter is returned.
791     /// In this case the |authTokenMaxAgeMillis| parameter is not used.
792     ///
793     /// Otherwise, the most recent matching auth token which is younger than |authTokenMaxAgeMillis|
794     /// is returned.
get_auth_tokens( &self, challenge: i64, secure_user_id: i64, auth_token_max_age_millis: i64, ) -> Result<(HardwareAuthToken, TimeStampToken)>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)
806         });
807 
808         let auth_token = if let Some((auth_token_entry, _)) = result {
809             auth_token_entry.take_auth_token()
810         } else {
811             // Filter the matching auth tokens by age.
812             if auth_token_max_age_millis != 0 {
813                 let now_in_millis = MonotonicRawTime::now();
814                 let result = Self::find_auth_token(|auth_token_entry: &AuthTokenEntry| {
815                     let token_valid = now_in_millis
816                         .checked_sub(&auth_token_entry.time_received())
817                         .map_or(false, |token_age_in_millis| {
818                             auth_token_max_age_millis > token_age_in_millis.milliseconds()
819                         });
820                     token_valid && auth_token_entry.satisfies(&sids, auth_type)
821                 });
822 
823                 if let Some((auth_token_entry, _)) = result {
824                     auth_token_entry.take_auth_token()
825                 } else {
826                     return Err(AuthzError::Rc(AuthzResponseCode::NO_AUTH_TOKEN_FOUND))
827                         .context(ks_err!("No auth token found."));
828                 }
829             } else {
830                 return Err(AuthzError::Rc(AuthzResponseCode::NO_AUTH_TOKEN_FOUND)).context(
831                     ks_err!(
832                         "No auth token found for \
833                     the given challenge and passed-in auth token max age is zero."
834                     ),
835                 );
836             }
837         };
838         // Wait and obtain the timestamp token from secure clock service.
839         let tst =
840             get_timestamp_token(challenge).context(ks_err!("Error in getting timestamp token."))?;
841         Ok((auth_token, tst))
842     }
843 }
844 
845 // TODO: Add tests to enforcement module (b/175578618).
846