blob: bee0e4b14fe63e03f6bde9c07caa304e90348708 [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.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080017use crate::error::{map_binder_status, Error, ErrorCode};
18use crate::globals::{get_timestamp_service, ASYNC_TASK, DB, ENFORCEMENTS};
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000019use crate::key_parameter::{KeyParameter, KeyParameterValue};
Qi Wub9433b52020-12-01 14:52:46 +080020use crate::{
21 database::{AuthTokenEntry, MonotonicRawTime},
22 gc::Gc,
23};
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000024use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Hasini Gunasinghe5112c702020-11-09 22:13:25 +000025 Algorithm::Algorithm, ErrorCode::ErrorCode as Ec, HardwareAuthToken::HardwareAuthToken,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080026 HardwareAuthenticatorType::HardwareAuthenticatorType,
27 KeyParameter::KeyParameter as KmKeyParameter, KeyPurpose::KeyPurpose, Tag::Tag,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080028};
29use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080030 ISecureClock::ISecureClock, TimeStampToken::TimeStampToken,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000031};
32use android_system_keystore2::aidl::android::system::keystore2::OperationChallenge::OperationChallenge;
33use anyhow::{Context, Result};
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080034use std::sync::{
35 mpsc::{channel, Receiver, Sender},
36 Arc, Mutex, Weak,
37};
Hasini Gunasinghe5112c702020-11-09 22:13:25 +000038use std::time::SystemTime;
Janis Danisevskisb1673db2021-02-08 18:11:57 -080039use std::{
40 collections::{HashMap, HashSet},
41 sync::mpsc::TryRecvError,
42};
Hasini Gunasinghe3410f792020-09-14 17:55:21 +000043
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080044#[derive(Debug)]
45enum AuthRequestState {
46 /// An outstanding per operation authorization request.
47 OpAuth,
48 /// An outstanding request for per operation authorization and secure timestamp.
49 TimeStampedOpAuth(Receiver<Result<TimeStampToken, Error>>),
50 /// An outstanding request for a timestamp token.
51 TimeStamp(Receiver<Result<TimeStampToken, Error>>),
52}
53
54#[derive(Debug)]
55struct AuthRequest {
56 state: AuthRequestState,
57 /// This need to be set to Some to fulfill a AuthRequestState::OpAuth or
58 /// AuthRequestState::TimeStampedOpAuth.
59 hat: Option<HardwareAuthToken>,
60}
61
62impl AuthRequest {
63 fn op_auth() -> Arc<Mutex<Self>> {
64 Arc::new(Mutex::new(Self { state: AuthRequestState::OpAuth, hat: None }))
65 }
66
67 fn timestamped_op_auth(receiver: Receiver<Result<TimeStampToken, Error>>) -> Arc<Mutex<Self>> {
68 Arc::new(Mutex::new(Self {
69 state: AuthRequestState::TimeStampedOpAuth(receiver),
70 hat: None,
71 }))
72 }
73
74 fn timestamp(
75 hat: HardwareAuthToken,
76 receiver: Receiver<Result<TimeStampToken, Error>>,
77 ) -> Arc<Mutex<Self>> {
78 Arc::new(Mutex::new(Self { state: AuthRequestState::TimeStamp(receiver), hat: Some(hat) }))
79 }
80
81 fn add_auth_token(&mut self, hat: HardwareAuthToken) {
82 self.hat = Some(hat)
83 }
84
85 fn get_auth_tokens(&mut self) -> Result<(HardwareAuthToken, Option<TimeStampToken>)> {
86 match (&self.state, self.hat.is_some()) {
87 (AuthRequestState::OpAuth, true) => Ok((self.hat.take().unwrap(), None)),
88 (AuthRequestState::TimeStampedOpAuth(recv), true)
89 | (AuthRequestState::TimeStamp(recv), true) => {
90 let result = recv.recv().context("In get_auth_tokens: Sender disconnected.")?;
91 let tst = result.context(concat!(
92 "In get_auth_tokens: Worker responded with error ",
93 "from generating timestamp token."
94 ))?;
95 Ok((self.hat.take().unwrap(), Some(tst)))
96 }
97 (_, false) => Err(Error::Km(ErrorCode::KEY_USER_NOT_AUTHENTICATED))
98 .context("In get_auth_tokens: No operation auth token received."),
99 }
100 }
101}
102
103/// DeferredAuthState describes how auth tokens and timestamp tokens need to be provided when
104/// updating and finishing an operation.
105#[derive(Debug)]
106enum DeferredAuthState {
107 /// Used when an operation does not require further authorization.
108 NoAuthRequired,
109 /// Indicates that the operation requires an operation specific token. This means we have
110 /// to return an operation challenge to the client which should reward us with an
111 /// operation specific auth token. If it is not provided before the client calls update
112 /// or finish, the operation fails as not authorized.
113 OpAuthRequired,
114 /// Indicates that the operation requires a time stamp token. The auth token was already
115 /// loaded from the database, but it has to be accompanied by a time stamp token to inform
116 /// the target KM with a different clock about the time on the authenticators.
117 TimeStampRequired(HardwareAuthToken),
118 /// Indicates that both an operation bound auth token and a verification token are
119 /// before the operation can commence.
120 TimeStampedOpAuthRequired,
121 /// In this state the auth info is waiting for the deferred authorizations to come in.
122 /// We block on timestamp tokens, because we can always make progress on these requests.
123 /// The per-op auth tokens might never come, which means we fail if the client calls
124 /// update or finish before we got a per-op auth token.
125 Waiting(Arc<Mutex<AuthRequest>>),
126 /// In this state we have gotten all of the required tokens, we just cache them to
127 /// be used when the operation progresses.
128 Token(HardwareAuthToken, Option<TimeStampToken>),
129}
130
131/// Auth info hold all of the authorization related information of an operation. It is stored
132/// in and owned by the operation. It is constructed by authorize_create and stays with the
133/// operation until it completes.
134#[derive(Debug)]
135pub struct AuthInfo {
136 state: DeferredAuthState,
Qi Wub9433b52020-12-01 14:52:46 +0800137 /// An optional key id required to update the usage count if the key usage is limited.
138 key_usage_limited: Option<i64>,
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800139 confirmation_token_receiver: Option<Arc<Mutex<Option<Receiver<Vec<u8>>>>>>,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800140}
141
142struct TokenReceiverMap {
143 /// The map maps an outstanding challenge to a TokenReceiver. If an incoming Hardware Auth
144 /// Token (HAT) has the map key in its challenge field, it gets passed to the TokenReceiver
145 /// and the entry is removed from the map. In the case where no HAT is received before the
146 /// corresponding operation gets dropped, the entry goes stale. So every time the cleanup
147 /// counter (second field in the tuple) turns 0, the map is cleaned from stale entries.
148 /// The cleanup counter is decremented every time a new receiver is added.
149 /// and reset to TokenReceiverMap::CLEANUP_PERIOD + 1 after each cleanup.
150 map_and_cleanup_counter: Mutex<(HashMap<i64, TokenReceiver>, u8)>,
151}
152
153impl Default for TokenReceiverMap {
154 fn default() -> Self {
155 Self { map_and_cleanup_counter: Mutex::new((HashMap::new(), Self::CLEANUP_PERIOD + 1)) }
156 }
157}
158
159impl TokenReceiverMap {
160 /// There is a chance that receivers may become stale because their operation is dropped
161 /// without ever being authorized. So occasionally we iterate through the map and throw
162 /// out obsolete entries.
163 /// This is the number of calls to add_receiver between cleanups.
164 const CLEANUP_PERIOD: u8 = 25;
165
166 pub fn add_auth_token(&self, hat: HardwareAuthToken) {
167 let mut map = self.map_and_cleanup_counter.lock().unwrap();
168 let (ref mut map, _) = *map;
169 if let Some((_, recv)) = map.remove_entry(&hat.challenge) {
170 recv.add_auth_token(hat);
171 }
172 }
173
174 pub fn add_receiver(&self, challenge: i64, recv: TokenReceiver) {
175 let mut map = self.map_and_cleanup_counter.lock().unwrap();
176 let (ref mut map, ref mut cleanup_counter) = *map;
177 map.insert(challenge, recv);
178
179 *cleanup_counter -= 1;
180 if *cleanup_counter == 0 {
181 map.retain(|_, v| !v.is_obsolete());
182 map.shrink_to_fit();
183 *cleanup_counter = Self::CLEANUP_PERIOD + 1;
184 }
185 }
186}
187
188#[derive(Debug)]
189struct TokenReceiver(Weak<Mutex<AuthRequest>>);
190
191impl TokenReceiver {
192 fn is_obsolete(&self) -> bool {
193 self.0.upgrade().is_none()
194 }
195
196 fn add_auth_token(&self, hat: HardwareAuthToken) {
197 if let Some(state_arc) = self.0.upgrade() {
198 let mut state = state_arc.lock().unwrap();
199 state.add_auth_token(hat);
200 }
201 }
202}
203
204fn get_timestamp_token(challenge: i64) -> Result<TimeStampToken, Error> {
205 let dev: Box<dyn ISecureClock> = get_timestamp_service()
206 .expect(concat!(
207 "Secure Clock service must be present ",
208 "if TimeStampTokens are required."
209 ))
210 .get_interface()
211 .expect("Fatal: Timestamp service does not implement ISecureClock.");
212 map_binder_status(dev.generateTimeStamp(challenge))
213}
214
215fn timestamp_token_request(challenge: i64, sender: Sender<Result<TimeStampToken, Error>>) {
216 if let Err(e) = sender.send(get_timestamp_token(challenge)) {
217 log::info!(
218 concat!(
219 "In timestamp_token_request: Operation hung up ",
220 "before timestamp token could be delivered. {:?}"
221 ),
222 e
223 );
224 }
225}
226
227impl AuthInfo {
228 /// This function gets called after an operation was successfully created.
229 /// It makes all the preparations required, so that the operation has all the authentication
230 /// related artifacts to advance on update and finish.
231 pub fn finalize_create_authorization(&mut self, challenge: i64) -> Option<OperationChallenge> {
232 match &self.state {
233 DeferredAuthState::OpAuthRequired => {
234 let auth_request = AuthRequest::op_auth();
235 let token_receiver = TokenReceiver(Arc::downgrade(&auth_request));
236 ENFORCEMENTS.register_op_auth_receiver(challenge, token_receiver);
237
238 self.state = DeferredAuthState::Waiting(auth_request);
239 Some(OperationChallenge { challenge })
240 }
241 DeferredAuthState::TimeStampedOpAuthRequired => {
242 let (sender, receiver) = channel::<Result<TimeStampToken, Error>>();
243 let auth_request = AuthRequest::timestamped_op_auth(receiver);
244 let token_receiver = TokenReceiver(Arc::downgrade(&auth_request));
245 ENFORCEMENTS.register_op_auth_receiver(challenge, token_receiver);
246
247 ASYNC_TASK.queue_hi(move || timestamp_token_request(challenge, sender));
248 self.state = DeferredAuthState::Waiting(auth_request);
249 Some(OperationChallenge { challenge })
250 }
251 DeferredAuthState::TimeStampRequired(hat) => {
252 let hat = (*hat).clone();
253 let (sender, receiver) = channel::<Result<TimeStampToken, Error>>();
254 let auth_request = AuthRequest::timestamp(hat, receiver);
255 ASYNC_TASK.queue_hi(move || timestamp_token_request(challenge, sender));
256 self.state = DeferredAuthState::Waiting(auth_request);
257 None
258 }
259 _ => None,
260 }
261 }
262
Qi Wub9433b52020-12-01 14:52:46 +0800263 /// This function is the authorization hook called before operation update.
264 /// It returns the auth tokens required by the operation to commence update.
265 pub fn before_update(&mut self) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>)> {
266 self.get_auth_tokens()
267 }
268
269 /// This function is the authorization hook called before operation finish.
270 /// It returns the auth tokens required by the operation to commence finish.
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800271 /// The third token is a confirmation token.
272 pub fn before_finish(
273 &mut self,
274 ) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>, Option<Vec<u8>>)> {
275 let mut confirmation_token: Option<Vec<u8>> = None;
276 if let Some(ref confirmation_token_receiver) = self.confirmation_token_receiver {
277 let locked_receiver = confirmation_token_receiver.lock().unwrap();
278 if let Some(ref receiver) = *locked_receiver {
279 loop {
280 match receiver.try_recv() {
281 // As long as we get tokens we loop and discard all but the most
282 // recent one.
283 Ok(t) => confirmation_token = Some(t),
284 Err(TryRecvError::Empty) => break,
285 Err(TryRecvError::Disconnected) => {
286 log::error!(concat!(
287 "We got disconnected from the APC service, ",
288 "this should never happen."
289 ));
290 break;
291 }
292 }
293 }
294 }
295 }
296 self.get_auth_tokens().map(|(hat, tst)| (hat, tst, confirmation_token))
Qi Wub9433b52020-12-01 14:52:46 +0800297 }
298
299 /// This function is the authorization hook called after finish succeeded.
300 /// As of this writing it checks if the key was a limited use key. If so it updates the
301 /// use counter of the key in the database. When the use counter is depleted, the key gets
302 /// marked for deletion and the garbage collector is notified.
303 pub fn after_finish(&self) -> Result<()> {
304 if let Some(key_id) = self.key_usage_limited {
305 // On the last successful use, the key gets deleted. In this case we
306 // have to notify the garbage collector.
307 let need_gc = DB
308 .with(|db| {
309 db.borrow_mut()
310 .check_and_update_key_usage_count(key_id)
311 .context("Trying to update key usage count.")
312 })
313 .context("In after_finish.")?;
314 if need_gc {
315 Gc::notify_gc();
316 }
317 }
318 Ok(())
319 }
320
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800321 /// This function returns the auth tokens as needed by the ongoing operation or fails
322 /// with ErrorCode::KEY_USER_NOT_AUTHENTICATED. If this was called for the first time
323 /// after a deferred authorization was requested by finalize_create_authorization, this
324 /// function may block on the generation of a time stamp token. It then moves the
325 /// tokens into the DeferredAuthState::Token state for future use.
Qi Wub9433b52020-12-01 14:52:46 +0800326 fn get_auth_tokens(&mut self) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>)> {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800327 let deferred_tokens = if let DeferredAuthState::Waiting(ref auth_request) = self.state {
328 let mut state = auth_request.lock().unwrap();
329 Some(state.get_auth_tokens().context("In AuthInfo::get_auth_tokens.")?)
330 } else {
331 None
332 };
333
334 if let Some((hat, tst)) = deferred_tokens {
335 self.state = DeferredAuthState::Token(hat, tst);
336 }
337
338 match &self.state {
339 DeferredAuthState::NoAuthRequired => Ok((None, None)),
340 DeferredAuthState::Token(hat, tst) => Ok((Some((*hat).clone()), (*tst).clone())),
341 DeferredAuthState::OpAuthRequired
342 | DeferredAuthState::TimeStampedOpAuthRequired
343 | DeferredAuthState::TimeStampRequired(_) => {
344 Err(Error::Km(ErrorCode::KEY_USER_NOT_AUTHENTICATED)).context(concat!(
345 "In AuthInfo::get_auth_tokens: No operation auth token requested??? ",
346 "This should not happen."
347 ))
348 }
349 // This should not be reachable, because it should have been handled above.
350 DeferredAuthState::Waiting(_) => {
351 Err(Error::sys()).context("In AuthInfo::get_auth_tokens: Cannot be reached.")
352 }
353 }
354 }
355}
356
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000357/// Enforcements data structure
358pub struct Enforcements {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800359 /// This hash set contains the user ids for whom the device is currently unlocked. If a user id
360 /// is not in the set, it implies that the device is locked for the user.
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000361 device_unlocked_set: Mutex<HashSet<i32>>,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800362 /// This field maps outstanding auth challenges to their operations. When an auth token
363 /// with the right challenge is received it is passed to the map using
364 /// TokenReceiverMap::add_auth_token() which removes the entry from the map. If an entry goes
365 /// stale, because the operation gets dropped before an auth token is received, the map
366 /// is cleaned up in regular intervals.
367 op_auth_map: TokenReceiverMap,
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800368 /// The enforcement module will try to get a confirmation token from this channel whenever
369 /// an operation that requires confirmation finishes.
370 confirmation_token_receiver: Arc<Mutex<Option<Receiver<Vec<u8>>>>>,
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000371}
372
373impl Enforcements {
Hasini Gunasinghef04d07a2020-11-25 22:41:35 +0000374 /// Creates an enforcement object with the two data structures it holds and the sender as None.
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000375 pub fn new() -> Self {
376 Enforcements {
377 device_unlocked_set: Mutex::new(HashSet::new()),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800378 op_auth_map: Default::default(),
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800379 confirmation_token_receiver: Default::default(),
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000380 }
381 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000382
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800383 /// Install the confirmation token receiver. The enforcement module will try to get a
384 /// confirmation token from this channel whenever an operation that requires confirmation
385 /// finishes.
386 pub fn install_confirmation_token_receiver(
387 &self,
388 confirmation_token_receiver: Receiver<Vec<u8>>,
389 ) {
390 *self.confirmation_token_receiver.lock().unwrap() = Some(confirmation_token_receiver);
391 }
392
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000393 /// Checks if a create call is authorized, given key parameters and operation parameters.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800394 /// It returns an optional immediate auth token which can be presented to begin, and an
395 /// AuthInfo object which stays with the authorized operation and is used to obtain
396 /// auth tokens and timestamp tokens as required by the operation.
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000397 /// With regard to auth tokens, the following steps are taken:
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800398 ///
399 /// If no key parameters are given (typically when the client is self managed
400 /// (see Domain.Blob)) nothing is enforced.
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000401 /// If the key is time-bound, find a matching auth token from the database.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800402 /// If the above step is successful, and if requires_timestamp is given, the returned
403 /// AuthInfo will provide a Timestamp token as appropriate.
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000404 pub fn authorize_create(
405 &self,
406 purpose: KeyPurpose,
Qi Wub9433b52020-12-01 14:52:46 +0800407 key_properties: Option<&(i64, Vec<KeyParameter>)>,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800408 op_params: &[KmKeyParameter],
409 requires_timestamp: bool,
410 ) -> Result<(Option<HardwareAuthToken>, AuthInfo)> {
Qi Wub9433b52020-12-01 14:52:46 +0800411 let (key_id, key_params) = match key_properties {
412 Some((key_id, key_params)) => (*key_id, key_params),
413 None => {
414 return Ok((
415 None,
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800416 AuthInfo {
417 state: DeferredAuthState::NoAuthRequired,
418 key_usage_limited: None,
419 confirmation_token_receiver: None,
420 },
Qi Wub9433b52020-12-01 14:52:46 +0800421 ))
422 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800423 };
424
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000425 match purpose {
426 // Allow SIGN, DECRYPT for both symmetric and asymmetric keys.
427 KeyPurpose::SIGN | KeyPurpose::DECRYPT => {}
428 // Rule out WRAP_KEY purpose
429 KeyPurpose::WRAP_KEY => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800430 return Err(Error::Km(Ec::INCOMPATIBLE_PURPOSE))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000431 .context("In authorize_create: WRAP_KEY purpose is not allowed here.");
432 }
Bram Bonnéa6b83822021-01-20 11:10:05 +0100433 // Allow AGREE_KEY for EC keys only.
434 KeyPurpose::AGREE_KEY => {
435 for kp in key_params.iter() {
436 if kp.get_tag() == Tag::ALGORITHM
437 && *kp.key_parameter_value() != KeyParameterValue::Algorithm(Algorithm::EC)
438 {
439 return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE)).context(
440 "In authorize_create: key agreement is only supported for EC keys.",
441 );
442 }
443 }
444 }
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000445 KeyPurpose::VERIFY | KeyPurpose::ENCRYPT => {
446 // We do not support ENCRYPT and VERIFY (the remaining two options of purpose) for
447 // asymmetric keys.
448 for kp in key_params.iter() {
449 match *kp.key_parameter_value() {
450 KeyParameterValue::Algorithm(Algorithm::RSA)
451 | KeyParameterValue::Algorithm(Algorithm::EC) => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800452 return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE)).context(
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000453 "In authorize_create: public operations on asymmetric keys are not
454 supported.",
455 );
456 }
457 _ => {}
458 }
459 }
460 }
461 _ => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800462 return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000463 .context("In authorize_create: specified purpose is not supported.");
464 }
465 }
466 // The following variables are to record information from key parameters to be used in
467 // enforcements, when two or more such pieces of information are required for enforcements.
468 // There is only one additional variable than what legacy keystore has, but this helps
469 // reduce the number of for loops on key parameters from 3 to 1, compared to legacy keystore
470 let mut key_purpose_authorized: bool = false;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000471 let mut user_auth_type: Option<HardwareAuthenticatorType> = None;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000472 let mut no_auth_required: bool = false;
473 let mut caller_nonce_allowed = false;
474 let mut user_id: i32 = -1;
475 let mut user_secure_ids = Vec::<i64>::new();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000476 let mut key_time_out: Option<i64> = None;
477 let mut allow_while_on_body = false;
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000478 let mut unlocked_device_required = false;
Qi Wub9433b52020-12-01 14:52:46 +0800479 let mut key_usage_limited: Option<i64> = None;
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800480 let mut confirmation_token_receiver: Option<Arc<Mutex<Option<Receiver<Vec<u8>>>>>> = None;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000481
482 // iterate through key parameters, recording information we need for authorization
483 // enforcements later, or enforcing authorizations in place, where applicable
484 for key_param in key_params.iter() {
485 match key_param.key_parameter_value() {
486 KeyParameterValue::NoAuthRequired => {
487 no_auth_required = true;
488 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000489 KeyParameterValue::AuthTimeout(t) => {
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000490 key_time_out = Some(*t as i64);
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000491 }
492 KeyParameterValue::HardwareAuthenticatorType(a) => {
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000493 user_auth_type = Some(*a);
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000494 }
495 KeyParameterValue::KeyPurpose(p) => {
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800496 // The following check has the effect of key_params.contains(purpose)
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000497 // Also, authorizing purpose can not be completed here, if there can be multiple
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800498 // key parameters for KeyPurpose.
499 key_purpose_authorized = key_purpose_authorized || *p == purpose;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000500 }
501 KeyParameterValue::CallerNonce => {
502 caller_nonce_allowed = true;
503 }
504 KeyParameterValue::ActiveDateTime(a) => {
505 if !Enforcements::is_given_time_passed(*a, true) {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800506 return Err(Error::Km(Ec::KEY_NOT_YET_VALID))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000507 .context("In authorize_create: key is not yet active.");
508 }
509 }
510 KeyParameterValue::OriginationExpireDateTime(o) => {
511 if (purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN)
512 && Enforcements::is_given_time_passed(*o, false)
513 {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800514 return Err(Error::Km(Ec::KEY_EXPIRED))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000515 .context("In authorize_create: key is expired.");
516 }
517 }
518 KeyParameterValue::UsageExpireDateTime(u) => {
519 if (purpose == KeyPurpose::DECRYPT || purpose == KeyPurpose::VERIFY)
520 && Enforcements::is_given_time_passed(*u, false)
521 {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800522 return Err(Error::Km(Ec::KEY_EXPIRED))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000523 .context("In authorize_create: 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 => {
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000533 unlocked_device_required = true;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000534 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000535 KeyParameterValue::AllowWhileOnBody => {
536 allow_while_on_body = true;
537 }
Qi Wub9433b52020-12-01 14:52:46 +0800538 KeyParameterValue::UsageCountLimit(_) => {
539 // We don't examine the limit here because this is enforced on finish.
540 // Instead, we store the key_id so that finish can look up the key
541 // in the database again and check and update the counter.
542 key_usage_limited = Some(key_id);
543 }
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800544 KeyParameterValue::TrustedConfirmationRequired => {
545 confirmation_token_receiver = Some(self.confirmation_token_receiver.clone());
546 }
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000547 // 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
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800550 // a subset of non-allowed tags are present). Because sanitizing key parameters
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000551 // 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 {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800558 return Err(Error::Km(Ec::INCOMPATIBLE_PURPOSE))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000559 .context("In authorize_create: 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 {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800564 return Err(Error::Km(Ec::INVALID_KEY_BLOB)).context(
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000565 "In authorize_create: key has both NO_AUTH_REQUIRED
566 and USER_SECURE_ID tags.",
567 );
568 }
569
570 // 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 +0000571 if (user_auth_type.is_some() && user_secure_ids.is_empty())
572 || (user_auth_type.is_none() && !user_secure_ids.is_empty())
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000573 {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800574 return Err(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED)).context(
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000575 "In authorize_create: Auth required, but either auth type or secure ids
576 are not present.",
577 );
578 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800579
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000580 // validate caller nonce for origination purposes
581 if (purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN)
582 && !caller_nonce_allowed
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800583 && op_params.iter().any(|kp| kp.tag == Tag::NONCE)
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000584 {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800585 return Err(Error::Km(Ec::CALLER_NONCE_PROHIBITED)).context(
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000586 "In authorize_create, NONCE is present,
587 although CALLER_NONCE is not present",
588 );
589 }
590
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000591 if unlocked_device_required {
592 // check the device locked status. If locked, operations on the key are not
593 // allowed.
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000594 if self.is_device_locked(user_id) {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800595 return Err(Error::Km(Ec::DEVICE_LOCKED))
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000596 .context("In authorize_create: device is locked.");
597 }
598 }
599
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800600 if !unlocked_device_required && no_auth_required {
Qi Wub9433b52020-12-01 14:52:46 +0800601 return Ok((
602 None,
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800603 AuthInfo {
604 state: DeferredAuthState::NoAuthRequired,
605 key_usage_limited,
606 confirmation_token_receiver,
607 },
Qi Wub9433b52020-12-01 14:52:46 +0800608 ));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000609 }
610
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800611 let has_sids = !user_secure_ids.is_empty();
612
613 let timeout_bound = key_time_out.is_some() && has_sids;
614
615 let per_op_bound = key_time_out.is_none() && has_sids;
616
617 let need_auth_token = timeout_bound || unlocked_device_required;
618
619 let hat_and_last_off_body = if need_auth_token {
620 let hat_and_last_off_body = Self::find_auth_token(|hat: &AuthTokenEntry| {
621 if let (Some(auth_type), true) = (user_auth_type, has_sids) {
622 hat.satisfies(&user_secure_ids, auth_type)
623 } else {
624 unlocked_device_required
625 }
626 })
627 .context("In authorize_create: Trying to get required auth token.")?;
628 Some(
629 hat_and_last_off_body
630 .ok_or(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
631 .context("In authorize_create: 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(concat!(
645 "In authorize_create: 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("In authorize_create: 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 (None, DeferredAuthState::TimeStampRequired(hat.take_auth_token()))
672 }
673 (Some(hat), false, true) => {
674 (Some(hat.take_auth_token()), DeferredAuthState::OpAuthRequired)
675 }
676 (Some(hat), false, false) => {
677 (Some(hat.take_auth_token()), DeferredAuthState::NoAuthRequired)
678 }
679 (None, _, true) => (None, DeferredAuthState::OpAuthRequired),
680 (None, _, false) => (None, DeferredAuthState::NoAuthRequired),
681 })
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800682 .map(|(hat, state)| {
683 (hat, AuthInfo { state, key_usage_limited, confirmation_token_receiver })
684 })
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800685 }
686
687 fn find_auth_token<F>(p: F) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
688 where
689 F: Fn(&AuthTokenEntry) -> bool,
690 {
691 DB.with(|db| {
692 let mut db = db.borrow_mut();
693 db.find_auth_token_entry(p).context("Trying to find auth token.")
694 })
695 .context("In find_auth_token.")
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000696 }
697
698 /// Checks if the time now since epoch is greater than (or equal, if is_given_time_inclusive is
699 /// set) the given time (in milliseconds)
700 fn is_given_time_passed(given_time: i64, is_given_time_inclusive: bool) -> bool {
701 let duration_since_epoch = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH);
702
703 let time_since_epoch = match duration_since_epoch {
704 Ok(duration) => duration.as_millis(),
705 Err(_) => return false,
706 };
707
708 if is_given_time_inclusive {
709 time_since_epoch >= (given_time as u128)
710 } else {
711 time_since_epoch > (given_time as u128)
712 }
713 }
714
715 /// Check if the device is locked for the given user. If there's no entry yet for the user,
716 /// we assume that the device is locked
717 fn is_device_locked(&self, user_id: i32) -> bool {
718 // unwrap here because there's no way this mutex guard can be poisoned and
719 // because there's no way to recover, even if it is poisoned.
720 let set = self.device_unlocked_set.lock().unwrap();
721 !set.contains(&user_id)
722 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000723
724 /// Sets the device locked status for the user. This method is called externally.
725 pub fn set_device_locked(&self, user_id: i32, device_locked_status: bool) {
726 // unwrap here because there's no way this mutex guard can be poisoned and
727 // because there's no way to recover, even if it is poisoned.
728 let mut set = self.device_unlocked_set.lock().unwrap();
729 if device_locked_status {
730 set.remove(&user_id);
731 } else {
732 set.insert(user_id);
733 }
734 }
735
736 /// Add this auth token to the database.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800737 /// Then present the auth token to the op auth map. If an operation is waiting for this
738 /// auth token this fulfills the request and removes the receiver from the map.
739 pub fn add_auth_token(&self, hat: HardwareAuthToken) -> Result<()> {
740 DB.with(|db| db.borrow_mut().insert_auth_token(&hat)).context("In add_auth_token.")?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000741
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800742 self.op_auth_map.add_auth_token(hat);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000743 Ok(())
744 }
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000745
746 /// This allows adding an entry to the op_auth_map, indexed by the operation challenge.
747 /// This is to be called by create_operation, once it has received the operation challenge
748 /// from keymint for an operation whose authorization decision is OpAuthRequired, as signalled
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800749 /// by the DeferredAuthState.
750 fn register_op_auth_receiver(&self, challenge: i64, recv: TokenReceiver) {
751 self.op_auth_map.add_receiver(challenge, recv);
Hasini Gunasinghef04d07a2020-11-25 22:41:35 +0000752 }
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000753}
754
755impl Default for Enforcements {
756 fn default() -> Self {
757 Self::new()
758 }
759}
760
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000761// TODO: Add tests to enforcement module (b/175578618).