blob: aa852f4f41896fd6ce20707cf07e3c283afe81c8 [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};
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +000029use android_system_keystore2::aidl::android::system::keystore2::{
30 IKeystoreSecurityLevel::KEY_FLAG_AUTH_BOUND_WITHOUT_CRYPTOGRAPHIC_LSKF_BINDING,
31 OperationChallenge::OperationChallenge,
32};
Stephen Crane221bbb52020-12-16 15:52:10 -080033use android_system_keystore2::binder::Strong;
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000034use anyhow::{Context, Result};
Paul Crowley7c57bf12021-02-02 16:26:57 -080035use keystore2_system_property::PropertyWatcher;
Janis Danisevskisb1673db2021-02-08 18:11:57 -080036use std::{
37 collections::{HashMap, HashSet},
Paul Crowley7c57bf12021-02-02 16:26:57 -080038 sync::{
39 atomic::{AtomicI32, Ordering},
40 mpsc::{channel, Receiver, Sender, TryRecvError},
41 Arc, Mutex, Weak,
42 },
43 time::SystemTime,
Janis Danisevskisb1673db2021-02-08 18:11:57 -080044};
Hasini Gunasinghe3410f792020-09-14 17:55:21 +000045
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080046#[derive(Debug)]
47enum AuthRequestState {
48 /// An outstanding per operation authorization request.
49 OpAuth,
50 /// An outstanding request for per operation authorization and secure timestamp.
51 TimeStampedOpAuth(Receiver<Result<TimeStampToken, Error>>),
52 /// An outstanding request for a timestamp token.
53 TimeStamp(Receiver<Result<TimeStampToken, Error>>),
54}
55
56#[derive(Debug)]
57struct AuthRequest {
58 state: AuthRequestState,
59 /// This need to be set to Some to fulfill a AuthRequestState::OpAuth or
60 /// AuthRequestState::TimeStampedOpAuth.
61 hat: Option<HardwareAuthToken>,
62}
63
64impl AuthRequest {
65 fn op_auth() -> Arc<Mutex<Self>> {
66 Arc::new(Mutex::new(Self { state: AuthRequestState::OpAuth, hat: None }))
67 }
68
69 fn timestamped_op_auth(receiver: Receiver<Result<TimeStampToken, Error>>) -> Arc<Mutex<Self>> {
70 Arc::new(Mutex::new(Self {
71 state: AuthRequestState::TimeStampedOpAuth(receiver),
72 hat: None,
73 }))
74 }
75
76 fn timestamp(
77 hat: HardwareAuthToken,
78 receiver: Receiver<Result<TimeStampToken, Error>>,
79 ) -> Arc<Mutex<Self>> {
80 Arc::new(Mutex::new(Self { state: AuthRequestState::TimeStamp(receiver), hat: Some(hat) }))
81 }
82
83 fn add_auth_token(&mut self, hat: HardwareAuthToken) {
84 self.hat = Some(hat)
85 }
86
87 fn get_auth_tokens(&mut self) -> Result<(HardwareAuthToken, Option<TimeStampToken>)> {
88 match (&self.state, self.hat.is_some()) {
89 (AuthRequestState::OpAuth, true) => Ok((self.hat.take().unwrap(), None)),
90 (AuthRequestState::TimeStampedOpAuth(recv), true)
91 | (AuthRequestState::TimeStamp(recv), true) => {
92 let result = recv.recv().context("In get_auth_tokens: Sender disconnected.")?;
93 let tst = result.context(concat!(
94 "In get_auth_tokens: Worker responded with error ",
95 "from generating timestamp token."
96 ))?;
97 Ok((self.hat.take().unwrap(), Some(tst)))
98 }
99 (_, false) => Err(Error::Km(ErrorCode::KEY_USER_NOT_AUTHENTICATED))
100 .context("In get_auth_tokens: No operation auth token received."),
101 }
102 }
103}
104
105/// DeferredAuthState describes how auth tokens and timestamp tokens need to be provided when
106/// updating and finishing an operation.
107#[derive(Debug)]
108enum DeferredAuthState {
109 /// Used when an operation does not require further authorization.
110 NoAuthRequired,
111 /// Indicates that the operation requires an operation specific token. This means we have
112 /// to return an operation challenge to the client which should reward us with an
113 /// operation specific auth token. If it is not provided before the client calls update
114 /// or finish, the operation fails as not authorized.
115 OpAuthRequired,
116 /// Indicates that the operation requires a time stamp token. The auth token was already
117 /// loaded from the database, but it has to be accompanied by a time stamp token to inform
118 /// the target KM with a different clock about the time on the authenticators.
119 TimeStampRequired(HardwareAuthToken),
120 /// Indicates that both an operation bound auth token and a verification token are
121 /// before the operation can commence.
122 TimeStampedOpAuthRequired,
123 /// In this state the auth info is waiting for the deferred authorizations to come in.
124 /// We block on timestamp tokens, because we can always make progress on these requests.
125 /// The per-op auth tokens might never come, which means we fail if the client calls
126 /// update or finish before we got a per-op auth token.
127 Waiting(Arc<Mutex<AuthRequest>>),
128 /// In this state we have gotten all of the required tokens, we just cache them to
129 /// be used when the operation progresses.
130 Token(HardwareAuthToken, Option<TimeStampToken>),
131}
132
133/// Auth info hold all of the authorization related information of an operation. It is stored
134/// in and owned by the operation. It is constructed by authorize_create and stays with the
135/// operation until it completes.
136#[derive(Debug)]
137pub struct AuthInfo {
138 state: DeferredAuthState,
Qi Wub9433b52020-12-01 14:52:46 +0800139 /// An optional key id required to update the usage count if the key usage is limited.
140 key_usage_limited: Option<i64>,
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800141 confirmation_token_receiver: Option<Arc<Mutex<Option<Receiver<Vec<u8>>>>>>,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800142}
143
144struct TokenReceiverMap {
145 /// The map maps an outstanding challenge to a TokenReceiver. If an incoming Hardware Auth
146 /// Token (HAT) has the map key in its challenge field, it gets passed to the TokenReceiver
147 /// and the entry is removed from the map. In the case where no HAT is received before the
148 /// corresponding operation gets dropped, the entry goes stale. So every time the cleanup
149 /// counter (second field in the tuple) turns 0, the map is cleaned from stale entries.
150 /// The cleanup counter is decremented every time a new receiver is added.
151 /// and reset to TokenReceiverMap::CLEANUP_PERIOD + 1 after each cleanup.
152 map_and_cleanup_counter: Mutex<(HashMap<i64, TokenReceiver>, u8)>,
153}
154
155impl Default for TokenReceiverMap {
156 fn default() -> Self {
157 Self { map_and_cleanup_counter: Mutex::new((HashMap::new(), Self::CLEANUP_PERIOD + 1)) }
158 }
159}
160
161impl TokenReceiverMap {
162 /// There is a chance that receivers may become stale because their operation is dropped
163 /// without ever being authorized. So occasionally we iterate through the map and throw
164 /// out obsolete entries.
165 /// This is the number of calls to add_receiver between cleanups.
166 const CLEANUP_PERIOD: u8 = 25;
167
168 pub fn add_auth_token(&self, hat: HardwareAuthToken) {
169 let mut map = self.map_and_cleanup_counter.lock().unwrap();
170 let (ref mut map, _) = *map;
171 if let Some((_, recv)) = map.remove_entry(&hat.challenge) {
172 recv.add_auth_token(hat);
173 }
174 }
175
176 pub fn add_receiver(&self, challenge: i64, recv: TokenReceiver) {
177 let mut map = self.map_and_cleanup_counter.lock().unwrap();
178 let (ref mut map, ref mut cleanup_counter) = *map;
179 map.insert(challenge, recv);
180
181 *cleanup_counter -= 1;
182 if *cleanup_counter == 0 {
183 map.retain(|_, v| !v.is_obsolete());
184 map.shrink_to_fit();
185 *cleanup_counter = Self::CLEANUP_PERIOD + 1;
186 }
187 }
188}
189
190#[derive(Debug)]
191struct TokenReceiver(Weak<Mutex<AuthRequest>>);
192
193impl TokenReceiver {
194 fn is_obsolete(&self) -> bool {
195 self.0.upgrade().is_none()
196 }
197
198 fn add_auth_token(&self, hat: HardwareAuthToken) {
199 if let Some(state_arc) = self.0.upgrade() {
200 let mut state = state_arc.lock().unwrap();
201 state.add_auth_token(hat);
202 }
203 }
204}
205
206fn get_timestamp_token(challenge: i64) -> Result<TimeStampToken, Error> {
Stephen Crane221bbb52020-12-16 15:52:10 -0800207 let dev: Strong<dyn ISecureClock> = get_timestamp_service()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800208 .expect(concat!(
209 "Secure Clock service must be present ",
210 "if TimeStampTokens are required."
211 ))
212 .get_interface()
213 .expect("Fatal: Timestamp service does not implement ISecureClock.");
214 map_binder_status(dev.generateTimeStamp(challenge))
215}
216
217fn timestamp_token_request(challenge: i64, sender: Sender<Result<TimeStampToken, Error>>) {
218 if let Err(e) = sender.send(get_timestamp_token(challenge)) {
219 log::info!(
220 concat!(
221 "In timestamp_token_request: Operation hung up ",
222 "before timestamp token could be delivered. {:?}"
223 ),
224 e
225 );
226 }
227}
228
229impl AuthInfo {
230 /// This function gets called after an operation was successfully created.
231 /// It makes all the preparations required, so that the operation has all the authentication
232 /// related artifacts to advance on update and finish.
233 pub fn finalize_create_authorization(&mut self, challenge: i64) -> Option<OperationChallenge> {
234 match &self.state {
235 DeferredAuthState::OpAuthRequired => {
236 let auth_request = AuthRequest::op_auth();
237 let token_receiver = TokenReceiver(Arc::downgrade(&auth_request));
238 ENFORCEMENTS.register_op_auth_receiver(challenge, token_receiver);
239
240 self.state = DeferredAuthState::Waiting(auth_request);
241 Some(OperationChallenge { challenge })
242 }
243 DeferredAuthState::TimeStampedOpAuthRequired => {
244 let (sender, receiver) = channel::<Result<TimeStampToken, Error>>();
245 let auth_request = AuthRequest::timestamped_op_auth(receiver);
246 let token_receiver = TokenReceiver(Arc::downgrade(&auth_request));
247 ENFORCEMENTS.register_op_auth_receiver(challenge, token_receiver);
248
Janis Danisevskis40f0e6b2021-02-10 15:48:44 -0800249 ASYNC_TASK.queue_hi(move |_| timestamp_token_request(challenge, sender));
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800250 self.state = DeferredAuthState::Waiting(auth_request);
251 Some(OperationChallenge { challenge })
252 }
253 DeferredAuthState::TimeStampRequired(hat) => {
254 let hat = (*hat).clone();
255 let (sender, receiver) = channel::<Result<TimeStampToken, Error>>();
256 let auth_request = AuthRequest::timestamp(hat, receiver);
Janis Danisevskis40f0e6b2021-02-10 15:48:44 -0800257 ASYNC_TASK.queue_hi(move |_| timestamp_token_request(challenge, sender));
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800258 self.state = DeferredAuthState::Waiting(auth_request);
259 None
260 }
261 _ => None,
262 }
263 }
264
Qi Wub9433b52020-12-01 14:52:46 +0800265 /// This function is the authorization hook called before operation update.
266 /// It returns the auth tokens required by the operation to commence update.
267 pub fn before_update(&mut self) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>)> {
268 self.get_auth_tokens()
269 }
270
271 /// This function is the authorization hook called before operation finish.
272 /// It returns the auth tokens required by the operation to commence finish.
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800273 /// The third token is a confirmation token.
274 pub fn before_finish(
275 &mut self,
276 ) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>, Option<Vec<u8>>)> {
277 let mut confirmation_token: Option<Vec<u8>> = None;
278 if let Some(ref confirmation_token_receiver) = self.confirmation_token_receiver {
279 let locked_receiver = confirmation_token_receiver.lock().unwrap();
280 if let Some(ref receiver) = *locked_receiver {
281 loop {
282 match receiver.try_recv() {
283 // As long as we get tokens we loop and discard all but the most
284 // recent one.
285 Ok(t) => confirmation_token = Some(t),
286 Err(TryRecvError::Empty) => break,
287 Err(TryRecvError::Disconnected) => {
288 log::error!(concat!(
289 "We got disconnected from the APC service, ",
290 "this should never happen."
291 ));
292 break;
293 }
294 }
295 }
296 }
297 }
298 self.get_auth_tokens().map(|(hat, tst)| (hat, tst, confirmation_token))
Qi Wub9433b52020-12-01 14:52:46 +0800299 }
300
301 /// This function is the authorization hook called after finish succeeded.
302 /// As of this writing it checks if the key was a limited use key. If so it updates the
303 /// use counter of the key in the database. When the use counter is depleted, the key gets
304 /// marked for deletion and the garbage collector is notified.
305 pub fn after_finish(&self) -> Result<()> {
306 if let Some(key_id) = self.key_usage_limited {
307 // On the last successful use, the key gets deleted. In this case we
308 // have to notify the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800309 DB.with(|db| {
310 db.borrow_mut()
311 .check_and_update_key_usage_count(key_id)
312 .context("Trying to update key usage count.")
313 })
314 .context("In after_finish.")?;
Qi Wub9433b52020-12-01 14:52:46 +0800315 }
316 Ok(())
317 }
318
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800319 /// This function returns the auth tokens as needed by the ongoing operation or fails
320 /// with ErrorCode::KEY_USER_NOT_AUTHENTICATED. If this was called for the first time
321 /// after a deferred authorization was requested by finalize_create_authorization, this
322 /// function may block on the generation of a time stamp token. It then moves the
323 /// tokens into the DeferredAuthState::Token state for future use.
Qi Wub9433b52020-12-01 14:52:46 +0800324 fn get_auth_tokens(&mut self) -> Result<(Option<HardwareAuthToken>, Option<TimeStampToken>)> {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800325 let deferred_tokens = if let DeferredAuthState::Waiting(ref auth_request) = self.state {
326 let mut state = auth_request.lock().unwrap();
327 Some(state.get_auth_tokens().context("In AuthInfo::get_auth_tokens.")?)
328 } else {
329 None
330 };
331
332 if let Some((hat, tst)) = deferred_tokens {
333 self.state = DeferredAuthState::Token(hat, tst);
334 }
335
336 match &self.state {
337 DeferredAuthState::NoAuthRequired => Ok((None, None)),
338 DeferredAuthState::Token(hat, tst) => Ok((Some((*hat).clone()), (*tst).clone())),
339 DeferredAuthState::OpAuthRequired
340 | DeferredAuthState::TimeStampedOpAuthRequired
341 | DeferredAuthState::TimeStampRequired(_) => {
342 Err(Error::Km(ErrorCode::KEY_USER_NOT_AUTHENTICATED)).context(concat!(
343 "In AuthInfo::get_auth_tokens: No operation auth token requested??? ",
344 "This should not happen."
345 ))
346 }
347 // This should not be reachable, because it should have been handled above.
348 DeferredAuthState::Waiting(_) => {
349 Err(Error::sys()).context("In AuthInfo::get_auth_tokens: Cannot be reached.")
350 }
351 }
352 }
353}
354
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000355/// Enforcements data structure
Paul Crowley7c57bf12021-02-02 16:26:57 -0800356#[derive(Default)]
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000357pub struct Enforcements {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800358 /// This hash set contains the user ids for whom the device is currently unlocked. If a user id
359 /// is not in the set, it implies that the device is locked for the user.
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000360 device_unlocked_set: Mutex<HashSet<i32>>,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800361 /// This field maps outstanding auth challenges to their operations. When an auth token
362 /// with the right challenge is received it is passed to the map using
363 /// TokenReceiverMap::add_auth_token() which removes the entry from the map. If an entry goes
364 /// stale, because the operation gets dropped before an auth token is received, the map
365 /// is cleaned up in regular intervals.
366 op_auth_map: TokenReceiverMap,
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800367 /// The enforcement module will try to get a confirmation token from this channel whenever
368 /// an operation that requires confirmation finishes.
369 confirmation_token_receiver: Arc<Mutex<Option<Receiver<Vec<u8>>>>>,
Paul Crowley7c57bf12021-02-02 16:26:57 -0800370 /// Highest boot level seen in keystore.boot_level; used to enforce MAX_BOOT_LEVEL tag.
371 boot_level: AtomicI32,
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000372}
373
374impl Enforcements {
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800375 /// Install the confirmation token receiver. The enforcement module will try to get a
376 /// confirmation token from this channel whenever an operation that requires confirmation
377 /// finishes.
378 pub fn install_confirmation_token_receiver(
379 &self,
380 confirmation_token_receiver: Receiver<Vec<u8>>,
381 ) {
382 *self.confirmation_token_receiver.lock().unwrap() = Some(confirmation_token_receiver);
383 }
384
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000385 /// Checks if a create call is authorized, given key parameters and operation parameters.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800386 /// It returns an optional immediate auth token which can be presented to begin, and an
387 /// AuthInfo object which stays with the authorized operation and is used to obtain
388 /// auth tokens and timestamp tokens as required by the operation.
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000389 /// With regard to auth tokens, the following steps are taken:
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800390 ///
391 /// If no key parameters are given (typically when the client is self managed
392 /// (see Domain.Blob)) nothing is enforced.
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000393 /// If the key is time-bound, find a matching auth token from the database.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800394 /// If the above step is successful, and if requires_timestamp is given, the returned
395 /// AuthInfo will provide a Timestamp token as appropriate.
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000396 pub fn authorize_create(
397 &self,
398 purpose: KeyPurpose,
Qi Wub9433b52020-12-01 14:52:46 +0800399 key_properties: Option<&(i64, Vec<KeyParameter>)>,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800400 op_params: &[KmKeyParameter],
401 requires_timestamp: bool,
402 ) -> Result<(Option<HardwareAuthToken>, AuthInfo)> {
Qi Wub9433b52020-12-01 14:52:46 +0800403 let (key_id, key_params) = match key_properties {
404 Some((key_id, key_params)) => (*key_id, key_params),
405 None => {
406 return Ok((
407 None,
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800408 AuthInfo {
409 state: DeferredAuthState::NoAuthRequired,
410 key_usage_limited: None,
411 confirmation_token_receiver: None,
412 },
Qi Wub9433b52020-12-01 14:52:46 +0800413 ))
414 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800415 };
416
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000417 match purpose {
418 // Allow SIGN, DECRYPT for both symmetric and asymmetric keys.
419 KeyPurpose::SIGN | KeyPurpose::DECRYPT => {}
420 // Rule out WRAP_KEY purpose
421 KeyPurpose::WRAP_KEY => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800422 return Err(Error::Km(Ec::INCOMPATIBLE_PURPOSE))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000423 .context("In authorize_create: WRAP_KEY purpose is not allowed here.");
424 }
Bram Bonnéa6b83822021-01-20 11:10:05 +0100425 // Allow AGREE_KEY for EC keys only.
426 KeyPurpose::AGREE_KEY => {
427 for kp in key_params.iter() {
428 if kp.get_tag() == Tag::ALGORITHM
429 && *kp.key_parameter_value() != KeyParameterValue::Algorithm(Algorithm::EC)
430 {
431 return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE)).context(
432 "In authorize_create: key agreement is only supported for EC keys.",
433 );
434 }
435 }
436 }
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000437 KeyPurpose::VERIFY | KeyPurpose::ENCRYPT => {
438 // We do not support ENCRYPT and VERIFY (the remaining two options of purpose) for
439 // asymmetric keys.
440 for kp in key_params.iter() {
441 match *kp.key_parameter_value() {
442 KeyParameterValue::Algorithm(Algorithm::RSA)
443 | KeyParameterValue::Algorithm(Algorithm::EC) => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800444 return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE)).context(
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000445 "In authorize_create: public operations on asymmetric keys are not
446 supported.",
447 );
448 }
449 _ => {}
450 }
451 }
452 }
453 _ => {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800454 return Err(Error::Km(Ec::UNSUPPORTED_PURPOSE))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000455 .context("In authorize_create: specified purpose is not supported.");
456 }
457 }
458 // The following variables are to record information from key parameters to be used in
459 // enforcements, when two or more such pieces of information are required for enforcements.
460 // There is only one additional variable than what legacy keystore has, but this helps
461 // reduce the number of for loops on key parameters from 3 to 1, compared to legacy keystore
462 let mut key_purpose_authorized: bool = false;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000463 let mut user_auth_type: Option<HardwareAuthenticatorType> = None;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000464 let mut no_auth_required: bool = false;
465 let mut caller_nonce_allowed = false;
466 let mut user_id: i32 = -1;
467 let mut user_secure_ids = Vec::<i64>::new();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000468 let mut key_time_out: Option<i64> = None;
469 let mut allow_while_on_body = false;
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000470 let mut unlocked_device_required = false;
Qi Wub9433b52020-12-01 14:52:46 +0800471 let mut key_usage_limited: Option<i64> = None;
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800472 let mut confirmation_token_receiver: Option<Arc<Mutex<Option<Receiver<Vec<u8>>>>>> = None;
Paul Crowley7c57bf12021-02-02 16:26:57 -0800473 let mut max_boot_level: Option<i32> = None;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000474
475 // iterate through key parameters, recording information we need for authorization
476 // enforcements later, or enforcing authorizations in place, where applicable
477 for key_param in key_params.iter() {
478 match key_param.key_parameter_value() {
479 KeyParameterValue::NoAuthRequired => {
480 no_auth_required = true;
481 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000482 KeyParameterValue::AuthTimeout(t) => {
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000483 key_time_out = Some(*t as i64);
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000484 }
485 KeyParameterValue::HardwareAuthenticatorType(a) => {
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000486 user_auth_type = Some(*a);
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000487 }
488 KeyParameterValue::KeyPurpose(p) => {
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800489 // The following check has the effect of key_params.contains(purpose)
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000490 // Also, authorizing purpose can not be completed here, if there can be multiple
Janis Danisevskis104d8e42021-01-14 22:49:27 -0800491 // key parameters for KeyPurpose.
492 key_purpose_authorized = key_purpose_authorized || *p == purpose;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000493 }
494 KeyParameterValue::CallerNonce => {
495 caller_nonce_allowed = true;
496 }
497 KeyParameterValue::ActiveDateTime(a) => {
498 if !Enforcements::is_given_time_passed(*a, true) {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800499 return Err(Error::Km(Ec::KEY_NOT_YET_VALID))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000500 .context("In authorize_create: key is not yet active.");
501 }
502 }
503 KeyParameterValue::OriginationExpireDateTime(o) => {
504 if (purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN)
505 && Enforcements::is_given_time_passed(*o, false)
506 {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800507 return Err(Error::Km(Ec::KEY_EXPIRED))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000508 .context("In authorize_create: key is expired.");
509 }
510 }
511 KeyParameterValue::UsageExpireDateTime(u) => {
512 if (purpose == KeyPurpose::DECRYPT || purpose == KeyPurpose::VERIFY)
513 && Enforcements::is_given_time_passed(*u, false)
514 {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800515 return Err(Error::Km(Ec::KEY_EXPIRED))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000516 .context("In authorize_create: key is expired.");
517 }
518 }
519 KeyParameterValue::UserSecureID(s) => {
520 user_secure_ids.push(*s);
521 }
522 KeyParameterValue::UserID(u) => {
523 user_id = *u;
524 }
525 KeyParameterValue::UnlockedDeviceRequired => {
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000526 unlocked_device_required = true;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000527 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000528 KeyParameterValue::AllowWhileOnBody => {
529 allow_while_on_body = true;
530 }
Qi Wub9433b52020-12-01 14:52:46 +0800531 KeyParameterValue::UsageCountLimit(_) => {
532 // We don't examine the limit here because this is enforced on finish.
533 // Instead, we store the key_id so that finish can look up the key
534 // in the database again and check and update the counter.
535 key_usage_limited = Some(key_id);
536 }
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800537 KeyParameterValue::TrustedConfirmationRequired => {
538 confirmation_token_receiver = Some(self.confirmation_token_receiver.clone());
539 }
Paul Crowley7c57bf12021-02-02 16:26:57 -0800540 KeyParameterValue::MaxBootLevel(level) => {
541 max_boot_level = Some(*level);
542 }
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000543 // NOTE: as per offline discussion, sanitizing key parameters and rejecting
544 // create operation if any non-allowed tags are present, is not done in
545 // authorize_create (unlike in legacy keystore where AuthorizeBegin is rejected if
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800546 // a subset of non-allowed tags are present). Because sanitizing key parameters
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000547 // should have been done during generate/import key, by KeyMint.
548 _ => { /*Do nothing on all the other key parameters, as in legacy keystore*/ }
549 }
550 }
551
552 // authorize the purpose
553 if !key_purpose_authorized {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800554 return Err(Error::Km(Ec::INCOMPATIBLE_PURPOSE))
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000555 .context("In authorize_create: the purpose is not authorized.");
556 }
557
558 // if both NO_AUTH_REQUIRED and USER_SECURE_ID tags are present, return error
559 if !user_secure_ids.is_empty() && no_auth_required {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800560 return Err(Error::Km(Ec::INVALID_KEY_BLOB)).context(
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000561 "In authorize_create: key has both NO_AUTH_REQUIRED
562 and USER_SECURE_ID tags.",
563 );
564 }
565
566 // 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 +0000567 if (user_auth_type.is_some() && user_secure_ids.is_empty())
568 || (user_auth_type.is_none() && !user_secure_ids.is_empty())
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000569 {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800570 return Err(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED)).context(
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000571 "In authorize_create: Auth required, but either auth type or secure ids
572 are not present.",
573 );
574 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800575
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000576 // validate caller nonce for origination purposes
577 if (purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN)
578 && !caller_nonce_allowed
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800579 && op_params.iter().any(|kp| kp.tag == Tag::NONCE)
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000580 {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800581 return Err(Error::Km(Ec::CALLER_NONCE_PROHIBITED)).context(
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000582 "In authorize_create, NONCE is present,
583 although CALLER_NONCE is not present",
584 );
585 }
586
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000587 if unlocked_device_required {
588 // check the device locked status. If locked, operations on the key are not
589 // allowed.
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000590 if self.is_device_locked(user_id) {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800591 return Err(Error::Km(Ec::DEVICE_LOCKED))
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000592 .context("In authorize_create: device is locked.");
593 }
594 }
595
Paul Crowley7c57bf12021-02-02 16:26:57 -0800596 if let Some(level) = max_boot_level {
597 if level < self.boot_level.load(Ordering::SeqCst) {
598 return Err(Error::Km(Ec::BOOT_LEVEL_EXCEEDED))
599 .context("In authorize_create: boot level is too late.");
600 }
601 }
602
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800603 if !unlocked_device_required && no_auth_required {
Qi Wub9433b52020-12-01 14:52:46 +0800604 return Ok((
605 None,
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800606 AuthInfo {
607 state: DeferredAuthState::NoAuthRequired,
608 key_usage_limited,
609 confirmation_token_receiver,
610 },
Qi Wub9433b52020-12-01 14:52:46 +0800611 ));
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000612 }
613
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800614 let has_sids = !user_secure_ids.is_empty();
615
616 let timeout_bound = key_time_out.is_some() && has_sids;
617
618 let per_op_bound = key_time_out.is_none() && has_sids;
619
620 let need_auth_token = timeout_bound || unlocked_device_required;
621
622 let hat_and_last_off_body = if need_auth_token {
623 let hat_and_last_off_body = Self::find_auth_token(|hat: &AuthTokenEntry| {
624 if let (Some(auth_type), true) = (user_auth_type, has_sids) {
625 hat.satisfies(&user_secure_ids, auth_type)
626 } else {
627 unlocked_device_required
628 }
629 })
630 .context("In authorize_create: Trying to get required auth token.")?;
631 Some(
632 hat_and_last_off_body
633 .ok_or(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
634 .context("In authorize_create: No suitable auth token found.")?,
635 )
636 } else {
637 None
638 };
639
640 // Now check the validity of the auth token if the key is timeout bound.
641 let hat = match (hat_and_last_off_body, key_time_out) {
642 (Some((hat, last_off_body)), Some(key_time_out)) => {
643 let now = MonotonicRawTime::now();
644 let token_age = now
645 .checked_sub(&hat.time_received())
646 .ok_or_else(Error::sys)
647 .context(concat!(
648 "In authorize_create: Overflow while computing Auth token validity. ",
649 "Validity cannot be established."
650 ))?;
651
652 let on_body_extended = allow_while_on_body && last_off_body < hat.time_received();
653
654 if token_age.seconds() > key_time_out && !on_body_extended {
655 return Err(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
656 .context("In authorize_create: matching auth token is expired.");
657 }
658 Some(hat)
659 }
660 (Some((hat, _)), None) => Some(hat),
661 // If timeout_bound is true, above code must have retrieved a HAT or returned with
662 // KEY_USER_NOT_AUTHENTICATED. This arm should not be reachable.
663 (None, Some(_)) => panic!("Logical error."),
664 _ => None,
665 };
666
667 Ok(match (hat, requires_timestamp, per_op_bound) {
668 // Per-op-bound and Some(hat) can only happen if we are both per-op bound and unlocked
669 // device required. In addition, this KM instance needs a timestamp token.
670 // So the HAT cannot be presented on create. So on update/finish we present both
671 // an per-op-bound auth token and a timestamp token.
672 (Some(_), true, true) => (None, DeferredAuthState::TimeStampedOpAuthRequired),
673 (Some(hat), true, false) => {
674 (None, DeferredAuthState::TimeStampRequired(hat.take_auth_token()))
675 }
676 (Some(hat), false, true) => {
677 (Some(hat.take_auth_token()), DeferredAuthState::OpAuthRequired)
678 }
679 (Some(hat), false, false) => {
680 (Some(hat.take_auth_token()), DeferredAuthState::NoAuthRequired)
681 }
682 (None, _, true) => (None, DeferredAuthState::OpAuthRequired),
683 (None, _, false) => (None, DeferredAuthState::NoAuthRequired),
684 })
Janis Danisevskisb1673db2021-02-08 18:11:57 -0800685 .map(|(hat, state)| {
686 (hat, AuthInfo { state, key_usage_limited, confirmation_token_receiver })
687 })
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800688 }
689
690 fn find_auth_token<F>(p: F) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
691 where
692 F: Fn(&AuthTokenEntry) -> bool,
693 {
694 DB.with(|db| {
695 let mut db = db.borrow_mut();
696 db.find_auth_token_entry(p).context("Trying to find auth token.")
697 })
698 .context("In find_auth_token.")
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000699 }
700
701 /// Checks if the time now since epoch is greater than (or equal, if is_given_time_inclusive is
702 /// set) the given time (in milliseconds)
703 fn is_given_time_passed(given_time: i64, is_given_time_inclusive: bool) -> bool {
704 let duration_since_epoch = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH);
705
706 let time_since_epoch = match duration_since_epoch {
707 Ok(duration) => duration.as_millis(),
708 Err(_) => return false,
709 };
710
711 if is_given_time_inclusive {
712 time_since_epoch >= (given_time as u128)
713 } else {
714 time_since_epoch > (given_time as u128)
715 }
716 }
717
718 /// Check if the device is locked for the given user. If there's no entry yet for the user,
719 /// we assume that the device is locked
720 fn is_device_locked(&self, user_id: i32) -> bool {
721 // unwrap here because there's no way this mutex guard can be poisoned and
722 // because there's no way to recover, even if it is poisoned.
723 let set = self.device_unlocked_set.lock().unwrap();
724 !set.contains(&user_id)
725 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000726
727 /// Sets the device locked status for the user. This method is called externally.
728 pub fn set_device_locked(&self, user_id: i32, device_locked_status: bool) {
729 // unwrap here because there's no way this mutex guard can be poisoned and
730 // because there's no way to recover, even if it is poisoned.
731 let mut set = self.device_unlocked_set.lock().unwrap();
732 if device_locked_status {
733 set.remove(&user_id);
734 } else {
735 set.insert(user_id);
736 }
737 }
738
739 /// Add this auth token to the database.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800740 /// Then present the auth token to the op auth map. If an operation is waiting for this
741 /// auth token this fulfills the request and removes the receiver from the map.
742 pub fn add_auth_token(&self, hat: HardwareAuthToken) -> Result<()> {
743 DB.with(|db| db.borrow_mut().insert_auth_token(&hat)).context("In add_auth_token.")?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000744
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800745 self.op_auth_map.add_auth_token(hat);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000746 Ok(())
747 }
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000748
749 /// This allows adding an entry to the op_auth_map, indexed by the operation challenge.
750 /// This is to be called by create_operation, once it has received the operation challenge
751 /// from keymint for an operation whose authorization decision is OpAuthRequired, as signalled
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800752 /// by the DeferredAuthState.
753 fn register_op_auth_receiver(&self, challenge: i64, recv: TokenReceiver) {
754 self.op_auth_map.add_receiver(challenge, recv);
Hasini Gunasinghef04d07a2020-11-25 22:41:35 +0000755 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000756
757 /// Given the set of key parameters and flags, check if super encryption is required.
758 pub fn super_encryption_required(key_parameters: &[KeyParameter], flags: Option<i32>) -> bool {
759 let auth_bound = key_parameters.iter().any(|kp| kp.get_tag() == Tag::USER_SECURE_ID);
760
761 let skip_lskf_binding = if let Some(flags) = flags {
762 (flags & KEY_FLAG_AUTH_BOUND_WITHOUT_CRYPTOGRAPHIC_LSKF_BINDING) != 0
763 } else {
764 false
765 };
766
767 auth_bound && !skip_lskf_binding
768 }
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000769
Paul Crowley7c57bf12021-02-02 16:26:57 -0800770 /// Watch the `keystore.boot_level` system property, and keep self.boot_level up to date.
771 /// Blocks waiting for system property changes, so must be run in its own thread.
772 pub fn watch_boot_level(&self) -> Result<()> {
773 let mut w = PropertyWatcher::new("keystore.boot_level")?;
774 loop {
775 fn parse_value(_name: &str, value: &str) -> Result<Option<i32>> {
776 Ok(if value == "end" { None } else { Some(value.parse::<i32>()?) })
777 }
778 match w.read(parse_value)? {
779 Some(level) => {
780 let old = self.boot_level.fetch_max(level, Ordering::SeqCst);
781 log::info!(
782 "Read keystore.boot_level: {}; boot level {} -> {}",
783 level,
784 old,
785 std::cmp::max(old, level)
786 );
787 }
788 None => {
789 log::info!("keystore.boot_level is `end`, finishing.");
790 self.boot_level.fetch_max(i32::MAX, Ordering::SeqCst);
791 break;
792 }
793 }
794 w.wait()?;
795 }
796 Ok(())
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000797 }
798}
799
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000800// TODO: Add tests to enforcement module (b/175578618).