blob: 9c3bc89faa73429fa1d90c8aa82f44a81ebbf591 [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 Danisevskis7e8b4622021-02-13 10:01:59 -080017use crate::database::{AuthTokenEntry, MonotonicRawTime};
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080018use crate::error::{map_binder_status, Error, ErrorCode};
19use crate::globals::{get_timestamp_service, ASYNC_TASK, DB, ENFORCEMENTS};
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000020use crate::key_parameter::{KeyParameter, KeyParameterValue};
21use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Hasini Gunasinghe5112c702020-11-09 22:13:25 +000022 Algorithm::Algorithm, ErrorCode::ErrorCode as Ec, HardwareAuthToken::HardwareAuthToken,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080023 HardwareAuthenticatorType::HardwareAuthenticatorType,
24 KeyParameter::KeyParameter as KmKeyParameter, KeyPurpose::KeyPurpose, Tag::Tag,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080025};
26use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080027 ISecureClock::ISecureClock, TimeStampToken::TimeStampToken,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000028};
29use android_system_keystore2::aidl::android::system::keystore2::OperationChallenge::OperationChallenge;
Stephen Crane221bbb52020-12-16 15:52:10 -080030use android_system_keystore2::binder::Strong;
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000031use anyhow::{Context, Result};
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080032use std::sync::{
33 mpsc::{channel, Receiver, Sender},
34 Arc, Mutex, Weak,
35};
Hasini Gunasinghe5112c702020-11-09 22:13:25 +000036use std::time::SystemTime;
Janis Danisevskisb1673db2021-02-08 18:11:57 -080037use std::{
38 collections::{HashMap, HashSet},
39 sync::mpsc::TryRecvError,
40};
Hasini Gunasinghe3410f792020-09-14 17:55:21 +000041
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080042#[derive(Debug)]
43enum AuthRequestState {
44 /// An outstanding per operation authorization request.
45 OpAuth,
46 /// An outstanding request for per operation authorization and secure timestamp.
47 TimeStampedOpAuth(Receiver<Result<TimeStampToken, Error>>),
48 /// An outstanding request for a timestamp token.
49 TimeStamp(Receiver<Result<TimeStampToken, Error>>),
50}
51
52#[derive(Debug)]
53struct AuthRequest {
54 state: AuthRequestState,
55 /// This need to be set to Some to fulfill a AuthRequestState::OpAuth or
56 /// AuthRequestState::TimeStampedOpAuth.
57 hat: Option<HardwareAuthToken>,
58}
59
60impl AuthRequest {
61 fn op_auth() -> Arc<Mutex<Self>> {
62 Arc::new(Mutex::new(Self { state: AuthRequestState::OpAuth, hat: None }))
63 }
64
65 fn timestamped_op_auth(receiver: Receiver<Result<TimeStampToken, Error>>) -> Arc<Mutex<Self>> {
66 Arc::new(Mutex::new(Self {
67 state: AuthRequestState::TimeStampedOpAuth(receiver),
68 hat: None,
69 }))
70 }
71
72 fn timestamp(
73 hat: HardwareAuthToken,
74 receiver: Receiver<Result<TimeStampToken, Error>>,
75 ) -> Arc<Mutex<Self>> {
76 Arc::new(Mutex::new(Self { state: AuthRequestState::TimeStamp(receiver), hat: Some(hat) }))
77 }
78
79 fn add_auth_token(&mut self, hat: HardwareAuthToken) {
80 self.hat = Some(hat)
81 }
82
83 fn get_auth_tokens(&mut self) -> Result<(HardwareAuthToken, Option<TimeStampToken>)> {
84 match (&self.state, self.hat.is_some()) {
85 (AuthRequestState::OpAuth, true) => Ok((self.hat.take().unwrap(), None)),
86 (AuthRequestState::TimeStampedOpAuth(recv), true)
87 | (AuthRequestState::TimeStamp(recv), true) => {
88 let result = recv.recv().context("In get_auth_tokens: Sender disconnected.")?;
89 let tst = result.context(concat!(
90 "In get_auth_tokens: Worker responded with error ",
91 "from generating timestamp token."
92 ))?;
93 Ok((self.hat.take().unwrap(), Some(tst)))
94 }
95 (_, false) => Err(Error::Km(ErrorCode::KEY_USER_NOT_AUTHENTICATED))
96 .context("In get_auth_tokens: No operation auth token received."),
97 }
98 }
99}
100
101/// DeferredAuthState describes how auth tokens and timestamp tokens need to be provided when
102/// updating and finishing an operation.
103#[derive(Debug)]
104enum DeferredAuthState {
105 /// Used when an operation does not require further authorization.
106 NoAuthRequired,
107 /// Indicates that the operation requires an operation specific token. This means we have
108 /// to return an operation challenge to the client which should reward us with an
109 /// operation specific auth token. If it is not provided before the client calls update
110 /// or finish, the operation fails as not authorized.
111 OpAuthRequired,
112 /// Indicates that the operation requires a time stamp token. The auth token was already
113 /// loaded from the database, but it has to be accompanied by a time stamp token to inform
114 /// the target KM with a different clock about the time on the authenticators.
115 TimeStampRequired(HardwareAuthToken),
116 /// Indicates that both an operation bound auth token and a verification token are
117 /// before the operation can commence.
118 TimeStampedOpAuthRequired,
119 /// In this state the auth info is waiting for the deferred authorizations to come in.
120 /// We block on timestamp tokens, because we can always make progress on these requests.
121 /// The per-op auth tokens might never come, which means we fail if the client calls
122 /// update or finish before we got a per-op auth token.
123 Waiting(Arc<Mutex<AuthRequest>>),
124 /// In this state we have gotten all of the required tokens, we just cache them to
125 /// be used when the operation progresses.
126 Token(HardwareAuthToken, Option<TimeStampToken>),
127}
128
129/// Auth info hold all of the authorization related information of an operation. It is stored
130/// in and owned by the operation. It is constructed by authorize_create and stays with the
131/// operation until it completes.
132#[derive(Debug)]
133pub struct AuthInfo {
134 state: DeferredAuthState,
Qi Wub9433b52020-12-01 14:52:46 +0800135 /// An optional key id required to update the usage count if the key usage is limited.
136 key_usage_limited: Option<i64>,
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800137 confirmation_token_receiver: Option<Arc<Mutex<Option<Receiver<Vec<u8>>>>>>,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800138}
139
140struct TokenReceiverMap {
141 /// The map maps an outstanding challenge to a TokenReceiver. If an incoming Hardware Auth
142 /// Token (HAT) has the map key in its challenge field, it gets passed to the TokenReceiver
143 /// and the entry is removed from the map. In the case where no HAT is received before the
144 /// corresponding operation gets dropped, the entry goes stale. So every time the cleanup
145 /// counter (second field in the tuple) turns 0, the map is cleaned from stale entries.
146 /// The cleanup counter is decremented every time a new receiver is added.
147 /// and reset to TokenReceiverMap::CLEANUP_PERIOD + 1 after each cleanup.
148 map_and_cleanup_counter: Mutex<(HashMap<i64, TokenReceiver>, u8)>,
149}
150
151impl Default for TokenReceiverMap {
152 fn default() -> Self {
153 Self { map_and_cleanup_counter: Mutex::new((HashMap::new(), Self::CLEANUP_PERIOD + 1)) }
154 }
155}
156
157impl TokenReceiverMap {
158 /// There is a chance that receivers may become stale because their operation is dropped
159 /// without ever being authorized. So occasionally we iterate through the map and throw
160 /// out obsolete entries.
161 /// This is the number of calls to add_receiver between cleanups.
162 const CLEANUP_PERIOD: u8 = 25;
163
164 pub fn add_auth_token(&self, hat: HardwareAuthToken) {
165 let mut map = self.map_and_cleanup_counter.lock().unwrap();
166 let (ref mut map, _) = *map;
167 if let Some((_, recv)) = map.remove_entry(&hat.challenge) {
168 recv.add_auth_token(hat);
169 }
170 }
171
172 pub fn add_receiver(&self, challenge: i64, recv: TokenReceiver) {
173 let mut map = self.map_and_cleanup_counter.lock().unwrap();
174 let (ref mut map, ref mut cleanup_counter) = *map;
175 map.insert(challenge, recv);
176
177 *cleanup_counter -= 1;
178 if *cleanup_counter == 0 {
179 map.retain(|_, v| !v.is_obsolete());
180 map.shrink_to_fit();
181 *cleanup_counter = Self::CLEANUP_PERIOD + 1;
182 }
183 }
184}
185
186#[derive(Debug)]
187struct TokenReceiver(Weak<Mutex<AuthRequest>>);
188
189impl TokenReceiver {
190 fn is_obsolete(&self) -> bool {
191 self.0.upgrade().is_none()
192 }
193
194 fn add_auth_token(&self, hat: HardwareAuthToken) {
195 if let Some(state_arc) = self.0.upgrade() {
196 let mut state = state_arc.lock().unwrap();
197 state.add_auth_token(hat);
198 }
199 }
200}
201
202fn get_timestamp_token(challenge: i64) -> Result<TimeStampToken, Error> {
Stephen Crane221bbb52020-12-16 15:52:10 -0800203 let dev: Strong<dyn ISecureClock> = get_timestamp_service()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800204 .expect(concat!(
205 "Secure Clock service must be present ",
206 "if TimeStampTokens are required."
207 ))
208 .get_interface()
209 .expect("Fatal: Timestamp service does not implement ISecureClock.");
210 map_binder_status(dev.generateTimeStamp(challenge))
211}
212
213fn timestamp_token_request(challenge: i64, sender: Sender<Result<TimeStampToken, Error>>) {
214 if let Err(e) = sender.send(get_timestamp_token(challenge)) {
215 log::info!(
216 concat!(
217 "In timestamp_token_request: Operation hung up ",
218 "before timestamp token could be delivered. {:?}"
219 ),
220 e
221 );
222 }
223}
224
225impl AuthInfo {
226 /// This function gets called after an operation was successfully created.
227 /// It makes all the preparations required, so that the operation has all the authentication
228 /// related artifacts to advance on update and finish.
229 pub fn finalize_create_authorization(&mut self, challenge: i64) -> Option<OperationChallenge> {
230 match &self.state {
231 DeferredAuthState::OpAuthRequired => {
232 let auth_request = AuthRequest::op_auth();
233 let token_receiver = TokenReceiver(Arc::downgrade(&auth_request));
234 ENFORCEMENTS.register_op_auth_receiver(challenge, token_receiver);
235
236 self.state = DeferredAuthState::Waiting(auth_request);
237 Some(OperationChallenge { challenge })
238 }
239 DeferredAuthState::TimeStampedOpAuthRequired => {
240 let (sender, receiver) = channel::<Result<TimeStampToken, Error>>();
241 let auth_request = AuthRequest::timestamped_op_auth(receiver);
242 let token_receiver = TokenReceiver(Arc::downgrade(&auth_request));
243 ENFORCEMENTS.register_op_auth_receiver(challenge, token_receiver);
244
Janis Danisevskis40f0e6b2021-02-10 15:48:44 -0800245 ASYNC_TASK.queue_hi(move |_| timestamp_token_request(challenge, sender));
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800246 self.state = DeferredAuthState::Waiting(auth_request);
247 Some(OperationChallenge { challenge })
248 }
249 DeferredAuthState::TimeStampRequired(hat) => {
250 let hat = (*hat).clone();
251 let (sender, receiver) = channel::<Result<TimeStampToken, Error>>();
252 let auth_request = AuthRequest::timestamp(hat, receiver);
Janis Danisevskis40f0e6b2021-02-10 15:48:44 -0800253 ASYNC_TASK.queue_hi(move |_| timestamp_token_request(challenge, sender));
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800254 self.state = DeferredAuthState::Waiting(auth_request);
255 None
256 }
257 _ => None,
258 }
259 }
260
Qi Wub9433b52020-12-01 14:52:46 +0800261 /// This function is the authorization hook called before operation update.
262 /// It returns the auth tokens required by the operation to commence update.
263 pub fn before_update(&mut self) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>)> {
264 self.get_auth_tokens()
265 }
266
267 /// This function is the authorization hook called before operation finish.
268 /// It returns the auth tokens required by the operation to commence finish.
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800269 /// The third token is a confirmation token.
270 pub fn before_finish(
271 &mut self,
272 ) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>, Option<Vec<u8>>)> {
273 let mut confirmation_token: Option<Vec<u8>> = None;
274 if let Some(ref confirmation_token_receiver) = self.confirmation_token_receiver {
275 let locked_receiver = confirmation_token_receiver.lock().unwrap();
276 if let Some(ref receiver) = *locked_receiver {
277 loop {
278 match receiver.try_recv() {
279 // As long as we get tokens we loop and discard all but the most
280 // recent one.
281 Ok(t) => confirmation_token = Some(t),
282 Err(TryRecvError::Empty) => break,
283 Err(TryRecvError::Disconnected) => {
284 log::error!(concat!(
285 "We got disconnected from the APC service, ",
286 "this should never happen."
287 ));
288 break;
289 }
290 }
291 }
292 }
293 }
294 self.get_auth_tokens().map(|(hat, tst)| (hat, tst, confirmation_token))
Qi Wub9433b52020-12-01 14:52:46 +0800295 }
296
297 /// This function is the authorization hook called after finish succeeded.
298 /// As of this writing it checks if the key was a limited use key. If so it updates the
299 /// use counter of the key in the database. When the use counter is depleted, the key gets
300 /// marked for deletion and the garbage collector is notified.
301 pub fn after_finish(&self) -> Result<()> {
302 if let Some(key_id) = self.key_usage_limited {
303 // On the last successful use, the key gets deleted. In this case we
304 // have to notify the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800305 DB.with(|db| {
306 db.borrow_mut()
307 .check_and_update_key_usage_count(key_id)
308 .context("Trying to update key usage count.")
309 })
310 .context("In after_finish.")?;
Qi Wub9433b52020-12-01 14:52:46 +0800311 }
312 Ok(())
313 }
314
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800315 /// This function returns the auth tokens as needed by the ongoing operation or fails
316 /// with ErrorCode::KEY_USER_NOT_AUTHENTICATED. If this was called for the first time
317 /// after a deferred authorization was requested by finalize_create_authorization, this
318 /// function may block on the generation of a time stamp token. It then moves the
319 /// tokens into the DeferredAuthState::Token state for future use.
Qi Wub9433b52020-12-01 14:52:46 +0800320 fn get_auth_tokens(&mut self) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>)> {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800321 let deferred_tokens = if let DeferredAuthState::Waiting(ref auth_request) = self.state {
322 let mut state = auth_request.lock().unwrap();
323 Some(state.get_auth_tokens().context("In AuthInfo::get_auth_tokens.")?)
324 } else {
325 None
326 };
327
328 if let Some((hat, tst)) = deferred_tokens {
329 self.state = DeferredAuthState::Token(hat, tst);
330 }
331
332 match &self.state {
333 DeferredAuthState::NoAuthRequired => Ok((None, None)),
334 DeferredAuthState::Token(hat, tst) => Ok((Some((*hat).clone()), (*tst).clone())),
335 DeferredAuthState::OpAuthRequired
336 | DeferredAuthState::TimeStampedOpAuthRequired
337 | DeferredAuthState::TimeStampRequired(_) => {
338 Err(Error::Km(ErrorCode::KEY_USER_NOT_AUTHENTICATED)).context(concat!(
339 "In AuthInfo::get_auth_tokens: No operation auth token requested??? ",
340 "This should not happen."
341 ))
342 }
343 // This should not be reachable, because it should have been handled above.
344 DeferredAuthState::Waiting(_) => {
345 Err(Error::sys()).context("In AuthInfo::get_auth_tokens: Cannot be reached.")
346 }
347 }
348 }
349}
350
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000351/// Enforcements data structure
352pub struct Enforcements {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800353 /// This hash set contains the user ids for whom the device is currently unlocked. If a user id
354 /// is not in the set, it implies that the device is locked for the user.
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000355 device_unlocked_set: Mutex<HashSet<i32>>,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800356 /// This field maps outstanding auth challenges to their operations. When an auth token
357 /// with the right challenge is received it is passed to the map using
358 /// TokenReceiverMap::add_auth_token() which removes the entry from the map. If an entry goes
359 /// stale, because the operation gets dropped before an auth token is received, the map
360 /// is cleaned up in regular intervals.
361 op_auth_map: TokenReceiverMap,
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800362 /// The enforcement module will try to get a confirmation token from this channel whenever
363 /// an operation that requires confirmation finishes.
364 confirmation_token_receiver: Arc<Mutex<Option<Receiver<Vec<u8>>>>>,
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000365}
366
367impl Enforcements {
Hasini Gunasinghef04d07a2020-11-25 22:41:35 +0000368 /// Creates an enforcement object with the two data structures it holds and the sender as None.
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000369 pub fn new() -> Self {
370 Enforcements {
371 device_unlocked_set: Mutex::new(HashSet::new()),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800372 op_auth_map: Default::default(),
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800373 confirmation_token_receiver: Default::default(),
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000374 }
375 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000376
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800377 /// Install the confirmation token receiver. The enforcement module will try to get a
378 /// confirmation token from this channel whenever an operation that requires confirmation
379 /// finishes.
380 pub fn install_confirmation_token_receiver(
381 &self,
382 confirmation_token_receiver: Receiver<Vec<u8>>,
383 ) {
384 *self.confirmation_token_receiver.lock().unwrap() = Some(confirmation_token_receiver);
385 }
386
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000387 /// Checks if a create call is authorized, given key parameters and operation parameters.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800388 /// It returns an optional immediate auth token which can be presented to begin, and an
389 /// AuthInfo object which stays with the authorized operation and is used to obtain
390 /// auth tokens and timestamp tokens as required by the operation.
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000391 /// With regard to auth tokens, the following steps are taken:
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800392 ///
393 /// If no key parameters are given (typically when the client is self managed
394 /// (see Domain.Blob)) nothing is enforced.
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000395 /// If the key is time-bound, find a matching auth token from the database.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800396 /// If the above step is successful, and if requires_timestamp is given, the returned
397 /// AuthInfo will provide a Timestamp token as appropriate.
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000398 pub fn authorize_create(
399 &self,
400 purpose: KeyPurpose,
Qi Wub9433b52020-12-01 14:52:46 +0800401 key_properties: Option<&(i64, Vec<KeyParameter>)>,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800402 op_params: &[KmKeyParameter],
403 requires_timestamp: bool,
404 ) -> Result<(Option<HardwareAuthToken>, AuthInfo)> {
Qi Wub9433b52020-12-01 14:52:46 +0800405 let (key_id, key_params) = match key_properties {
406 Some((key_id, key_params)) => (*key_id, key_params),
407 None => {
408 return Ok((
409 None,
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800410 AuthInfo {
411 state: DeferredAuthState::NoAuthRequired,
412 key_usage_limited: None,
413 confirmation_token_receiver: None,
414 },
Qi Wub9433b52020-12-01 14:52:46 +0800415 ))
416 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800417 };
418
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000419 match purpose {
420 // Allow SIGN, DECRYPT for both symmetric and asymmetric keys.
421 KeyPurpose::SIGN | KeyPurpose::DECRYPT => {}
422 // Rule out WRAP_KEY purpose
423 KeyPurpose::WRAP_KEY => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800424 return Err(Error::Km(Ec::INCOMPATIBLE_PURPOSE))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000425 .context("In authorize_create: WRAP_KEY purpose is not allowed here.");
426 }
Bram Bonnéa6b83822021-01-20 11:10:05 +0100427 // Allow AGREE_KEY for EC keys only.
428 KeyPurpose::AGREE_KEY => {
429 for kp in key_params.iter() {
430 if kp.get_tag() == Tag::ALGORITHM
431 && *kp.key_parameter_value() != KeyParameterValue::Algorithm(Algorithm::EC)
432 {
433 return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE)).context(
434 "In authorize_create: key agreement is only supported for EC keys.",
435 );
436 }
437 }
438 }
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000439 KeyPurpose::VERIFY | KeyPurpose::ENCRYPT => {
440 // We do not support ENCRYPT and VERIFY (the remaining two options of purpose) for
441 // asymmetric keys.
442 for kp in key_params.iter() {
443 match *kp.key_parameter_value() {
444 KeyParameterValue::Algorithm(Algorithm::RSA)
445 | KeyParameterValue::Algorithm(Algorithm::EC) => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800446 return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE)).context(
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000447 "In authorize_create: public operations on asymmetric keys are not
448 supported.",
449 );
450 }
451 _ => {}
452 }
453 }
454 }
455 _ => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800456 return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000457 .context("In authorize_create: specified purpose is not supported.");
458 }
459 }
460 // The following variables are to record information from key parameters to be used in
461 // enforcements, when two or more such pieces of information are required for enforcements.
462 // There is only one additional variable than what legacy keystore has, but this helps
463 // reduce the number of for loops on key parameters from 3 to 1, compared to legacy keystore
464 let mut key_purpose_authorized: bool = false;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000465 let mut user_auth_type: Option<HardwareAuthenticatorType> = None;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000466 let mut no_auth_required: bool = false;
467 let mut caller_nonce_allowed = false;
468 let mut user_id: i32 = -1;
469 let mut user_secure_ids = Vec::<i64>::new();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000470 let mut key_time_out: Option<i64> = None;
471 let mut allow_while_on_body = false;
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000472 let mut unlocked_device_required = false;
Qi Wub9433b52020-12-01 14:52:46 +0800473 let mut key_usage_limited: Option<i64> = None;
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800474 let mut confirmation_token_receiver: Option<Arc<Mutex<Option<Receiver<Vec<u8>>>>>> = None;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000475
476 // iterate through key parameters, recording information we need for authorization
477 // enforcements later, or enforcing authorizations in place, where applicable
478 for key_param in key_params.iter() {
479 match key_param.key_parameter_value() {
480 KeyParameterValue::NoAuthRequired => {
481 no_auth_required = true;
482 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000483 KeyParameterValue::AuthTimeout(t) => {
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000484 key_time_out = Some(*t as i64);
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000485 }
486 KeyParameterValue::HardwareAuthenticatorType(a) => {
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000487 user_auth_type = Some(*a);
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000488 }
489 KeyParameterValue::KeyPurpose(p) => {
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800490 // The following check has the effect of key_params.contains(purpose)
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000491 // Also, authorizing purpose can not be completed here, if there can be multiple
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800492 // key parameters for KeyPurpose.
493 key_purpose_authorized = key_purpose_authorized || *p == purpose;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000494 }
495 KeyParameterValue::CallerNonce => {
496 caller_nonce_allowed = true;
497 }
498 KeyParameterValue::ActiveDateTime(a) => {
499 if !Enforcements::is_given_time_passed(*a, true) {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800500 return Err(Error::Km(Ec::KEY_NOT_YET_VALID))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000501 .context("In authorize_create: key is not yet active.");
502 }
503 }
504 KeyParameterValue::OriginationExpireDateTime(o) => {
505 if (purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN)
506 && Enforcements::is_given_time_passed(*o, false)
507 {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800508 return Err(Error::Km(Ec::KEY_EXPIRED))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000509 .context("In authorize_create: key is expired.");
510 }
511 }
512 KeyParameterValue::UsageExpireDateTime(u) => {
513 if (purpose == KeyPurpose::DECRYPT || purpose == KeyPurpose::VERIFY)
514 && Enforcements::is_given_time_passed(*u, false)
515 {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800516 return Err(Error::Km(Ec::KEY_EXPIRED))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000517 .context("In authorize_create: key is expired.");
518 }
519 }
520 KeyParameterValue::UserSecureID(s) => {
521 user_secure_ids.push(*s);
522 }
523 KeyParameterValue::UserID(u) => {
524 user_id = *u;
525 }
526 KeyParameterValue::UnlockedDeviceRequired => {
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000527 unlocked_device_required = true;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000528 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000529 KeyParameterValue::AllowWhileOnBody => {
530 allow_while_on_body = true;
531 }
Qi Wub9433b52020-12-01 14:52:46 +0800532 KeyParameterValue::UsageCountLimit(_) => {
533 // We don't examine the limit here because this is enforced on finish.
534 // Instead, we store the key_id so that finish can look up the key
535 // in the database again and check and update the counter.
536 key_usage_limited = Some(key_id);
537 }
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800538 KeyParameterValue::TrustedConfirmationRequired => {
539 confirmation_token_receiver = Some(self.confirmation_token_receiver.clone());
540 }
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000541 // NOTE: as per offline discussion, sanitizing key parameters and rejecting
542 // create operation if any non-allowed tags are present, is not done in
543 // authorize_create (unlike in legacy keystore where AuthorizeBegin is rejected if
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800544 // a subset of non-allowed tags are present). Because sanitizing key parameters
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000545 // should have been done during generate/import key, by KeyMint.
546 _ => { /*Do nothing on all the other key parameters, as in legacy keystore*/ }
547 }
548 }
549
550 // authorize the purpose
551 if !key_purpose_authorized {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800552 return Err(Error::Km(Ec::INCOMPATIBLE_PURPOSE))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000553 .context("In authorize_create: the purpose is not authorized.");
554 }
555
556 // if both NO_AUTH_REQUIRED and USER_SECURE_ID tags are present, return error
557 if !user_secure_ids.is_empty() && no_auth_required {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800558 return Err(Error::Km(Ec::INVALID_KEY_BLOB)).context(
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000559 "In authorize_create: key has both NO_AUTH_REQUIRED
560 and USER_SECURE_ID tags.",
561 );
562 }
563
564 // 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 +0000565 if (user_auth_type.is_some() && user_secure_ids.is_empty())
566 || (user_auth_type.is_none() && !user_secure_ids.is_empty())
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000567 {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800568 return Err(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED)).context(
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000569 "In authorize_create: Auth required, but either auth type or secure ids
570 are not present.",
571 );
572 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800573
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000574 // validate caller nonce for origination purposes
575 if (purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN)
576 && !caller_nonce_allowed
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800577 && op_params.iter().any(|kp| kp.tag == Tag::NONCE)
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000578 {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800579 return Err(Error::Km(Ec::CALLER_NONCE_PROHIBITED)).context(
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000580 "In authorize_create, NONCE is present,
581 although CALLER_NONCE is not present",
582 );
583 }
584
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000585 if unlocked_device_required {
586 // check the device locked status. If locked, operations on the key are not
587 // allowed.
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000588 if self.is_device_locked(user_id) {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800589 return Err(Error::Km(Ec::DEVICE_LOCKED))
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000590 .context("In authorize_create: device is locked.");
591 }
592 }
593
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800594 if !unlocked_device_required && no_auth_required {
Qi Wub9433b52020-12-01 14:52:46 +0800595 return Ok((
596 None,
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800597 AuthInfo {
598 state: DeferredAuthState::NoAuthRequired,
599 key_usage_limited,
600 confirmation_token_receiver,
601 },
Qi Wub9433b52020-12-01 14:52:46 +0800602 ));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000603 }
604
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800605 let has_sids = !user_secure_ids.is_empty();
606
607 let timeout_bound = key_time_out.is_some() && has_sids;
608
609 let per_op_bound = key_time_out.is_none() && has_sids;
610
611 let need_auth_token = timeout_bound || unlocked_device_required;
612
613 let hat_and_last_off_body = if need_auth_token {
614 let hat_and_last_off_body = Self::find_auth_token(|hat: &AuthTokenEntry| {
615 if let (Some(auth_type), true) = (user_auth_type, has_sids) {
616 hat.satisfies(&user_secure_ids, auth_type)
617 } else {
618 unlocked_device_required
619 }
620 })
621 .context("In authorize_create: Trying to get required auth token.")?;
622 Some(
623 hat_and_last_off_body
624 .ok_or(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
625 .context("In authorize_create: No suitable auth token found.")?,
626 )
627 } else {
628 None
629 };
630
631 // Now check the validity of the auth token if the key is timeout bound.
632 let hat = match (hat_and_last_off_body, key_time_out) {
633 (Some((hat, last_off_body)), Some(key_time_out)) => {
634 let now = MonotonicRawTime::now();
635 let token_age = now
636 .checked_sub(&hat.time_received())
637 .ok_or_else(Error::sys)
638 .context(concat!(
639 "In authorize_create: Overflow while computing Auth token validity. ",
640 "Validity cannot be established."
641 ))?;
642
643 let on_body_extended = allow_while_on_body && last_off_body < hat.time_received();
644
645 if token_age.seconds() > key_time_out && !on_body_extended {
646 return Err(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
647 .context("In authorize_create: matching auth token is expired.");
648 }
649 Some(hat)
650 }
651 (Some((hat, _)), None) => Some(hat),
652 // If timeout_bound is true, above code must have retrieved a HAT or returned with
653 // KEY_USER_NOT_AUTHENTICATED. This arm should not be reachable.
654 (None, Some(_)) => panic!("Logical error."),
655 _ => None,
656 };
657
658 Ok(match (hat, requires_timestamp, per_op_bound) {
659 // Per-op-bound and Some(hat) can only happen if we are both per-op bound and unlocked
660 // device required. In addition, this KM instance needs a timestamp token.
661 // So the HAT cannot be presented on create. So on update/finish we present both
662 // an per-op-bound auth token and a timestamp token.
663 (Some(_), true, true) => (None, DeferredAuthState::TimeStampedOpAuthRequired),
664 (Some(hat), true, false) => {
665 (None, DeferredAuthState::TimeStampRequired(hat.take_auth_token()))
666 }
667 (Some(hat), false, true) => {
668 (Some(hat.take_auth_token()), DeferredAuthState::OpAuthRequired)
669 }
670 (Some(hat), false, false) => {
671 (Some(hat.take_auth_token()), DeferredAuthState::NoAuthRequired)
672 }
673 (None, _, true) => (None, DeferredAuthState::OpAuthRequired),
674 (None, _, false) => (None, DeferredAuthState::NoAuthRequired),
675 })
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800676 .map(|(hat, state)| {
677 (hat, AuthInfo { state, key_usage_limited, confirmation_token_receiver })
678 })
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800679 }
680
681 fn find_auth_token<F>(p: F) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
682 where
683 F: Fn(&AuthTokenEntry) -> bool,
684 {
685 DB.with(|db| {
686 let mut db = db.borrow_mut();
687 db.find_auth_token_entry(p).context("Trying to find auth token.")
688 })
689 .context("In find_auth_token.")
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000690 }
691
692 /// Checks if the time now since epoch is greater than (or equal, if is_given_time_inclusive is
693 /// set) the given time (in milliseconds)
694 fn is_given_time_passed(given_time: i64, is_given_time_inclusive: bool) -> bool {
695 let duration_since_epoch = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH);
696
697 let time_since_epoch = match duration_since_epoch {
698 Ok(duration) => duration.as_millis(),
699 Err(_) => return false,
700 };
701
702 if is_given_time_inclusive {
703 time_since_epoch >= (given_time as u128)
704 } else {
705 time_since_epoch > (given_time as u128)
706 }
707 }
708
709 /// Check if the device is locked for the given user. If there's no entry yet for the user,
710 /// we assume that the device is locked
711 fn is_device_locked(&self, user_id: i32) -> bool {
712 // unwrap here because there's no way this mutex guard can be poisoned and
713 // because there's no way to recover, even if it is poisoned.
714 let set = self.device_unlocked_set.lock().unwrap();
715 !set.contains(&user_id)
716 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000717
718 /// Sets the device locked status for the user. This method is called externally.
719 pub fn set_device_locked(&self, user_id: i32, device_locked_status: bool) {
720 // unwrap here because there's no way this mutex guard can be poisoned and
721 // because there's no way to recover, even if it is poisoned.
722 let mut set = self.device_unlocked_set.lock().unwrap();
723 if device_locked_status {
724 set.remove(&user_id);
725 } else {
726 set.insert(user_id);
727 }
728 }
729
730 /// Add this auth token to the database.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800731 /// Then present the auth token to the op auth map. If an operation is waiting for this
732 /// auth token this fulfills the request and removes the receiver from the map.
733 pub fn add_auth_token(&self, hat: HardwareAuthToken) -> Result<()> {
734 DB.with(|db| db.borrow_mut().insert_auth_token(&hat)).context("In add_auth_token.")?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000735
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800736 self.op_auth_map.add_auth_token(hat);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000737 Ok(())
738 }
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000739
740 /// This allows adding an entry to the op_auth_map, indexed by the operation challenge.
741 /// This is to be called by create_operation, once it has received the operation challenge
742 /// from keymint for an operation whose authorization decision is OpAuthRequired, as signalled
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800743 /// by the DeferredAuthState.
744 fn register_op_auth_receiver(&self, challenge: i64, recv: TokenReceiver) {
745 self.op_auth_map.add_receiver(challenge, recv);
Hasini Gunasinghef04d07a2020-11-25 22:41:35 +0000746 }
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000747}
748
749impl Default for Enforcements {
750 fn default() -> Self {
751 Self::new()
752 }
753}
754
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000755// TODO: Add tests to enforcement module (b/175578618).