Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 1 | // Copyright 2020, The Android Open Source Project |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 15 | //! Key parameters are declared by KeyMint to describe properties of keys and operations. |
| 16 | //! During key generation and import, key parameters are used to characterize a key, its usage |
| 17 | //! restrictions, and additional parameters for attestation. During the lifetime of the key, |
| 18 | //! the key characteristics are expressed as set of key parameters. During cryptographic |
| 19 | //! operations, clients may specify additional operation specific parameters. |
| 20 | //! This module provides a Keystore 2.0 internal representation for key parameters and |
| 21 | //! implements traits to convert it from and into KeyMint KeyParameters and store it in |
| 22 | //! the SQLite database. |
| 23 | //! |
| 24 | //! ## Synopsis |
| 25 | //! |
| 26 | //! enum KeyParameterValue { |
| 27 | //! Invalid, |
| 28 | //! Algorithm(Algorithm), |
| 29 | //! ... |
| 30 | //! } |
| 31 | //! |
| 32 | //! impl KeyParameterValue { |
| 33 | //! pub fn get_tag(&self) -> Tag; |
| 34 | //! pub fn new_from_sql(tag: Tag, data: &SqlField) -> Result<Self>; |
Janis Danisevskis | 6b00e25 | 2020-12-22 11:36:45 -0800 | [diff] [blame^] | 35 | //! pub fn new_from_tag_primitive_pair<T: Into<Primitive>>(tag: Tag, v: T) |
| 36 | //! -> Result<Self, PrimitiveError>; |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 37 | //! fn to_sql(&self) -> SqlResult<ToSqlOutput> |
| 38 | //! } |
| 39 | //! |
| 40 | //! use ...::keymint::KeyParameter as KmKeyParameter; |
| 41 | //! impl Into<KmKeyParameter> for KeyParameterValue {} |
| 42 | //! impl From<KmKeyParameter> for KeyParameterValue {} |
| 43 | //! |
| 44 | //! ## Implementation |
Janis Danisevskis | 6b00e25 | 2020-12-22 11:36:45 -0800 | [diff] [blame^] | 45 | //! Each of the six functions is implemented as match statement over each key parameter variant. |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 46 | //! We bootstrap these function as well as the KeyParameterValue enum itself from a single list |
| 47 | //! of key parameters, that needs to be kept in sync with the KeyMint AIDL specification. |
| 48 | //! |
| 49 | //! The list resembles an enum declaration with a few extra fields. |
| 50 | //! enum KeyParameterValue { |
| 51 | //! Invalid with tag INVALID and field Invalid, |
| 52 | //! Algorithm(Algorithm) with tag ALGORITHM and field Algorithm, |
| 53 | //! ... |
| 54 | //! } |
| 55 | //! The tag corresponds to the variant of the keymint::Tag, and the field corresponds to the |
| 56 | //! variant of the keymint::KeyParameterValue union. There is no one to one mapping between |
| 57 | //! tags and union fields, e.g., the values of both tags BOOT_PATCHLEVEL and VENDOR_PATCHLEVEL |
| 58 | //! are stored in the Integer field. |
| 59 | //! |
| 60 | //! The macros interpreting them all follow a similar pattern and follow the following fragment |
| 61 | //! naming scheme: |
| 62 | //! |
| 63 | //! Algorithm(Algorithm) with tag ALGORITHM and field Algorithm, |
| 64 | //! $vname $(($vtype ))? with tag $tag_name and field $field_name, |
| 65 | //! |
| 66 | //! Further, KeyParameterValue appears in the macro as $enum_name. |
| 67 | //! Note that $vtype is optional to accommodate variants like Invalid which don't wrap a value. |
| 68 | //! |
| 69 | //! In some cases $vtype is not part of the expansion, but we still have to modify the expansion |
| 70 | //! depending on the presence of $vtype. In these cases we recurse through the list following the |
| 71 | //! following pattern: |
| 72 | //! |
| 73 | //! (@<marker> <non repeating args>, [<out list>], [<in list>]) |
| 74 | //! |
| 75 | //! These macros usually have four rules: |
| 76 | //! * Two main recursive rules, of the form: |
| 77 | //! ( |
| 78 | //! @<marker> |
| 79 | //! <non repeating args>, |
| 80 | //! [<out list>], |
| 81 | //! [<one element pattern> <in tail>] |
| 82 | //! ) => { |
| 83 | //! macro!{@<marker> <non repeating args>, [<out list> |
| 84 | //! <one element expansion> |
| 85 | //! ], [<in tail>]} |
| 86 | //! }; |
| 87 | //! They pop one element off the <in list> and add one expansion to the out list. |
| 88 | //! The element expansion is kept on a separate line (or lines) for better readability. |
| 89 | //! The two variants differ in whether or not $vtype is expected. |
| 90 | //! * The termination condition which has an empty in list. |
| 91 | //! * The public interface, which does not have @marker and calls itself with an empty out list. |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 92 | |
Janis Danisevskis | 6b00e25 | 2020-12-22 11:36:45 -0800 | [diff] [blame^] | 93 | use std::convert::TryInto; |
| 94 | |
Janis Danisevskis | 4522c2b | 2020-11-27 18:04:58 -0800 | [diff] [blame] | 95 | use crate::db_utils::SqlField; |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 96 | use crate::error::Error as KeystoreError; |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 97 | use crate::error::ResponseCode; |
| 98 | |
Shawn Willden | 708744a | 2020-12-11 13:05:27 +0000 | [diff] [blame] | 99 | pub use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{ |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 100 | Algorithm::Algorithm, BlockMode::BlockMode, Digest::Digest, EcCurve::EcCurve, |
| 101 | HardwareAuthenticatorType::HardwareAuthenticatorType, KeyOrigin::KeyOrigin, |
Janis Danisevskis | 398e6be | 2020-12-17 09:29:25 -0800 | [diff] [blame] | 102 | KeyParameter::KeyParameter as KmKeyParameter, |
| 103 | KeyParameterValue::KeyParameterValue as KmKeyParameterValue, KeyPurpose::KeyPurpose, |
| 104 | PaddingMode::PaddingMode, SecurityLevel::SecurityLevel, Tag::Tag, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 105 | }; |
Janis Danisevskis | a53c9cf | 2020-10-26 11:52:33 -0700 | [diff] [blame] | 106 | use android_system_keystore2::aidl::android::system::keystore2::Authorization::Authorization; |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 107 | use anyhow::{Context, Result}; |
Janis Danisevskis | 4522c2b | 2020-11-27 18:04:58 -0800 | [diff] [blame] | 108 | use rusqlite::types::{Null, ToSql, ToSqlOutput}; |
| 109 | use rusqlite::Result as SqlResult; |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 110 | |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 111 | /// This trait is used to associate a primitive to any type that can be stored inside a |
| 112 | /// KeyParameterValue, especially the AIDL enum types, e.g., keymint::{Algorithm, Digest, ...}. |
| 113 | /// This allows for simplifying the macro rules, e.g., for reading from the SQL database. |
| 114 | /// An expression like `KeyParameterValue::Algorithm(row.get(0))` would not work because |
| 115 | /// a type of `Algorithm` is expected which does not implement `FromSql` and we cannot |
| 116 | /// implement it because we own neither the type nor the trait. |
| 117 | /// With AssociatePrimitive we can write an expression |
| 118 | /// `KeyParameter::Algorithm(<Algorithm>::from_primitive(row.get(0)))` to inform `get` |
| 119 | /// about the expected primitive type that it can convert into. By implementing this |
| 120 | /// trait for all inner types we can write a single rule to cover all cases (except where |
| 121 | /// there is no wrapped type): |
| 122 | /// `KeyParameterValue::$vname(<$vtype>::from_primitive(row.get(0)))` |
| 123 | trait AssociatePrimitive { |
| 124 | type Primitive; |
| 125 | |
| 126 | fn from_primitive(v: Self::Primitive) -> Self; |
| 127 | fn to_primitive(&self) -> Self::Primitive; |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 128 | } |
| 129 | |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 130 | /// Associates the given type with i32. The macro assumes that the given type is actually a |
| 131 | /// tuple struct wrapping i32, such as AIDL enum types. |
| 132 | macro_rules! implement_associate_primitive_for_aidl_enum { |
| 133 | ($t:ty) => { |
| 134 | impl AssociatePrimitive for $t { |
| 135 | type Primitive = i32; |
| 136 | |
| 137 | fn from_primitive(v: Self::Primitive) -> Self { |
| 138 | Self(v) |
| 139 | } |
| 140 | fn to_primitive(&self) -> Self::Primitive { |
| 141 | self.0 |
| 142 | } |
| 143 | } |
| 144 | }; |
| 145 | } |
| 146 | |
| 147 | /// Associates the given type with itself. |
| 148 | macro_rules! implement_associate_primitive_identity { |
| 149 | ($t:ty) => { |
| 150 | impl AssociatePrimitive for $t { |
| 151 | type Primitive = $t; |
| 152 | |
| 153 | fn from_primitive(v: Self::Primitive) -> Self { |
| 154 | v |
| 155 | } |
| 156 | fn to_primitive(&self) -> Self::Primitive { |
| 157 | self.clone() |
| 158 | } |
| 159 | } |
| 160 | }; |
| 161 | } |
| 162 | |
| 163 | implement_associate_primitive_for_aidl_enum! {Algorithm} |
| 164 | implement_associate_primitive_for_aidl_enum! {BlockMode} |
| 165 | implement_associate_primitive_for_aidl_enum! {Digest} |
| 166 | implement_associate_primitive_for_aidl_enum! {EcCurve} |
| 167 | implement_associate_primitive_for_aidl_enum! {HardwareAuthenticatorType} |
| 168 | implement_associate_primitive_for_aidl_enum! {KeyOrigin} |
| 169 | implement_associate_primitive_for_aidl_enum! {KeyPurpose} |
| 170 | implement_associate_primitive_for_aidl_enum! {PaddingMode} |
| 171 | implement_associate_primitive_for_aidl_enum! {SecurityLevel} |
| 172 | |
| 173 | implement_associate_primitive_identity! {Vec<u8>} |
| 174 | implement_associate_primitive_identity! {i64} |
| 175 | implement_associate_primitive_identity! {i32} |
| 176 | |
Janis Danisevskis | 6b00e25 | 2020-12-22 11:36:45 -0800 | [diff] [blame^] | 177 | /// This enum allows passing a primitive value to `KeyParameterValue::new_from_tag_primitive_pair` |
| 178 | /// Usually, it is not necessary to use this type directly because the function uses |
| 179 | /// `Into<Primitive>` as a trait bound. |
| 180 | pub enum Primitive { |
| 181 | /// Wraps an i64. |
| 182 | I64(i64), |
| 183 | /// Wraps an i32. |
| 184 | I32(i32), |
| 185 | /// Wraps a Vec<u8>. |
| 186 | Vec(Vec<u8>), |
| 187 | } |
| 188 | |
| 189 | impl From<i64> for Primitive { |
| 190 | fn from(v: i64) -> Self { |
| 191 | Self::I64(v) |
| 192 | } |
| 193 | } |
| 194 | impl From<i32> for Primitive { |
| 195 | fn from(v: i32) -> Self { |
| 196 | Self::I32(v) |
| 197 | } |
| 198 | } |
| 199 | impl From<Vec<u8>> for Primitive { |
| 200 | fn from(v: Vec<u8>) -> Self { |
| 201 | Self::Vec(v) |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | /// This error is returned by `KeyParameterValue::new_from_tag_primitive_pair`. |
| 206 | #[derive(thiserror::Error, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] |
| 207 | pub enum PrimitiveError { |
| 208 | /// Returned if this primitive is unsuitable for the given tag type. |
| 209 | #[error("Primitive does not match the expected tag type.")] |
| 210 | TypeMismatch, |
| 211 | /// Return if the tag type is unknown. |
| 212 | #[error("Unknown tag.")] |
| 213 | UnknownTag, |
| 214 | } |
| 215 | |
| 216 | impl TryInto<i64> for Primitive { |
| 217 | type Error = PrimitiveError; |
| 218 | |
| 219 | fn try_into(self) -> Result<i64, Self::Error> { |
| 220 | match self { |
| 221 | Self::I64(v) => Ok(v), |
| 222 | _ => Err(Self::Error::TypeMismatch), |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | impl TryInto<i32> for Primitive { |
| 227 | type Error = PrimitiveError; |
| 228 | |
| 229 | fn try_into(self) -> Result<i32, Self::Error> { |
| 230 | match self { |
| 231 | Self::I32(v) => Ok(v), |
| 232 | _ => Err(Self::Error::TypeMismatch), |
| 233 | } |
| 234 | } |
| 235 | } |
| 236 | impl TryInto<Vec<u8>> for Primitive { |
| 237 | type Error = PrimitiveError; |
| 238 | |
| 239 | fn try_into(self) -> Result<Vec<u8>, Self::Error> { |
| 240 | match self { |
| 241 | Self::Vec(v) => Ok(v), |
| 242 | _ => Err(Self::Error::TypeMismatch), |
| 243 | } |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | /// Expands the list of KeyParameterValue variants as follows: |
| 248 | /// |
| 249 | /// Input: |
| 250 | /// Invalid with tag INVALID and field Invalid, |
| 251 | /// Algorithm(Algorithm) with tag ALGORITHM and field Algorithm, |
| 252 | /// |
| 253 | /// Output: |
| 254 | /// ``` |
| 255 | /// pub fn new_from_tag_primitive_pair<T: Into<Primitive>>( |
| 256 | /// tag: Tag, |
| 257 | /// v: T |
| 258 | /// ) -> Result<KeyParameterValue, PrimitiveError> { |
| 259 | /// let p: Primitive = v.into(); |
| 260 | /// Ok(match tag { |
| 261 | /// Tag::INVALID => KeyParameterValue::Invalid, |
| 262 | /// Tag::ALGORITHM => KeyParameterValue::Algorithm( |
| 263 | /// <Algorithm>::from_primitive(p.try_into()?) |
| 264 | /// ), |
| 265 | /// _ => return Err(PrimitiveError::UnknownTag), |
| 266 | /// }) |
| 267 | /// } |
| 268 | /// ``` |
| 269 | macro_rules! implement_from_tag_primitive_pair { |
| 270 | ($enum_name:ident; $($vname:ident$(($vtype:ty))? $tag_name:ident),*) => { |
| 271 | /// Returns the an instance of $enum_name or an error if the given primitive does not match |
| 272 | /// the tag type or the tag is unknown. |
| 273 | pub fn new_from_tag_primitive_pair<T: Into<Primitive>>( |
| 274 | tag: Tag, |
| 275 | v: T |
| 276 | ) -> Result<$enum_name, PrimitiveError> { |
| 277 | let p: Primitive = v.into(); |
| 278 | Ok(match tag { |
| 279 | $(Tag::$tag_name => $enum_name::$vname$(( |
| 280 | <$vtype>::from_primitive(p.try_into()?) |
| 281 | ))?,)* |
| 282 | _ => return Err(PrimitiveError::UnknownTag), |
| 283 | }) |
| 284 | } |
| 285 | }; |
| 286 | } |
| 287 | |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 288 | /// Expands the list of KeyParameterValue variants as follows: |
| 289 | /// |
| 290 | /// Input: |
| 291 | /// pub enum KeyParameterValue { |
| 292 | /// Invalid with tag INVALID and field Invalid, |
| 293 | /// Algorithm(Algorithm) with tag ALGORITHM and field Algorithm, |
| 294 | /// } |
| 295 | /// |
| 296 | /// Output: |
| 297 | /// ``` |
| 298 | /// pub enum KeyParameterValue { |
| 299 | /// Invalid, |
| 300 | /// Algorithm(Algorithm), |
| 301 | /// } |
| 302 | /// ``` |
| 303 | macro_rules! implement_enum { |
| 304 | ( |
| 305 | $(#[$enum_meta:meta])* |
| 306 | $enum_vis:vis enum $enum_name:ident { |
| 307 | $($(#[$emeta:meta])* $vname:ident$(($vtype:ty))?),* $(,)? |
| 308 | } |
| 309 | ) => { |
| 310 | $(#[$enum_meta])* |
| 311 | $enum_vis enum $enum_name { |
| 312 | $( |
| 313 | $(#[$emeta])* |
| 314 | $vname$(($vtype))? |
| 315 | ),* |
| 316 | } |
| 317 | }; |
| 318 | } |
| 319 | |
| 320 | /// Expands the list of KeyParameterValue variants as follows: |
| 321 | /// |
| 322 | /// Input: |
| 323 | /// Invalid with tag INVALID and field Invalid, |
| 324 | /// Algorithm(Algorithm) with tag ALGORITHM and field Algorithm, |
| 325 | /// |
| 326 | /// Output: |
| 327 | /// ``` |
| 328 | /// pub fn get_tag(&self) -> Tag { |
| 329 | /// match self { |
| 330 | /// KeyParameterValue::Invalid => Tag::INVALID, |
| 331 | /// KeyParameterValue::Algorithm(_) => Tag::ALGORITHM, |
| 332 | /// } |
| 333 | /// } |
| 334 | /// ``` |
| 335 | macro_rules! implement_get_tag { |
| 336 | ( |
| 337 | @replace_type_spec |
| 338 | $enum_name:ident, |
| 339 | [$($out:tt)*], |
| 340 | [$vname:ident($vtype:ty) $tag_name:ident, $($in:tt)*] |
| 341 | ) => { |
| 342 | implement_get_tag!{@replace_type_spec $enum_name, [$($out)* |
| 343 | $enum_name::$vname(_) => Tag::$tag_name, |
| 344 | ], [$($in)*]} |
| 345 | }; |
| 346 | ( |
| 347 | @replace_type_spec |
| 348 | $enum_name:ident, |
| 349 | [$($out:tt)*], |
| 350 | [$vname:ident $tag_name:ident, $($in:tt)*] |
| 351 | ) => { |
| 352 | implement_get_tag!{@replace_type_spec $enum_name, [$($out)* |
| 353 | $enum_name::$vname => Tag::$tag_name, |
| 354 | ], [$($in)*]} |
| 355 | }; |
| 356 | (@replace_type_spec $enum_name:ident, [$($out:tt)*], []) => { |
| 357 | /// Returns the tag of the given instance. |
| 358 | pub fn get_tag(&self) -> Tag { |
| 359 | match self { |
| 360 | $($out)* |
| 361 | } |
| 362 | } |
| 363 | }; |
| 364 | |
| 365 | ($enum_name:ident; $($vname:ident$(($vtype:ty))? $tag_name:ident),*) => { |
| 366 | implement_get_tag!{@replace_type_spec $enum_name, [], [$($vname$(($vtype))? $tag_name,)*]} |
| 367 | }; |
| 368 | } |
| 369 | |
| 370 | /// Expands the list of KeyParameterValue variants as follows: |
| 371 | /// |
| 372 | /// Input: |
| 373 | /// Invalid with tag INVALID and field Invalid, |
| 374 | /// Algorithm(Algorithm) with tag ALGORITHM and field Algorithm, |
| 375 | /// |
| 376 | /// Output: |
| 377 | /// ``` |
| 378 | /// fn to_sql(&self) -> SqlResult<ToSqlOutput> { |
| 379 | /// match self { |
| 380 | /// KeyParameterValue::Invalid => Ok(ToSqlOutput::from(Null)), |
| 381 | /// KeyParameterValue::Algorithm(v) => Ok(ToSqlOutput::from(v.to_primitive())), |
| 382 | /// } |
| 383 | /// } |
| 384 | /// ``` |
| 385 | macro_rules! implement_to_sql { |
| 386 | ( |
| 387 | @replace_type_spec |
| 388 | $enum_name:ident, |
| 389 | [$($out:tt)*], |
| 390 | [$vname:ident($vtype:ty), $($in:tt)*] |
| 391 | ) => { |
| 392 | implement_to_sql!{@replace_type_spec $enum_name, [ $($out)* |
| 393 | $enum_name::$vname(v) => Ok(ToSqlOutput::from(v.to_primitive())), |
| 394 | ], [$($in)*]} |
| 395 | }; |
| 396 | ( |
| 397 | @replace_type_spec |
| 398 | $enum_name:ident, |
| 399 | [$($out:tt)*], |
| 400 | [$vname:ident, $($in:tt)*] |
| 401 | ) => { |
| 402 | implement_to_sql!{@replace_type_spec $enum_name, [ $($out)* |
| 403 | $enum_name::$vname => Ok(ToSqlOutput::from(Null)), |
| 404 | ], [$($in)*]} |
| 405 | }; |
| 406 | (@replace_type_spec $enum_name:ident, [$($out:tt)*], []) => { |
| 407 | /// Converts $enum_name to be stored in a rusqlite database. |
| 408 | fn to_sql(&self) -> SqlResult<ToSqlOutput> { |
| 409 | match self { |
| 410 | $($out)* |
| 411 | } |
| 412 | } |
| 413 | }; |
| 414 | |
| 415 | |
| 416 | ($enum_name:ident; $($vname:ident$(($vtype:ty))?),*) => { |
| 417 | impl ToSql for $enum_name { |
| 418 | implement_to_sql!{@replace_type_spec $enum_name, [], [$($vname$(($vtype))?,)*]} |
| 419 | } |
| 420 | |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | /// Expands the list of KeyParameterValue variants as follows: |
| 425 | /// |
| 426 | /// Input: |
| 427 | /// Invalid with tag INVALID and field Invalid, |
| 428 | /// Algorithm(Algorithm) with tag ALGORITHM and field Algorithm, |
| 429 | /// |
| 430 | /// Output: |
| 431 | /// ``` |
| 432 | /// pub fn new_from_sql( |
| 433 | /// tag: Tag, |
| 434 | /// data: &SqlField, |
| 435 | /// ) -> Result<Self> { |
| 436 | /// Ok(match self { |
| 437 | /// Tag::Invalid => KeyParameterValue::Invalid, |
| 438 | /// Tag::ALGORITHM => { |
| 439 | /// KeyParameterValue::Algorithm(<Algorithm>::from_primitive(data |
| 440 | /// .get() |
| 441 | /// .map_err(|_| KeystoreError::Rc(ResponseCode::VALUE_CORRUPTED)) |
| 442 | /// .context(concat!("Failed to read sql data for tag: ", "ALGORITHM", "."))? |
| 443 | /// )) |
| 444 | /// }, |
| 445 | /// }) |
| 446 | /// } |
| 447 | /// ``` |
| 448 | macro_rules! implement_new_from_sql { |
| 449 | ($enum_name:ident; $($vname:ident$(($vtype:ty))? $tag_name:ident),*) => { |
| 450 | /// Takes a tag and an SqlField and attempts to construct a KeyParameter value. |
| 451 | /// This function may fail if the parameter value cannot be extracted from the |
| 452 | /// database cell. |
| 453 | pub fn new_from_sql( |
| 454 | tag: Tag, |
| 455 | data: &SqlField, |
| 456 | ) -> Result<Self> { |
| 457 | Ok(match tag { |
| 458 | $( |
| 459 | Tag::$tag_name => { |
| 460 | $enum_name::$vname$((<$vtype>::from_primitive(data |
| 461 | .get() |
| 462 | .map_err(|_| KeystoreError::Rc(ResponseCode::VALUE_CORRUPTED)) |
| 463 | .context(concat!( |
| 464 | "Failed to read sql data for tag: ", |
| 465 | stringify!($tag_name), |
| 466 | "." |
| 467 | ))? |
| 468 | )))? |
| 469 | }, |
| 470 | )* |
| 471 | _ => $enum_name::Invalid, |
| 472 | }) |
| 473 | } |
| 474 | }; |
| 475 | } |
| 476 | |
| 477 | /// This key parameter default is used during the conversion from KeyParameterValue |
| 478 | /// to keymint::KeyParameterValue. Keystore's version does not have wrapped types |
| 479 | /// for boolean tags and the tag Invalid. The AIDL version uses bool and integer |
| 480 | /// variants respectively. This default function is invoked in these cases to |
| 481 | /// homogenize the rules for boolean and invalid tags. |
| 482 | /// The bool variant returns true because boolean parameters are implicitly true |
| 483 | /// if present. |
| 484 | trait KpDefault { |
| 485 | fn default() -> Self; |
| 486 | } |
| 487 | |
| 488 | impl KpDefault for i32 { |
| 489 | fn default() -> Self { |
| 490 | 0 |
| 491 | } |
| 492 | } |
| 493 | |
| 494 | impl KpDefault for bool { |
| 495 | fn default() -> Self { |
| 496 | true |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | /// Expands the list of KeyParameterValue variants as follows: |
| 501 | /// |
| 502 | /// Input: |
| 503 | /// Invalid with tag INVALID and field Invalid, |
| 504 | /// Algorithm(Algorithm) with tag ALGORITHM and field Algorithm, |
| 505 | /// |
| 506 | /// Output: |
| 507 | /// ``` |
| 508 | /// impl From<KmKeyParameter> for KeyParameterValue { |
| 509 | /// fn from(kp: KmKeyParameter) -> Self { |
| 510 | /// match kp { |
| 511 | /// KmKeyParameter { tag: Tag::INVALID, value: KmKeyParameterValue::Invalid(_) } |
| 512 | /// => $enum_name::$vname, |
| 513 | /// KmKeyParameter { tag: Tag::Algorithm, value: KmKeyParameterValue::Algorithm(v) } |
| 514 | /// => $enum_name::Algorithm(v), |
| 515 | /// _ => $enum_name::Invalid, |
| 516 | /// } |
| 517 | /// } |
| 518 | /// } |
| 519 | /// |
| 520 | /// impl Into<KmKeyParameter> for KeyParameterValue { |
| 521 | /// fn into(self) -> KmKeyParameter { |
| 522 | /// match self { |
| 523 | /// KeyParameterValue::Invalid => KmKeyParameter { |
| 524 | /// tag: Tag::INVALID, |
| 525 | /// value: KmKeyParameterValue::Invalid(KpDefault::default()) |
| 526 | /// }, |
| 527 | /// KeyParameterValue::Algorithm(v) => KmKeyParameter { |
| 528 | /// tag: Tag::ALGORITHM, |
| 529 | /// value: KmKeyParameterValue::Algorithm(v) |
| 530 | /// }, |
| 531 | /// } |
| 532 | /// } |
| 533 | /// } |
| 534 | /// ``` |
| 535 | macro_rules! implement_try_from_to_km_parameter { |
| 536 | // The first three rules expand From<KmKeyParameter>. |
| 537 | ( |
| 538 | @from |
| 539 | $enum_name:ident, |
| 540 | [$($out:tt)*], |
| 541 | [$vname:ident($vtype:ty) $tag_name:ident $field_name:ident, $($in:tt)*] |
| 542 | ) => { |
| 543 | implement_try_from_to_km_parameter!{@from $enum_name, [$($out)* |
| 544 | KmKeyParameter { |
| 545 | tag: Tag::$tag_name, |
| 546 | value: KmKeyParameterValue::$field_name(v) |
| 547 | } => $enum_name::$vname(v), |
| 548 | ], [$($in)*] |
| 549 | }}; |
| 550 | ( |
| 551 | @from |
| 552 | $enum_name:ident, |
| 553 | [$($out:tt)*], |
| 554 | [$vname:ident $tag_name:ident $field_name:ident, $($in:tt)*] |
| 555 | ) => { |
| 556 | implement_try_from_to_km_parameter!{@from $enum_name, [$($out)* |
| 557 | KmKeyParameter { |
| 558 | tag: Tag::$tag_name, |
| 559 | value: KmKeyParameterValue::$field_name(_) |
| 560 | } => $enum_name::$vname, |
| 561 | ], [$($in)*] |
| 562 | }}; |
| 563 | (@from $enum_name:ident, [$($out:tt)*], []) => { |
| 564 | impl From<KmKeyParameter> for $enum_name { |
| 565 | fn from(kp: KmKeyParameter) -> Self { |
| 566 | match kp { |
| 567 | $($out)* |
| 568 | _ => $enum_name::Invalid, |
| 569 | } |
| 570 | } |
| 571 | } |
| 572 | }; |
| 573 | |
| 574 | // The next three rules expand Into<KmKeyParameter>. |
| 575 | ( |
| 576 | @into |
| 577 | $enum_name:ident, |
| 578 | [$($out:tt)*], |
| 579 | [$vname:ident($vtype:ty) $tag_name:ident $field_name:ident, $($in:tt)*] |
| 580 | ) => { |
| 581 | implement_try_from_to_km_parameter!{@into $enum_name, [$($out)* |
| 582 | $enum_name::$vname(v) => KmKeyParameter { |
| 583 | tag: Tag::$tag_name, |
| 584 | value: KmKeyParameterValue::$field_name(v) |
| 585 | }, |
| 586 | ], [$($in)*] |
| 587 | }}; |
| 588 | ( |
| 589 | @into |
| 590 | $enum_name:ident, |
| 591 | [$($out:tt)*], |
| 592 | [$vname:ident $tag_name:ident $field_name:ident, $($in:tt)*] |
| 593 | ) => { |
| 594 | implement_try_from_to_km_parameter!{@into $enum_name, [$($out)* |
| 595 | $enum_name::$vname => KmKeyParameter { |
| 596 | tag: Tag::$tag_name, |
| 597 | value: KmKeyParameterValue::$field_name(KpDefault::default()) |
| 598 | }, |
| 599 | ], [$($in)*] |
| 600 | }}; |
| 601 | (@into $enum_name:ident, [$($out:tt)*], []) => { |
| 602 | impl Into<KmKeyParameter> for $enum_name { |
| 603 | fn into(self) -> KmKeyParameter { |
| 604 | match self { |
| 605 | $($out)* |
| 606 | } |
| 607 | } |
| 608 | } |
| 609 | }; |
| 610 | |
| 611 | |
| 612 | ($enum_name:ident; $($vname:ident$(($vtype:ty))? $tag_name:ident $field_name:ident),*) => { |
| 613 | implement_try_from_to_km_parameter!( |
| 614 | @from $enum_name, |
| 615 | [], |
| 616 | [$($vname$(($vtype))? $tag_name $field_name,)*] |
| 617 | ); |
| 618 | implement_try_from_to_km_parameter!( |
| 619 | @into $enum_name, |
| 620 | [], |
| 621 | [$($vname$(($vtype))? $tag_name $field_name,)*] |
| 622 | ); |
| 623 | }; |
| 624 | } |
| 625 | |
| 626 | /// This is the top level macro. While the other macros do most of the heavy lifting, this takes |
| 627 | /// the key parameter list and passes it on to the other macros to generate all of the conversion |
| 628 | /// functions. In addition, it generates an important test vector for verifying that tag type of the |
| 629 | /// keymint tag matches the associated keymint KeyParameterValue field. |
| 630 | macro_rules! implement_key_parameter_value { |
| 631 | ( |
| 632 | $(#[$enum_meta:meta])* |
| 633 | $enum_vis:vis enum $enum_name:ident { |
| 634 | $( |
| 635 | $(#[$emeta:meta])* |
| 636 | $vname:ident$(($vtype:ty))? with tag $tag_name:ident and field $field_name:ident |
| 637 | ),* $(,)? |
| 638 | } |
| 639 | ) => { |
| 640 | implement_enum!( |
| 641 | $(#[$enum_meta])* |
| 642 | $enum_vis enum $enum_name { |
| 643 | $( |
| 644 | $(#[$emeta])* |
| 645 | $vname$(($vtype))? |
| 646 | ),* |
| 647 | }); |
| 648 | |
| 649 | impl $enum_name { |
| 650 | implement_new_from_sql!($enum_name; $($vname$(($vtype))? $tag_name),*); |
| 651 | implement_get_tag!($enum_name; $($vname$(($vtype))? $tag_name),*); |
Janis Danisevskis | 6b00e25 | 2020-12-22 11:36:45 -0800 | [diff] [blame^] | 652 | implement_from_tag_primitive_pair!($enum_name; $($vname$(($vtype))? $tag_name),*); |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 653 | |
| 654 | #[cfg(test)] |
| 655 | fn make_field_matches_tag_type_test_vector() -> Vec<KmKeyParameter> { |
| 656 | vec![$(KmKeyParameter{ |
| 657 | tag: Tag::$tag_name, |
| 658 | value: KmKeyParameterValue::$field_name(Default::default())} |
| 659 | ),*] |
| 660 | } |
| 661 | } |
| 662 | |
| 663 | implement_try_from_to_km_parameter!( |
| 664 | $enum_name; |
| 665 | $($vname$(($vtype))? $tag_name $field_name),* |
| 666 | ); |
| 667 | |
| 668 | implement_to_sql!($enum_name; $($vname$(($vtype))?),*); |
| 669 | }; |
| 670 | } |
| 671 | |
| 672 | implement_key_parameter_value! { |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 673 | /// KeyParameterValue holds a value corresponding to one of the Tags defined in |
| 674 | /// the AIDL spec at hardware/interfaces/keymint |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 675 | #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)] |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 676 | pub enum KeyParameterValue { |
| 677 | /// Associated with Tag:INVALID |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 678 | Invalid with tag INVALID and field Invalid, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 679 | /// Set of purposes for which the key may be used |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 680 | KeyPurpose(KeyPurpose) with tag PURPOSE and field KeyPurpose, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 681 | /// Cryptographic algorithm with which the key is used |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 682 | Algorithm(Algorithm) with tag ALGORITHM and field Algorithm, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 683 | /// Size of the key , in bits |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 684 | KeySize(i32) with tag KEY_SIZE and field Integer, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 685 | /// Block cipher mode(s) with which the key may be used |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 686 | BlockMode(BlockMode) with tag BLOCK_MODE and field BlockMode, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 687 | /// Digest algorithms that may be used with the key to perform signing and verification |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 688 | Digest(Digest) with tag DIGEST and field Digest, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 689 | /// Padding modes that may be used with the key. Relevant to RSA, AES and 3DES keys. |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 690 | PaddingMode(PaddingMode) with tag PADDING and field PaddingMode, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 691 | /// Can the caller provide a nonce for nonce-requiring operations |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 692 | CallerNonce with tag CALLER_NONCE and field BoolValue, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 693 | /// Minimum length of MAC for HMAC keys and AES keys that support GCM mode |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 694 | MinMacLength(i32) with tag MIN_MAC_LENGTH and field Integer, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 695 | /// The elliptic curve |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 696 | EcCurve(EcCurve) with tag EC_CURVE and field EcCurve, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 697 | /// Value of the public exponent for an RSA key pair |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 698 | RSAPublicExponent(i64) with tag RSA_PUBLIC_EXPONENT and field LongInteger, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 699 | /// An attestation certificate for the generated key should contain an application-scoped |
| 700 | /// and time-bounded device-unique ID |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 701 | IncludeUniqueID with tag INCLUDE_UNIQUE_ID and field BoolValue, |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 702 | //TODO: find out about this |
| 703 | // /// Necessary system environment conditions for the generated key to be used |
| 704 | // KeyBlobUsageRequirements(KeyBlobUsageRequirements), |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 705 | /// Only the boot loader can use the key |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 706 | BootLoaderOnly with tag BOOTLOADER_ONLY and field BoolValue, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 707 | /// When deleted, the key is guaranteed to be permanently deleted and unusable |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 708 | RollbackResistance with tag ROLLBACK_RESISTANCE and field BoolValue, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 709 | /// The date and time at which the key becomes active |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 710 | ActiveDateTime(i64) with tag ACTIVE_DATETIME and field DateTime, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 711 | /// The date and time at which the key expires for signing and encryption |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 712 | OriginationExpireDateTime(i64) with tag ORIGINATION_EXPIRE_DATETIME and field DateTime, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 713 | /// The date and time at which the key expires for verification and decryption |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 714 | UsageExpireDateTime(i64) with tag USAGE_EXPIRE_DATETIME and field DateTime, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 715 | /// Minimum amount of time that elapses between allowed operations |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 716 | MinSecondsBetweenOps(i32) with tag MIN_SECONDS_BETWEEN_OPS and field Integer, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 717 | /// Maximum number of times that a key may be used between system reboots |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 718 | MaxUsesPerBoot(i32) with tag MAX_USES_PER_BOOT and field Integer, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 719 | /// ID of the Android user that is permitted to use the key |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 720 | UserID(i32) with tag USER_ID and field Integer, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 721 | /// A key may only be used under a particular secure user authentication state |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 722 | UserSecureID(i64) with tag USER_SECURE_ID and field LongInteger, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 723 | /// No authentication is required to use this key |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 724 | NoAuthRequired with tag NO_AUTH_REQUIRED and field BoolValue, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 725 | /// The types of user authenticators that may be used to authorize this key |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 726 | HardwareAuthenticatorType(HardwareAuthenticatorType) with tag USER_AUTH_TYPE and field HardwareAuthenticatorType, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 727 | /// The time in seconds for which the key is authorized for use, after user authentication |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 728 | AuthTimeout(i32) with tag AUTH_TIMEOUT and field Integer, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 729 | /// The key may be used after authentication timeout if device is still on-body |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 730 | AllowWhileOnBody with tag ALLOW_WHILE_ON_BODY and field BoolValue, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 731 | /// The key must be unusable except when the user has provided proof of physical presence |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 732 | TrustedUserPresenceRequired with tag TRUSTED_USER_PRESENCE_REQUIRED and field BoolValue, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 733 | /// Applicable to keys with KeyPurpose SIGN, and specifies that this key must not be usable |
| 734 | /// unless the user provides confirmation of the data to be signed |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 735 | TrustedConfirmationRequired with tag TRUSTED_CONFIRMATION_REQUIRED and field BoolValue, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 736 | /// The key may only be used when the device is unlocked |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 737 | UnlockedDeviceRequired with tag UNLOCKED_DEVICE_REQUIRED and field BoolValue, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 738 | /// When provided to generateKey or importKey, this tag specifies data |
| 739 | /// that is necessary during all uses of the key |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 740 | ApplicationID(Vec<u8>) with tag APPLICATION_ID and field Blob, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 741 | /// When provided to generateKey or importKey, this tag specifies data |
| 742 | /// that is necessary during all uses of the key |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 743 | ApplicationData(Vec<u8>) with tag APPLICATION_DATA and field Blob, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 744 | /// Specifies the date and time the key was created |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 745 | CreationDateTime(i64) with tag CREATION_DATETIME and field DateTime, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 746 | /// Specifies where the key was created, if known |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 747 | KeyOrigin(KeyOrigin) with tag ORIGIN and field Origin, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 748 | /// The key used by verified boot to validate the operating system booted |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 749 | RootOfTrust(Vec<u8>) with tag ROOT_OF_TRUST and field Blob, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 750 | /// System OS version with which the key may be used |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 751 | OSVersion(i32) with tag OS_VERSION and field Integer, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 752 | /// Specifies the system security patch level with which the key may be used |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 753 | OSPatchLevel(i32) with tag OS_PATCHLEVEL and field Integer, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 754 | /// Specifies a unique, time-based identifier |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 755 | UniqueID(Vec<u8>) with tag UNIQUE_ID and field Blob, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 756 | /// Used to deliver a "challenge" value to the attestKey() method |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 757 | AttestationChallenge(Vec<u8>) with tag ATTESTATION_CHALLENGE and field Blob, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 758 | /// The set of applications which may use a key, used only with attestKey() |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 759 | AttestationApplicationID(Vec<u8>) with tag ATTESTATION_APPLICATION_ID and field Blob, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 760 | /// Provides the device's brand name, to attestKey() |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 761 | AttestationIdBrand(Vec<u8>) with tag ATTESTATION_ID_BRAND and field Blob, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 762 | /// Provides the device's device name, to attestKey() |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 763 | AttestationIdDevice(Vec<u8>) with tag ATTESTATION_ID_DEVICE and field Blob, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 764 | /// Provides the device's product name, to attestKey() |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 765 | AttestationIdProduct(Vec<u8>) with tag ATTESTATION_ID_PRODUCT and field Blob, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 766 | /// Provides the device's serial number, to attestKey() |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 767 | AttestationIdSerial(Vec<u8>) with tag ATTESTATION_ID_SERIAL and field Blob, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 768 | /// Provides the IMEIs for all radios on the device, to attestKey() |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 769 | AttestationIdIMEI(Vec<u8>) with tag ATTESTATION_ID_IMEI and field Blob, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 770 | /// Provides the MEIDs for all radios on the device, to attestKey() |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 771 | AttestationIdMEID(Vec<u8>) with tag ATTESTATION_ID_MEID and field Blob, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 772 | /// Provides the device's manufacturer name, to attestKey() |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 773 | AttestationIdManufacturer(Vec<u8>) with tag ATTESTATION_ID_MANUFACTURER and field Blob, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 774 | /// Provides the device's model name, to attestKey() |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 775 | AttestationIdModel(Vec<u8>) with tag ATTESTATION_ID_MODEL and field Blob, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 776 | /// Specifies the vendor image security patch level with which the key may be used |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 777 | VendorPatchLevel(i32) with tag VENDOR_PATCHLEVEL and field Integer, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 778 | /// Specifies the boot image (kernel) security patch level with which the key may be used |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 779 | BootPatchLevel(i32) with tag BOOT_PATCHLEVEL and field Integer, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 780 | /// Provides "associated data" for AES-GCM encryption or decryption |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 781 | AssociatedData(Vec<u8>) with tag ASSOCIATED_DATA and field Blob, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 782 | /// Provides or returns a nonce or Initialization Vector (IV) for AES-GCM, |
| 783 | /// AES-CBC, AES-CTR, or 3DES-CBC encryption or decryption |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 784 | Nonce(Vec<u8>) with tag NONCE and field Blob, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 785 | /// Provides the requested length of a MAC or GCM authentication tag, in bits |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 786 | MacLength(i32) with tag MAC_LENGTH and field Integer, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 787 | /// Specifies whether the device has been factory reset since the |
| 788 | /// last unique ID rotation. Used for key attestation |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 789 | ResetSinceIdRotation with tag RESET_SINCE_ID_ROTATION and field BoolValue, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 790 | /// Used to deliver a cryptographic token proving that the user |
| 791 | /// confirmed a signing request |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 792 | ConfirmationToken(Vec<u8>) with tag CONFIRMATION_TOKEN and field Blob, |
| 793 | } |
| 794 | } |
| 795 | |
| 796 | impl From<&KmKeyParameter> for KeyParameterValue { |
| 797 | fn from(kp: &KmKeyParameter) -> Self { |
| 798 | kp.clone().into() |
| 799 | } |
| 800 | } |
| 801 | |
| 802 | /// KeyParameter wraps the KeyParameterValue and the security level at which it is enforced. |
| 803 | #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)] |
| 804 | pub struct KeyParameter { |
| 805 | value: KeyParameterValue, |
| 806 | security_level: SecurityLevel, |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 807 | } |
| 808 | |
| 809 | impl KeyParameter { |
| 810 | /// Create an instance of KeyParameter, given the value and the security level. |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 811 | pub fn new(value: KeyParameterValue, security_level: SecurityLevel) -> Self { |
| 812 | KeyParameter { value, security_level } |
Hasini Gunasinghe | 1248636 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 813 | } |
| 814 | |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 815 | /// Construct a KeyParameter from the data from a rusqlite row. |
| 816 | /// Note that following variants of KeyParameterValue should not be stored: |
| 817 | /// IncludeUniqueID, ApplicationID, ApplicationData, RootOfTrust, UniqueID, |
| 818 | /// Attestation*, AssociatedData, Nonce, MacLength, ResetSinceIdRotation, ConfirmationToken. |
| 819 | /// This filtering is enforced at a higher level and here we support conversion for all the |
| 820 | /// variants. |
| 821 | pub fn new_from_sql( |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 822 | tag_val: Tag, |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 823 | data: &SqlField, |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 824 | security_level_val: SecurityLevel, |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 825 | ) -> Result<Self> { |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 826 | Ok(Self { |
| 827 | value: KeyParameterValue::new_from_sql(tag_val, data)?, |
| 828 | security_level: security_level_val, |
| 829 | }) |
| 830 | } |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 831 | |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 832 | /// Get the KeyMint Tag of this this key parameter. |
| 833 | pub fn get_tag(&self) -> Tag { |
| 834 | self.value.get_tag() |
| 835 | } |
| 836 | |
| 837 | /// Returns key parameter value. |
| 838 | pub fn key_parameter_value(&self) -> &KeyParameterValue { |
| 839 | &self.value |
| 840 | } |
| 841 | |
| 842 | /// Returns the security level of this key parameter. |
| 843 | pub fn security_level(&self) -> &SecurityLevel { |
| 844 | &self.security_level |
| 845 | } |
| 846 | |
| 847 | /// An authorization is a KeyParameter with an associated security level that is used |
| 848 | /// to convey the key characteristics to keystore clients. This function consumes |
| 849 | /// an internal KeyParameter representation to produce the Authorization wire type. |
| 850 | pub fn into_authorization(self) -> Authorization { |
| 851 | Authorization { securityLevel: self.security_level, keyParameter: self.value.into() } |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 852 | } |
| 853 | } |
| 854 | |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 855 | #[cfg(test)] |
| 856 | mod generated_key_parameter_tests { |
| 857 | use super::*; |
| 858 | use android_hardware_security_keymint::aidl::android::hardware::security::keymint::TagType::TagType; |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 859 | |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 860 | fn get_field_by_tag_type(tag: Tag) -> KmKeyParameterValue { |
| 861 | let tag_type = TagType((tag.0 as u32 & 0xF0000000) as i32); |
| 862 | match tag { |
| 863 | Tag::ALGORITHM => return KmKeyParameterValue::Algorithm(Default::default()), |
| 864 | Tag::BLOCK_MODE => return KmKeyParameterValue::BlockMode(Default::default()), |
| 865 | Tag::PADDING => return KmKeyParameterValue::PaddingMode(Default::default()), |
| 866 | Tag::DIGEST => return KmKeyParameterValue::Digest(Default::default()), |
| 867 | Tag::EC_CURVE => return KmKeyParameterValue::EcCurve(Default::default()), |
| 868 | Tag::ORIGIN => return KmKeyParameterValue::Origin(Default::default()), |
| 869 | Tag::PURPOSE => return KmKeyParameterValue::KeyPurpose(Default::default()), |
| 870 | Tag::USER_AUTH_TYPE => { |
| 871 | return KmKeyParameterValue::HardwareAuthenticatorType(Default::default()) |
| 872 | } |
| 873 | Tag::HARDWARE_TYPE => return KmKeyParameterValue::SecurityLevel(Default::default()), |
| 874 | _ => {} |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 875 | } |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 876 | match tag_type { |
| 877 | TagType::INVALID => return KmKeyParameterValue::Invalid(Default::default()), |
| 878 | TagType::ENUM | TagType::ENUM_REP => {} |
| 879 | TagType::UINT | TagType::UINT_REP => { |
| 880 | return KmKeyParameterValue::Integer(Default::default()) |
| 881 | } |
| 882 | TagType::ULONG | TagType::ULONG_REP => { |
| 883 | return KmKeyParameterValue::LongInteger(Default::default()) |
| 884 | } |
| 885 | TagType::DATE => return KmKeyParameterValue::DateTime(Default::default()), |
| 886 | TagType::BOOL => return KmKeyParameterValue::BoolValue(Default::default()), |
| 887 | TagType::BIGNUM | TagType::BYTES => { |
| 888 | return KmKeyParameterValue::Blob(Default::default()) |
| 889 | } |
| 890 | _ => {} |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 891 | } |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 892 | panic!("Unknown tag/tag_type: {:?} {:?}", tag, tag_type); |
| 893 | } |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 894 | |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 895 | fn check_field_matches_tag_type(list_o_parameters: &[KmKeyParameter]) { |
| 896 | for kp in list_o_parameters.iter() { |
| 897 | match (&kp.value, get_field_by_tag_type(kp.tag)) { |
| 898 | (&KmKeyParameterValue::Algorithm(_), KmKeyParameterValue::Algorithm(_)) |
| 899 | | (&KmKeyParameterValue::BlockMode(_), KmKeyParameterValue::BlockMode(_)) |
| 900 | | (&KmKeyParameterValue::PaddingMode(_), KmKeyParameterValue::PaddingMode(_)) |
| 901 | | (&KmKeyParameterValue::Digest(_), KmKeyParameterValue::Digest(_)) |
| 902 | | (&KmKeyParameterValue::EcCurve(_), KmKeyParameterValue::EcCurve(_)) |
| 903 | | (&KmKeyParameterValue::Origin(_), KmKeyParameterValue::Origin(_)) |
| 904 | | (&KmKeyParameterValue::KeyPurpose(_), KmKeyParameterValue::KeyPurpose(_)) |
| 905 | | ( |
| 906 | &KmKeyParameterValue::HardwareAuthenticatorType(_), |
| 907 | KmKeyParameterValue::HardwareAuthenticatorType(_), |
| 908 | ) |
| 909 | | (&KmKeyParameterValue::SecurityLevel(_), KmKeyParameterValue::SecurityLevel(_)) |
| 910 | | (&KmKeyParameterValue::Invalid(_), KmKeyParameterValue::Invalid(_)) |
| 911 | | (&KmKeyParameterValue::Integer(_), KmKeyParameterValue::Integer(_)) |
| 912 | | (&KmKeyParameterValue::LongInteger(_), KmKeyParameterValue::LongInteger(_)) |
| 913 | | (&KmKeyParameterValue::DateTime(_), KmKeyParameterValue::DateTime(_)) |
| 914 | | (&KmKeyParameterValue::BoolValue(_), KmKeyParameterValue::BoolValue(_)) |
| 915 | | (&KmKeyParameterValue::Blob(_), KmKeyParameterValue::Blob(_)) => {} |
| 916 | (actual, expected) => panic!( |
| 917 | "Tag {:?} associated with variant {:?} expected {:?}", |
| 918 | kp.tag, actual, expected |
| 919 | ), |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 920 | } |
| 921 | } |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 922 | } |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 923 | |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 924 | #[test] |
| 925 | fn key_parameter_value_field_matches_tag_type() { |
| 926 | check_field_matches_tag_type(&KeyParameterValue::make_field_matches_tag_type_test_vector()); |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 927 | } |
| 928 | } |
| 929 | |
| 930 | #[cfg(test)] |
| 931 | mod basic_tests { |
| 932 | use crate::key_parameter::*; |
| 933 | |
| 934 | // Test basic functionality of KeyParameter. |
| 935 | #[test] |
| 936 | fn test_key_parameter() { |
| 937 | let key_parameter = KeyParameter::new( |
| 938 | KeyParameterValue::Algorithm(Algorithm::RSA), |
| 939 | SecurityLevel::STRONGBOX, |
| 940 | ); |
| 941 | |
| 942 | assert_eq!(key_parameter.get_tag(), Tag::ALGORITHM); |
| 943 | |
| 944 | assert_eq!( |
| 945 | *key_parameter.key_parameter_value(), |
| 946 | KeyParameterValue::Algorithm(Algorithm::RSA) |
| 947 | ); |
| 948 | |
| 949 | assert_eq!(*key_parameter.security_level(), SecurityLevel::STRONGBOX); |
| 950 | } |
| 951 | } |
| 952 | |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 953 | /// The storage_tests module first tests the 'new_from_sql' method for KeyParameters of different |
| 954 | /// data types and then tests 'to_sql' method for KeyParameters of those |
| 955 | /// different data types. The five different data types for KeyParameter values are: |
| 956 | /// i) enums of u32 |
| 957 | /// ii) u32 |
| 958 | /// iii) u64 |
| 959 | /// iv) Vec<u8> |
| 960 | /// v) bool |
| 961 | #[cfg(test)] |
| 962 | mod storage_tests { |
| 963 | use crate::error::*; |
| 964 | use crate::key_parameter::*; |
| 965 | use anyhow::Result; |
| 966 | use rusqlite::types::ToSql; |
| 967 | use rusqlite::{params, Connection, NO_PARAMS}; |
| 968 | |
| 969 | /// Test initializing a KeyParameter (with key parameter value corresponding to an enum of i32) |
| 970 | /// from a database table row. |
| 971 | #[test] |
| 972 | fn test_new_from_sql_enum_i32() -> Result<()> { |
| 973 | let db = init_db()?; |
| 974 | insert_into_keyparameter( |
| 975 | &db, |
| 976 | 1, |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 977 | Tag::ALGORITHM.0, |
| 978 | &Algorithm::RSA.0, |
| 979 | SecurityLevel::STRONGBOX.0, |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 980 | )?; |
| 981 | let key_param = query_from_keyparameter(&db)?; |
| 982 | assert_eq!(Tag::ALGORITHM, key_param.get_tag()); |
| 983 | assert_eq!(*key_param.key_parameter_value(), KeyParameterValue::Algorithm(Algorithm::RSA)); |
| 984 | assert_eq!(*key_param.security_level(), SecurityLevel::STRONGBOX); |
| 985 | Ok(()) |
| 986 | } |
| 987 | |
| 988 | /// Test initializing a KeyParameter (with key parameter value which is of i32) |
| 989 | /// from a database table row. |
| 990 | #[test] |
| 991 | fn test_new_from_sql_i32() -> Result<()> { |
| 992 | let db = init_db()?; |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 993 | insert_into_keyparameter(&db, 1, Tag::KEY_SIZE.0, &1024, SecurityLevel::STRONGBOX.0)?; |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 994 | let key_param = query_from_keyparameter(&db)?; |
| 995 | assert_eq!(Tag::KEY_SIZE, key_param.get_tag()); |
| 996 | assert_eq!(*key_param.key_parameter_value(), KeyParameterValue::KeySize(1024)); |
| 997 | Ok(()) |
| 998 | } |
| 999 | |
| 1000 | /// Test initializing a KeyParameter (with key parameter value which is of i64) |
| 1001 | /// from a database table row. |
| 1002 | #[test] |
| 1003 | fn test_new_from_sql_i64() -> Result<()> { |
| 1004 | let db = init_db()?; |
| 1005 | // max value for i64, just to test corner cases |
| 1006 | insert_into_keyparameter( |
| 1007 | &db, |
| 1008 | 1, |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1009 | Tag::RSA_PUBLIC_EXPONENT.0, |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 1010 | &(i64::MAX), |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1011 | SecurityLevel::STRONGBOX.0, |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 1012 | )?; |
| 1013 | let key_param = query_from_keyparameter(&db)?; |
| 1014 | assert_eq!(Tag::RSA_PUBLIC_EXPONENT, key_param.get_tag()); |
| 1015 | assert_eq!( |
| 1016 | *key_param.key_parameter_value(), |
| 1017 | KeyParameterValue::RSAPublicExponent(i64::MAX) |
| 1018 | ); |
| 1019 | Ok(()) |
| 1020 | } |
| 1021 | |
| 1022 | /// Test initializing a KeyParameter (with key parameter value which is of bool) |
| 1023 | /// from a database table row. |
| 1024 | #[test] |
| 1025 | fn test_new_from_sql_bool() -> Result<()> { |
| 1026 | let db = init_db()?; |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1027 | insert_into_keyparameter(&db, 1, Tag::CALLER_NONCE.0, &Null, SecurityLevel::STRONGBOX.0)?; |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 1028 | let key_param = query_from_keyparameter(&db)?; |
| 1029 | assert_eq!(Tag::CALLER_NONCE, key_param.get_tag()); |
| 1030 | assert_eq!(*key_param.key_parameter_value(), KeyParameterValue::CallerNonce); |
| 1031 | Ok(()) |
| 1032 | } |
| 1033 | |
| 1034 | /// Test initializing a KeyParameter (with key parameter value which is of Vec<u8>) |
| 1035 | /// from a database table row. |
| 1036 | #[test] |
| 1037 | fn test_new_from_sql_vec_u8() -> Result<()> { |
| 1038 | let db = init_db()?; |
| 1039 | let app_id = String::from("MyAppID"); |
| 1040 | let app_id_bytes = app_id.into_bytes(); |
| 1041 | insert_into_keyparameter( |
| 1042 | &db, |
| 1043 | 1, |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1044 | Tag::APPLICATION_ID.0, |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 1045 | &app_id_bytes, |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1046 | SecurityLevel::STRONGBOX.0, |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 1047 | )?; |
| 1048 | let key_param = query_from_keyparameter(&db)?; |
| 1049 | assert_eq!(Tag::APPLICATION_ID, key_param.get_tag()); |
| 1050 | assert_eq!( |
| 1051 | *key_param.key_parameter_value(), |
| 1052 | KeyParameterValue::ApplicationID(app_id_bytes) |
| 1053 | ); |
| 1054 | Ok(()) |
| 1055 | } |
| 1056 | |
| 1057 | /// Test storing a KeyParameter (with key parameter value which corresponds to an enum of i32) |
| 1058 | /// in the database |
| 1059 | #[test] |
| 1060 | fn test_to_sql_enum_i32() -> Result<()> { |
| 1061 | let db = init_db()?; |
| 1062 | let kp = KeyParameter::new( |
| 1063 | KeyParameterValue::Algorithm(Algorithm::RSA), |
| 1064 | SecurityLevel::STRONGBOX, |
| 1065 | ); |
| 1066 | store_keyparameter(&db, 1, &kp)?; |
| 1067 | let key_param = query_from_keyparameter(&db)?; |
| 1068 | assert_eq!(kp.get_tag(), key_param.get_tag()); |
| 1069 | assert_eq!(kp.key_parameter_value(), key_param.key_parameter_value()); |
| 1070 | assert_eq!(kp.security_level(), key_param.security_level()); |
| 1071 | Ok(()) |
| 1072 | } |
| 1073 | |
| 1074 | /// Test storing a KeyParameter (with key parameter value which is of i32) in the database |
| 1075 | #[test] |
| 1076 | fn test_to_sql_i32() -> Result<()> { |
| 1077 | let db = init_db()?; |
| 1078 | let kp = KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::STRONGBOX); |
| 1079 | store_keyparameter(&db, 1, &kp)?; |
| 1080 | let key_param = query_from_keyparameter(&db)?; |
| 1081 | assert_eq!(kp.get_tag(), key_param.get_tag()); |
| 1082 | assert_eq!(kp.key_parameter_value(), key_param.key_parameter_value()); |
| 1083 | assert_eq!(kp.security_level(), key_param.security_level()); |
| 1084 | Ok(()) |
| 1085 | } |
| 1086 | |
| 1087 | /// Test storing a KeyParameter (with key parameter value which is of i64) in the database |
| 1088 | #[test] |
| 1089 | fn test_to_sql_i64() -> Result<()> { |
| 1090 | let db = init_db()?; |
| 1091 | // max value for i64, just to test corner cases |
| 1092 | let kp = KeyParameter::new( |
| 1093 | KeyParameterValue::RSAPublicExponent(i64::MAX), |
| 1094 | SecurityLevel::STRONGBOX, |
| 1095 | ); |
| 1096 | store_keyparameter(&db, 1, &kp)?; |
| 1097 | let key_param = query_from_keyparameter(&db)?; |
| 1098 | assert_eq!(kp.get_tag(), key_param.get_tag()); |
| 1099 | assert_eq!(kp.key_parameter_value(), key_param.key_parameter_value()); |
| 1100 | assert_eq!(kp.security_level(), key_param.security_level()); |
| 1101 | Ok(()) |
| 1102 | } |
| 1103 | |
| 1104 | /// Test storing a KeyParameter (with key parameter value which is of Vec<u8>) in the database |
| 1105 | #[test] |
| 1106 | fn test_to_sql_vec_u8() -> Result<()> { |
| 1107 | let db = init_db()?; |
| 1108 | let kp = KeyParameter::new( |
| 1109 | KeyParameterValue::ApplicationID(String::from("MyAppID").into_bytes()), |
| 1110 | SecurityLevel::STRONGBOX, |
| 1111 | ); |
| 1112 | store_keyparameter(&db, 1, &kp)?; |
| 1113 | let key_param = query_from_keyparameter(&db)?; |
| 1114 | assert_eq!(kp.get_tag(), key_param.get_tag()); |
| 1115 | assert_eq!(kp.key_parameter_value(), key_param.key_parameter_value()); |
| 1116 | assert_eq!(kp.security_level(), key_param.security_level()); |
| 1117 | Ok(()) |
| 1118 | } |
| 1119 | |
| 1120 | /// Test storing a KeyParameter (with key parameter value which is of i32) in the database |
| 1121 | #[test] |
| 1122 | fn test_to_sql_bool() -> Result<()> { |
| 1123 | let db = init_db()?; |
| 1124 | let kp = KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::STRONGBOX); |
| 1125 | store_keyparameter(&db, 1, &kp)?; |
| 1126 | let key_param = query_from_keyparameter(&db)?; |
| 1127 | assert_eq!(kp.get_tag(), key_param.get_tag()); |
| 1128 | assert_eq!(kp.key_parameter_value(), key_param.key_parameter_value()); |
| 1129 | assert_eq!(kp.security_level(), key_param.security_level()); |
| 1130 | Ok(()) |
| 1131 | } |
| 1132 | |
| 1133 | #[test] |
| 1134 | /// Test Tag::Invalid |
| 1135 | fn test_invalid_tag() -> Result<()> { |
| 1136 | let db = init_db()?; |
| 1137 | insert_into_keyparameter(&db, 1, 0, &123, 1)?; |
| 1138 | let key_param = query_from_keyparameter(&db)?; |
| 1139 | assert_eq!(Tag::INVALID, key_param.get_tag()); |
| 1140 | Ok(()) |
| 1141 | } |
| 1142 | |
| 1143 | #[test] |
| 1144 | fn test_non_existing_enum_variant() -> Result<()> { |
| 1145 | let db = init_db()?; |
| 1146 | insert_into_keyparameter(&db, 1, 100, &123, 1)?; |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 1147 | let key_param = query_from_keyparameter(&db)?; |
| 1148 | assert_eq!(Tag::INVALID, key_param.get_tag()); |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 1149 | Ok(()) |
| 1150 | } |
| 1151 | |
| 1152 | #[test] |
| 1153 | fn test_invalid_conversion_from_sql() -> Result<()> { |
| 1154 | let db = init_db()?; |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1155 | insert_into_keyparameter(&db, 1, Tag::ALGORITHM.0, &Null, 1)?; |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 1156 | tests::check_result_contains_error_string( |
| 1157 | query_from_keyparameter(&db), |
| 1158 | "Failed to read sql data for tag: ALGORITHM.", |
| 1159 | ); |
| 1160 | Ok(()) |
| 1161 | } |
| 1162 | |
| 1163 | /// Helper method to init database table for key parameter |
| 1164 | fn init_db() -> Result<Connection> { |
| 1165 | let db = Connection::open_in_memory().context("Failed to initialize sqlite connection.")?; |
| 1166 | db.execute("ATTACH DATABASE ? as 'persistent';", params![""]) |
| 1167 | .context("Failed to attach databases.")?; |
| 1168 | db.execute( |
| 1169 | "CREATE TABLE IF NOT EXISTS persistent.keyparameter ( |
| 1170 | keyentryid INTEGER, |
| 1171 | tag INTEGER, |
| 1172 | data ANY, |
| 1173 | security_level INTEGER);", |
| 1174 | NO_PARAMS, |
| 1175 | ) |
| 1176 | .context("Failed to initialize \"keyparameter\" table.")?; |
| 1177 | Ok(db) |
| 1178 | } |
| 1179 | |
| 1180 | /// Helper method to insert an entry into key parameter table, with individual parameters |
| 1181 | fn insert_into_keyparameter<T: ToSql>( |
| 1182 | db: &Connection, |
| 1183 | key_id: i64, |
| 1184 | tag: i32, |
| 1185 | value: &T, |
| 1186 | security_level: i32, |
| 1187 | ) -> Result<()> { |
| 1188 | db.execute( |
| 1189 | "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level) |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1190 | VALUES(?, ?, ?, ?);", |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 1191 | params![key_id, tag, *value, security_level], |
| 1192 | )?; |
| 1193 | Ok(()) |
| 1194 | } |
| 1195 | |
| 1196 | /// Helper method to store a key parameter instance. |
| 1197 | fn store_keyparameter(db: &Connection, key_id: i64, kp: &KeyParameter) -> Result<()> { |
| 1198 | db.execute( |
| 1199 | "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level) |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1200 | VALUES(?, ?, ?, ?);", |
| 1201 | params![key_id, kp.get_tag().0, kp.key_parameter_value(), kp.security_level().0], |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 1202 | )?; |
| 1203 | Ok(()) |
| 1204 | } |
| 1205 | |
| 1206 | /// Helper method to query a row from keyparameter table |
| 1207 | fn query_from_keyparameter(db: &Connection) -> Result<KeyParameter> { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1208 | let mut stmt = |
| 1209 | db.prepare("SELECT tag, data, security_level FROM persistent.keyparameter")?; |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 1210 | let mut rows = stmt.query(NO_PARAMS)?; |
| 1211 | let row = rows.next()?.unwrap(); |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1212 | Ok(KeyParameter::new_from_sql( |
| 1213 | Tag(row.get(0)?), |
Janis Danisevskis | 4522c2b | 2020-11-27 18:04:58 -0800 | [diff] [blame] | 1214 | &SqlField::new(1, row), |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1215 | SecurityLevel(row.get(2)?), |
| 1216 | )?) |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 1217 | } |
| 1218 | } |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1219 | |
| 1220 | /// The wire_tests module tests the 'convert_to_wire' and 'convert_from_wire' methods for |
Janis Danisevskis | 85d4793 | 2020-10-23 16:12:59 -0700 | [diff] [blame] | 1221 | /// KeyParameter, for the four different types used in KmKeyParameter, in addition to Invalid |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1222 | /// key parameter. |
| 1223 | /// i) bool |
| 1224 | /// ii) integer |
| 1225 | /// iii) longInteger |
Janis Danisevskis | 85d4793 | 2020-10-23 16:12:59 -0700 | [diff] [blame] | 1226 | /// iv) blob |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1227 | #[cfg(test)] |
| 1228 | mod wire_tests { |
| 1229 | use crate::key_parameter::*; |
| 1230 | /// unit tests for to conversions |
| 1231 | #[test] |
| 1232 | fn test_convert_to_wire_invalid() { |
| 1233 | let kp = KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::STRONGBOX); |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 1234 | assert_eq!( |
| 1235 | KmKeyParameter { tag: Tag::INVALID, value: KmKeyParameterValue::Invalid(0) }, |
| 1236 | kp.value.into() |
| 1237 | ); |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1238 | } |
| 1239 | #[test] |
| 1240 | fn test_convert_to_wire_bool() { |
| 1241 | let kp = KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::STRONGBOX); |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 1242 | assert_eq!( |
| 1243 | KmKeyParameter { tag: Tag::CALLER_NONCE, value: KmKeyParameterValue::BoolValue(true) }, |
| 1244 | kp.value.into() |
| 1245 | ); |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1246 | } |
| 1247 | #[test] |
| 1248 | fn test_convert_to_wire_integer() { |
| 1249 | let kp = KeyParameter::new( |
| 1250 | KeyParameterValue::KeyPurpose(KeyPurpose::ENCRYPT), |
| 1251 | SecurityLevel::STRONGBOX, |
| 1252 | ); |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 1253 | assert_eq!( |
| 1254 | KmKeyParameter { |
| 1255 | tag: Tag::PURPOSE, |
| 1256 | value: KmKeyParameterValue::KeyPurpose(KeyPurpose::ENCRYPT) |
| 1257 | }, |
| 1258 | kp.value.into() |
| 1259 | ); |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1260 | } |
| 1261 | #[test] |
| 1262 | fn test_convert_to_wire_long_integer() { |
| 1263 | let kp = |
| 1264 | KeyParameter::new(KeyParameterValue::UserSecureID(i64::MAX), SecurityLevel::STRONGBOX); |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 1265 | assert_eq!( |
| 1266 | KmKeyParameter { |
| 1267 | tag: Tag::USER_SECURE_ID, |
| 1268 | value: KmKeyParameterValue::LongInteger(i64::MAX) |
| 1269 | }, |
| 1270 | kp.value.into() |
| 1271 | ); |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1272 | } |
| 1273 | #[test] |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1274 | fn test_convert_to_wire_blob() { |
| 1275 | let kp = KeyParameter::new( |
| 1276 | KeyParameterValue::ConfirmationToken(String::from("ConfirmationToken").into_bytes()), |
| 1277 | SecurityLevel::STRONGBOX, |
| 1278 | ); |
Janis Danisevskis | 398e6be | 2020-12-17 09:29:25 -0800 | [diff] [blame] | 1279 | assert_eq!( |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 1280 | KmKeyParameter { |
| 1281 | tag: Tag::CONFIRMATION_TOKEN, |
| 1282 | value: KmKeyParameterValue::Blob(String::from("ConfirmationToken").into_bytes()) |
| 1283 | }, |
| 1284 | kp.value.into() |
Janis Danisevskis | 398e6be | 2020-12-17 09:29:25 -0800 | [diff] [blame] | 1285 | ); |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1286 | } |
| 1287 | |
| 1288 | /// unit tests for from conversion |
| 1289 | #[test] |
| 1290 | fn test_convert_from_wire_invalid() { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1291 | let aidl_kp = KmKeyParameter { tag: Tag::INVALID, ..Default::default() }; |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 1292 | assert_eq!(KeyParameterValue::Invalid, aidl_kp.into()); |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1293 | } |
| 1294 | #[test] |
| 1295 | fn test_convert_from_wire_bool() { |
| 1296 | let aidl_kp = |
Janis Danisevskis | 398e6be | 2020-12-17 09:29:25 -0800 | [diff] [blame] | 1297 | KmKeyParameter { tag: Tag::CALLER_NONCE, value: KmKeyParameterValue::BoolValue(true) }; |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 1298 | assert_eq!(KeyParameterValue::CallerNonce, aidl_kp.into()); |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1299 | } |
| 1300 | #[test] |
| 1301 | fn test_convert_from_wire_integer() { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1302 | let aidl_kp = KmKeyParameter { |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1303 | tag: Tag::PURPOSE, |
Janis Danisevskis | 398e6be | 2020-12-17 09:29:25 -0800 | [diff] [blame] | 1304 | value: KmKeyParameterValue::KeyPurpose(KeyPurpose::ENCRYPT), |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1305 | }; |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 1306 | assert_eq!(KeyParameterValue::KeyPurpose(KeyPurpose::ENCRYPT), aidl_kp.into()); |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1307 | } |
| 1308 | #[test] |
| 1309 | fn test_convert_from_wire_long_integer() { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1310 | let aidl_kp = KmKeyParameter { |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1311 | tag: Tag::USER_SECURE_ID, |
Janis Danisevskis | 398e6be | 2020-12-17 09:29:25 -0800 | [diff] [blame] | 1312 | value: KmKeyParameterValue::LongInteger(i64::MAX), |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1313 | }; |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 1314 | assert_eq!(KeyParameterValue::UserSecureID(i64::MAX), aidl_kp.into()); |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1315 | } |
| 1316 | #[test] |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1317 | fn test_convert_from_wire_blob() { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1318 | let aidl_kp = KmKeyParameter { |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1319 | tag: Tag::CONFIRMATION_TOKEN, |
Janis Danisevskis | 398e6be | 2020-12-17 09:29:25 -0800 | [diff] [blame] | 1320 | value: KmKeyParameterValue::Blob(String::from("ConfirmationToken").into_bytes()), |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1321 | }; |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1322 | assert_eq!( |
| 1323 | KeyParameterValue::ConfirmationToken(String::from("ConfirmationToken").into_bytes()), |
Janis Danisevskis | e6efb24 | 2020-12-19 13:58:01 -0800 | [diff] [blame] | 1324 | aidl_kp.into() |
Hasini Gunasinghe | 3eb77c2 | 2020-08-28 15:45:06 +0000 | [diff] [blame] | 1325 | ); |
| 1326 | } |
| 1327 | } |