blob: 41a4e48931acb658b52541cac41a4030100144ea [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.
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000017use crate::auth_token_handler::AuthTokenHandler;
18use crate::database::AuthTokenEntry;
19use crate::error::Error as KeystoreError;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +000020use crate::globals::DB;
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000021use crate::key_parameter::{KeyParameter, KeyParameterValue};
22use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Hasini Gunasinghe5112c702020-11-09 22:13:25 +000023 Algorithm::Algorithm, ErrorCode::ErrorCode as Ec, HardwareAuthToken::HardwareAuthToken,
24 HardwareAuthenticatorType::HardwareAuthenticatorType, KeyPurpose::KeyPurpose,
Hasini Gunasinghe557b1032020-11-10 01:35:30 +000025 SecurityLevel::SecurityLevel, Tag::Tag, Timestamp::Timestamp,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000026};
27use android_system_keystore2::aidl::android::system::keystore2::OperationChallenge::OperationChallenge;
28use anyhow::{Context, Result};
Hasini Gunasinghe3410f792020-09-14 17:55:21 +000029use std::collections::{HashMap, HashSet};
30use std::sync::Mutex;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +000031use std::time::SystemTime;
Hasini Gunasinghe3410f792020-09-14 17:55:21 +000032
33/// Enforcements data structure
34pub struct Enforcements {
35 // This hash set contains the user ids for whom the device is currently unlocked. If a user id
36 // is not in the set, it implies that the device is locked for the user.
37 device_unlocked_set: Mutex<HashSet<i32>>,
38 // This maps the operation challenge to an optional auth token, to maintain op-auth tokens
39 // in-memory, until they are picked up and given to the operation by authorise_update_finish().
40 op_auth_map: Mutex<HashMap<i64, Option<HardwareAuthToken>>>,
41}
42
43impl Enforcements {
44 /// Creates an enforcement object with the two data structures it holds.
45 pub fn new() -> Self {
46 Enforcements {
47 device_unlocked_set: Mutex::new(HashSet::new()),
48 op_auth_map: Mutex::new(HashMap::new()),
49 }
50 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000051
52 /// Checks if update or finish calls are authorized. If the operation is based on per-op key,
53 /// try to receive the auth token from the op_auth_map. We assume that by the time update/finish
54 /// is called, the auth token has been delivered to keystore. Therefore, we do not wait for it
55 /// and if the auth token is not found in the map, an error is returned.
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000056 /// This method is called only during the first call to update or if finish is called right
57 /// after create operation, because the operation caches the authorization decisions and tokens
58 /// from previous calls to enforcement module.
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000059 pub fn authorize_update_or_finish(
60 &self,
61 key_params: &[KeyParameter],
Hasini Gunasinghe888dd352020-11-17 23:08:39 +000062 op_challenge: Option<&OperationChallenge>,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000063 ) -> Result<AuthTokenHandler> {
64 let mut user_auth_type: Option<HardwareAuthenticatorType> = None;
65 let mut user_secure_ids = Vec::<i64>::new();
66 let mut is_timeout_key = false;
67
68 for key_param in key_params.iter() {
69 match key_param.key_parameter_value() {
70 KeyParameterValue::NoAuthRequired => {
71 // unlike in authorize_create, we do not check if both NoAuthRequired and user
72 // secure id are present, because that is already checked in authorize_create.
73 return Ok(AuthTokenHandler::NoAuthRequired);
74 }
75 KeyParameterValue::AuthTimeout(_) => {
76 is_timeout_key = true;
77 }
78 KeyParameterValue::HardwareAuthenticatorType(a) => {
79 user_auth_type = Some(*a);
80 }
81 KeyParameterValue::UserSecureID(u) => {
82 user_secure_ids.push(*u);
83 }
84 _ => {}
85 }
86 }
87
88 // If either of auth_type or secure_id is present and the other is not present,
89 // authorize_create would have already returned error.
90 // At this point, if UserSecureID is present and AuthTimeout is not present in
91 // key parameters, per-op auth is required.
92 // Obtain and validate the auth token.
93 if !is_timeout_key && !user_secure_ids.is_empty() {
94 let challenge =
95 op_challenge.ok_or(KeystoreError::Km(Ec::KEY_USER_NOT_AUTHENTICATED)).context(
96 "In authorize_update_or_finish: Auth required, but operation challenge is not
97 present.",
98 )?;
99 let auth_type =
100 user_auth_type.ok_or(KeystoreError::Km(Ec::KEY_USER_NOT_AUTHENTICATED)).context(
101 "In authorize_update_or_finish: Auth required, but authenticator type is not
102 present.",
103 )?;
104 // It is ok to unwrap here, because there is no way this lock can get poisoned and
105 // and there is no way to recover if it is poisoned.
106 let mut op_auth_map_guard = self.op_auth_map.lock().unwrap();
107 let auth_entry = op_auth_map_guard.remove(&(challenge.challenge));
108
109 match auth_entry {
110 Some(Some(auth_token)) => {
111 if AuthTokenEntry::satisfies_auth(&auth_token, &user_secure_ids, auth_type) {
112 return Ok(AuthTokenHandler::Token(auth_token, None));
113 } else {
114 return Err(KeystoreError::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
115 .context("In authorize_update_or_finish: Auth token does not match.");
116 }
117 }
118 _ => {
119 // there was no auth token
120 return Err(KeystoreError::Km(Ec::KEY_USER_NOT_AUTHENTICATED)).context(
121 "In authorize_update_or_finish: Auth required, but an auth token
122 is not found for the given operation challenge, in the op_auth_map.",
123 );
124 }
125 }
126 }
127
128 // If we don't find HardwareAuthenticatorType and UserSecureID, we assume that
129 // authentication is not required, because in legacy keys, authentication related
130 // key parameters may not present.
131 // TODO: METRICS: count how many times (if any) this code path is executed, in order
132 // to identify if any such keys are in use
133 Ok(AuthTokenHandler::NoAuthRequired)
134 }
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000135
136 /// Checks if a create call is authorized, given key parameters and operation parameters.
137 /// With regard to auth tokens, the following steps are taken:
138 /// If the key is time-bound, find a matching auth token from the database.
139 /// If the above step is successful, and if the security level is STRONGBOX, return a
140 /// VerificationRequired variant of the AuthTokenHandler with the found auth token to signal
141 /// the operation that it may need to obtain a verification token from TEE KeyMint.
142 /// If the security level is not STRONGBOX, return a Token variant of the AuthTokenHandler with
143 /// the found auth token to signal the operation that no more authorization required.
144 /// If the key is per-op, return an OpAuthRequired variant of the AuthTokenHandler to signal
145 /// create_operation() that it needs to add the operation challenge to the op_auth_map, once it
146 /// is received from the keymint, and that operation needs to be authorized before update/finish
147 /// is called.
148 pub fn authorize_create(
149 &self,
150 purpose: KeyPurpose,
151 key_params: &[KeyParameter],
152 op_params: &[KeyParameter],
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000153 security_level: SecurityLevel,
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000154 ) -> Result<AuthTokenHandler> {
155 match purpose {
156 // Allow SIGN, DECRYPT for both symmetric and asymmetric keys.
157 KeyPurpose::SIGN | KeyPurpose::DECRYPT => {}
158 // Rule out WRAP_KEY purpose
159 KeyPurpose::WRAP_KEY => {
160 return Err(KeystoreError::Km(Ec::INCOMPATIBLE_PURPOSE))
161 .context("In authorize_create: WRAP_KEY purpose is not allowed here.");
162 }
163 KeyPurpose::VERIFY | KeyPurpose::ENCRYPT => {
164 // We do not support ENCRYPT and VERIFY (the remaining two options of purpose) for
165 // asymmetric keys.
166 for kp in key_params.iter() {
167 match *kp.key_parameter_value() {
168 KeyParameterValue::Algorithm(Algorithm::RSA)
169 | KeyParameterValue::Algorithm(Algorithm::EC) => {
170 return Err(KeystoreError::Km(Ec::UNSUPPORTED_PURPOSE)).context(
171 "In authorize_create: public operations on asymmetric keys are not
172 supported.",
173 );
174 }
175 _ => {}
176 }
177 }
178 }
179 _ => {
180 return Err(KeystoreError::Km(Ec::UNSUPPORTED_PURPOSE))
181 .context("In authorize_create: specified purpose is not supported.");
182 }
183 }
184 // The following variables are to record information from key parameters to be used in
185 // enforcements, when two or more such pieces of information are required for enforcements.
186 // There is only one additional variable than what legacy keystore has, but this helps
187 // reduce the number of for loops on key parameters from 3 to 1, compared to legacy keystore
188 let mut key_purpose_authorized: bool = false;
189 let mut is_time_out_key: bool = false;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000190 let mut user_auth_type: Option<HardwareAuthenticatorType> = None;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000191 let mut no_auth_required: bool = false;
192 let mut caller_nonce_allowed = false;
193 let mut user_id: i32 = -1;
194 let mut user_secure_ids = Vec::<i64>::new();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000195 let mut key_time_out: Option<i64> = None;
196 let mut allow_while_on_body = false;
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000197
198 // iterate through key parameters, recording information we need for authorization
199 // enforcements later, or enforcing authorizations in place, where applicable
200 for key_param in key_params.iter() {
201 match key_param.key_parameter_value() {
202 KeyParameterValue::NoAuthRequired => {
203 no_auth_required = true;
204 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000205 KeyParameterValue::AuthTimeout(t) => {
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000206 is_time_out_key = true;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000207 key_time_out = Some(*t as i64);
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000208 }
209 KeyParameterValue::HardwareAuthenticatorType(a) => {
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000210 user_auth_type = Some(*a);
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000211 }
212 KeyParameterValue::KeyPurpose(p) => {
213 // Note: if there can be multiple KeyPurpose key parameters (TODO: confirm this),
214 // following check has the effect of key_params.contains(purpose)
215 // Also, authorizing purpose can not be completed here, if there can be multiple
216 // key parameters for KeyPurpose
217 if !key_purpose_authorized && *p == purpose {
218 key_purpose_authorized = true;
219 }
220 }
221 KeyParameterValue::CallerNonce => {
222 caller_nonce_allowed = true;
223 }
224 KeyParameterValue::ActiveDateTime(a) => {
225 if !Enforcements::is_given_time_passed(*a, true) {
226 return Err(KeystoreError::Km(Ec::KEY_NOT_YET_VALID))
227 .context("In authorize_create: key is not yet active.");
228 }
229 }
230 KeyParameterValue::OriginationExpireDateTime(o) => {
231 if (purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN)
232 && Enforcements::is_given_time_passed(*o, false)
233 {
234 return Err(KeystoreError::Km(Ec::KEY_EXPIRED))
235 .context("In authorize_create: key is expired.");
236 }
237 }
238 KeyParameterValue::UsageExpireDateTime(u) => {
239 if (purpose == KeyPurpose::DECRYPT || purpose == KeyPurpose::VERIFY)
240 && Enforcements::is_given_time_passed(*u, false)
241 {
242 return Err(KeystoreError::Km(Ec::KEY_EXPIRED))
243 .context("In authorize_create: key is expired.");
244 }
245 }
246 KeyParameterValue::UserSecureID(s) => {
247 user_secure_ids.push(*s);
248 }
249 KeyParameterValue::UserID(u) => {
250 user_id = *u;
251 }
252 KeyParameterValue::UnlockedDeviceRequired => {
253 // check the device locked status. If locked, operations on the key are not
254 // allowed.
255 if self.is_device_locked(user_id) {
256 return Err(KeystoreError::Km(Ec::DEVICE_LOCKED))
257 .context("In authorize_create: device is locked.");
258 }
259 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000260 KeyParameterValue::AllowWhileOnBody => {
261 allow_while_on_body = true;
262 }
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000263 // NOTE: as per offline discussion, sanitizing key parameters and rejecting
264 // create operation if any non-allowed tags are present, is not done in
265 // authorize_create (unlike in legacy keystore where AuthorizeBegin is rejected if
266 // a subset of non-allowed tags are present). Because santizing key parameters
267 // should have been done during generate/import key, by KeyMint.
268 _ => { /*Do nothing on all the other key parameters, as in legacy keystore*/ }
269 }
270 }
271
272 // authorize the purpose
273 if !key_purpose_authorized {
274 return Err(KeystoreError::Km(Ec::INCOMPATIBLE_PURPOSE))
275 .context("In authorize_create: the purpose is not authorized.");
276 }
277
278 // if both NO_AUTH_REQUIRED and USER_SECURE_ID tags are present, return error
279 if !user_secure_ids.is_empty() && no_auth_required {
280 return Err(KeystoreError::Km(Ec::INVALID_KEY_BLOB)).context(
281 "In authorize_create: key has both NO_AUTH_REQUIRED
282 and USER_SECURE_ID tags.",
283 );
284 }
285
286 // 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 +0000287 if (user_auth_type.is_some() && user_secure_ids.is_empty())
288 || (user_auth_type.is_none() && !user_secure_ids.is_empty())
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000289 {
290 return Err(KeystoreError::Km(Ec::KEY_USER_NOT_AUTHENTICATED)).context(
291 "In authorize_create: Auth required, but either auth type or secure ids
292 are not present.",
293 );
294 }
295 // validate caller nonce for origination purposes
296 if (purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN)
297 && !caller_nonce_allowed
298 && op_params.iter().any(|kp| kp.get_tag() == Tag::NONCE)
299 {
300 return Err(KeystoreError::Km(Ec::CALLER_NONCE_PROHIBITED)).context(
301 "In authorize_create, NONCE is present,
302 although CALLER_NONCE is not present",
303 );
304 }
305
306 if !user_secure_ids.is_empty() {
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000307 // key requiring authentication per operation
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000308 if !is_time_out_key {
309 return Ok(AuthTokenHandler::OpAuthRequired);
310 } else {
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +0000311 // key requiring time-out based authentication
312 let auth_token = DB
313 .with::<_, Result<HardwareAuthToken>>(|db| {
314 let mut db = db.borrow_mut();
315 match (user_auth_type, key_time_out) {
316 (Some(auth_type), Some(key_time_out)) => {
317 let matching_entry = db
318 .find_timed_auth_token_entry(
319 &user_secure_ids,
320 auth_type,
321 key_time_out,
322 allow_while_on_body,
323 )
324 .context("Failed to find timed auth token.")?;
325 Ok(matching_entry.get_auth_token())
326 }
327 (_, _) => Err(KeystoreError::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
328 .context("Authenticator type and/or key time out is not given."),
329 }
330 })
331 .context("In authorize_create.")?;
332
333 if security_level == SecurityLevel::STRONGBOX {
334 return Ok(AuthTokenHandler::VerificationRequired(auth_token));
335 } else {
336 return Ok(AuthTokenHandler::Token(auth_token, None));
337 }
Hasini Gunasinghe5112c702020-11-09 22:13:25 +0000338 }
339 }
340
341 // If we reach here, all authorization enforcements have passed and no auth token required.
342 Ok(AuthTokenHandler::NoAuthRequired)
343 }
344
345 /// Checks if the time now since epoch is greater than (or equal, if is_given_time_inclusive is
346 /// set) the given time (in milliseconds)
347 fn is_given_time_passed(given_time: i64, is_given_time_inclusive: bool) -> bool {
348 let duration_since_epoch = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH);
349
350 let time_since_epoch = match duration_since_epoch {
351 Ok(duration) => duration.as_millis(),
352 Err(_) => return false,
353 };
354
355 if is_given_time_inclusive {
356 time_since_epoch >= (given_time as u128)
357 } else {
358 time_since_epoch > (given_time as u128)
359 }
360 }
361
362 /// Check if the device is locked for the given user. If there's no entry yet for the user,
363 /// we assume that the device is locked
364 fn is_device_locked(&self, user_id: i32) -> bool {
365 // unwrap here because there's no way this mutex guard can be poisoned and
366 // because there's no way to recover, even if it is poisoned.
367 let set = self.device_unlocked_set.lock().unwrap();
368 !set.contains(&user_id)
369 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000370
371 /// Sets the device locked status for the user. This method is called externally.
372 pub fn set_device_locked(&self, user_id: i32, device_locked_status: bool) {
373 // unwrap here because there's no way this mutex guard can be poisoned and
374 // because there's no way to recover, even if it is poisoned.
375 let mut set = self.device_unlocked_set.lock().unwrap();
376 if device_locked_status {
377 set.remove(&user_id);
378 } else {
379 set.insert(user_id);
380 }
381 }
382
383 /// Add this auth token to the database.
384 /// Then check if there is an entry in the op_auth_map, indexed by the challenge of this
385 /// auth token (which could have been inserted during create_operation of an operation on a
386 /// per-op-auth key). If so, add a copy of this auth token to the map indexed by the
387 /// challenge.
388 pub fn add_auth_token(&self, auth_token: HardwareAuthToken) -> Result<()> {
389 //it is ok to unwrap here, because there is no way this lock can get poisoned and
390 //and there is no way to recover if it is poisoned.
391 let mut op_auth_map_guard = self.op_auth_map.lock().unwrap();
392
393 if op_auth_map_guard.contains_key(&auth_token.challenge) {
394 let auth_token_copy = HardwareAuthToken {
395 challenge: auth_token.challenge,
396 userId: auth_token.userId,
397 authenticatorId: auth_token.authenticatorId,
398 authenticatorType: HardwareAuthenticatorType(auth_token.authenticatorType.0),
399 timestamp: Timestamp { milliSeconds: auth_token.timestamp.milliSeconds },
400 mac: auth_token.mac.clone(),
401 };
402 op_auth_map_guard.insert(auth_token.challenge, Some(auth_token_copy));
403 }
404
405 DB.with(|db| db.borrow_mut().insert_auth_token(&auth_token))
406 .context("In add_auth_token.")?;
407 Ok(())
408 }
Hasini Gunasinghe888dd352020-11-17 23:08:39 +0000409
410 /// This allows adding an entry to the op_auth_map, indexed by the operation challenge.
411 /// This is to be called by create_operation, once it has received the operation challenge
412 /// from keymint for an operation whose authorization decision is OpAuthRequired, as signalled
413 /// by the AuthTokenHandler.
414 pub fn insert_to_op_auth_map(&self, op_challenge: i64) {
415 let mut op_auth_map_guard = self.op_auth_map.lock().unwrap();
416 op_auth_map_guard.insert(op_challenge, None);
417 }
Hasini Gunasinghe3410f792020-09-14 17:55:21 +0000418}
419
420impl Default for Enforcements {
421 fn default() -> Self {
422 Self::new()
423 }
424}
425
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000426// TODO: Add tests to enforcement module (b/175578618).