blob: 549f57407630cf96e276f5d3c7acf85a5ed43ad0 [file] [log] [blame]
Hasini Gunasinghe12486362020-07-24 18:40:20 +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
Janis Danisevskise6efb242020-12-19 13:58:01 -080015//! 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 Danisevskis6b00e252020-12-22 11:36:45 -080035//! pub fn new_from_tag_primitive_pair<T: Into<Primitive>>(tag: Tag, v: T)
36//! -> Result<Self, PrimitiveError>;
Janis Danisevskise6efb242020-12-19 13:58:01 -080037//! 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 Danisevskis6b00e252020-12-22 11:36:45 -080045//! Each of the six functions is implemented as match statement over each key parameter variant.
Janis Danisevskise6efb242020-12-19 13:58:01 -080046//! 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 Gunasinghe12486362020-07-24 18:40:20 +000092
Janis Danisevskis6b00e252020-12-22 11:36:45 -080093use std::convert::TryInto;
94
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080095use crate::db_utils::SqlField;
Hasini Gunasingheaf993662020-07-24 18:40:20 +000096use crate::error::Error as KeystoreError;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070097use crate::error::ResponseCode;
98
Shawn Willden708744a2020-12-11 13:05:27 +000099pub use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700100 Algorithm::Algorithm, BlockMode::BlockMode, Digest::Digest, EcCurve::EcCurve,
101 HardwareAuthenticatorType::HardwareAuthenticatorType, KeyOrigin::KeyOrigin,
Janis Danisevskis398e6be2020-12-17 09:29:25 -0800102 KeyParameter::KeyParameter as KmKeyParameter,
103 KeyParameterValue::KeyParameterValue as KmKeyParameterValue, KeyPurpose::KeyPurpose,
104 PaddingMode::PaddingMode, SecurityLevel::SecurityLevel, Tag::Tag,
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000105};
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700106use android_system_keystore2::aidl::android::system::keystore2::Authorization::Authorization;
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000107use anyhow::{Context, Result};
Janis Danisevskis4522c2b2020-11-27 18:04:58 -0800108use rusqlite::types::{Null, ToSql, ToSqlOutput};
109use rusqlite::Result as SqlResult;
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000110
Janis Danisevskise6efb242020-12-19 13:58:01 -0800111/// 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)))`
123trait AssociatePrimitive {
124 type Primitive;
125
126 fn from_primitive(v: Self::Primitive) -> Self;
127 fn to_primitive(&self) -> Self::Primitive;
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000128}
129
Janis Danisevskise6efb242020-12-19 13:58:01 -0800130/// 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.
132macro_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.
148macro_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
163implement_associate_primitive_for_aidl_enum! {Algorithm}
164implement_associate_primitive_for_aidl_enum! {BlockMode}
165implement_associate_primitive_for_aidl_enum! {Digest}
166implement_associate_primitive_for_aidl_enum! {EcCurve}
167implement_associate_primitive_for_aidl_enum! {HardwareAuthenticatorType}
168implement_associate_primitive_for_aidl_enum! {KeyOrigin}
169implement_associate_primitive_for_aidl_enum! {KeyPurpose}
170implement_associate_primitive_for_aidl_enum! {PaddingMode}
171implement_associate_primitive_for_aidl_enum! {SecurityLevel}
172
173implement_associate_primitive_identity! {Vec<u8>}
174implement_associate_primitive_identity! {i64}
175implement_associate_primitive_identity! {i32}
176
Janis Danisevskis6b00e252020-12-22 11:36:45 -0800177/// 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.
180pub 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
189impl From<i64> for Primitive {
190 fn from(v: i64) -> Self {
191 Self::I64(v)
192 }
193}
194impl From<i32> for Primitive {
195 fn from(v: i32) -> Self {
196 Self::I32(v)
197 }
198}
199impl 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)]
207pub 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
216impl 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}
226impl 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}
236impl 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/// ```
269macro_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 Danisevskise6efb242020-12-19 13:58:01 -0800288/// 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/// ```
303macro_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/// ```
335macro_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/// ```
385macro_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/// ```
448macro_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.
484trait KpDefault {
485 fn default() -> Self;
486}
487
488impl KpDefault for i32 {
489 fn default() -> Self {
490 0
491 }
492}
493
494impl 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/// ```
535macro_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)*], []) => {
Matthew Maurerb77a28d2021-05-07 16:08:20 -0700602 impl From<$enum_name> for KmKeyParameter {
603 fn from(x: $enum_name) -> Self {
604 match x {
Janis Danisevskise6efb242020-12-19 13:58:01 -0800605 $($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.
630macro_rules! implement_key_parameter_value {
631 (
632 $(#[$enum_meta:meta])*
633 $enum_vis:vis enum $enum_name:ident {
634 $(
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800635 $(#[$($emeta:tt)+])*
636 $vname:ident$(($vtype:ty))?
Janis Danisevskise6efb242020-12-19 13:58:01 -0800637 ),* $(,)?
638 }
639 ) => {
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800640 implement_key_parameter_value!{
641 @extract_attr
642 $(#[$enum_meta])*
643 $enum_vis enum $enum_name {
644 []
645 [$(
646 [] [$(#[$($emeta)+])*]
647 $vname$(($vtype))?,
648 )*]
649 }
650 }
651 };
652
653 (
654 @extract_attr
655 $(#[$enum_meta:meta])*
656 $enum_vis:vis enum $enum_name:ident {
657 [$($out:tt)*]
658 [
659 [$(#[$mout:meta])*]
660 [
661 #[key_param(tag = $tag_name:ident, field = $field_name:ident)]
662 $(#[$($mtail:tt)+])*
663 ]
664 $vname:ident$(($vtype:ty))?,
665 $($tail:tt)*
666 ]
667 }
668 ) => {
669 implement_key_parameter_value!{
670 @extract_attr
671 $(#[$enum_meta])*
672 $enum_vis enum $enum_name {
673 [
674 $($out)*
675 $(#[$mout])*
676 $(#[$($mtail)+])*
677 $tag_name $field_name $vname$(($vtype))?,
678 ]
679 [$($tail)*]
680 }
681 }
682 };
683
684 (
685 @extract_attr
686 $(#[$enum_meta:meta])*
687 $enum_vis:vis enum $enum_name:ident {
688 [$($out:tt)*]
689 [
690 [$(#[$mout:meta])*]
691 [
692 #[$front:meta]
693 $(#[$($mtail:tt)+])*
694 ]
695 $vname:ident$(($vtype:ty))?,
696 $($tail:tt)*
697 ]
698 }
699 ) => {
700 implement_key_parameter_value!{
701 @extract_attr
702 $(#[$enum_meta])*
703 $enum_vis enum $enum_name {
704 [$($out)*]
705 [
706 [
707 $(#[$mout])*
708 #[$front]
709 ]
710 [$(#[$($mtail)+])*]
711 $vname$(($vtype))?,
712 $($tail)*
713 ]
714 }
715 }
716 };
717
718 (
719 @extract_attr
720 $(#[$enum_meta:meta])*
721 $enum_vis:vis enum $enum_name:ident {
722 [$($out:tt)*]
723 []
724 }
725 ) => {
726 implement_key_parameter_value!{
727 @spill
728 $(#[$enum_meta])*
729 $enum_vis enum $enum_name {
730 $($out)*
731 }
732 }
733 };
734
735 (
736 @spill
737 $(#[$enum_meta:meta])*
738 $enum_vis:vis enum $enum_name:ident {
739 $(
740 $(#[$emeta:meta])*
741 $tag_name:ident $field_name:ident $vname:ident$(($vtype:ty))?,
742 )*
743 }
744 ) => {
Janis Danisevskise6efb242020-12-19 13:58:01 -0800745 implement_enum!(
746 $(#[$enum_meta])*
747 $enum_vis enum $enum_name {
748 $(
749 $(#[$emeta])*
750 $vname$(($vtype))?
751 ),*
752 });
753
754 impl $enum_name {
755 implement_new_from_sql!($enum_name; $($vname$(($vtype))? $tag_name),*);
756 implement_get_tag!($enum_name; $($vname$(($vtype))? $tag_name),*);
Janis Danisevskis6b00e252020-12-22 11:36:45 -0800757 implement_from_tag_primitive_pair!($enum_name; $($vname$(($vtype))? $tag_name),*);
Janis Danisevskise6efb242020-12-19 13:58:01 -0800758
759 #[cfg(test)]
760 fn make_field_matches_tag_type_test_vector() -> Vec<KmKeyParameter> {
761 vec![$(KmKeyParameter{
762 tag: Tag::$tag_name,
763 value: KmKeyParameterValue::$field_name(Default::default())}
764 ),*]
765 }
766 }
767
768 implement_try_from_to_km_parameter!(
769 $enum_name;
770 $($vname$(($vtype))? $tag_name $field_name),*
771 );
772
773 implement_to_sql!($enum_name; $($vname$(($vtype))?),*);
774 };
775}
776
777implement_key_parameter_value! {
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000778/// KeyParameterValue holds a value corresponding to one of the Tags defined in
Shawn Willden525c0032021-03-29 13:58:33 +0000779/// the AIDL spec at hardware/interfaces/security/keymint
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700780#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000781pub enum KeyParameterValue {
782 /// Associated with Tag:INVALID
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800783 #[key_param(tag = INVALID, field = Invalid)]
784 Invalid,
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000785 /// Set of purposes for which the key may be used
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800786 #[key_param(tag = PURPOSE, field = KeyPurpose)]
787 KeyPurpose(KeyPurpose),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000788 /// Cryptographic algorithm with which the key is used
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800789 #[key_param(tag = ALGORITHM, field = Algorithm)]
790 Algorithm(Algorithm),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000791 /// Size of the key , in bits
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800792 #[key_param(tag = KEY_SIZE, field = Integer)]
793 KeySize(i32),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000794 /// Block cipher mode(s) with which the key may be used
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800795 #[key_param(tag = BLOCK_MODE, field = BlockMode)]
796 BlockMode(BlockMode),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000797 /// Digest algorithms that may be used with the key to perform signing and verification
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800798 #[key_param(tag = DIGEST, field = Digest)]
799 Digest(Digest),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000800 /// Padding modes that may be used with the key. Relevant to RSA, AES and 3DES keys.
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800801 #[key_param(tag = PADDING, field = PaddingMode)]
802 PaddingMode(PaddingMode),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000803 /// Can the caller provide a nonce for nonce-requiring operations
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800804 #[key_param(tag = CALLER_NONCE, field = BoolValue)]
805 CallerNonce,
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000806 /// Minimum length of MAC for HMAC keys and AES keys that support GCM mode
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800807 #[key_param(tag = MIN_MAC_LENGTH, field = Integer)]
808 MinMacLength(i32),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000809 /// The elliptic curve
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800810 #[key_param(tag = EC_CURVE, field = EcCurve)]
811 EcCurve(EcCurve),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000812 /// Value of the public exponent for an RSA key pair
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800813 #[key_param(tag = RSA_PUBLIC_EXPONENT, field = LongInteger)]
814 RSAPublicExponent(i64),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000815 /// An attestation certificate for the generated key should contain an application-scoped
816 /// and time-bounded device-unique ID
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800817 #[key_param(tag = INCLUDE_UNIQUE_ID, field = BoolValue)]
818 IncludeUniqueID,
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000819 //TODO: find out about this
820 // /// Necessary system environment conditions for the generated key to be used
821 // KeyBlobUsageRequirements(KeyBlobUsageRequirements),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000822 /// Only the boot loader can use the key
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800823 #[key_param(tag = BOOTLOADER_ONLY, field = BoolValue)]
824 BootLoaderOnly,
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000825 /// When deleted, the key is guaranteed to be permanently deleted and unusable
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800826 #[key_param(tag = ROLLBACK_RESISTANCE, field = BoolValue)]
827 RollbackResistance,
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000828 /// The date and time at which the key becomes active
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800829 #[key_param(tag = ACTIVE_DATETIME, field = DateTime)]
830 ActiveDateTime(i64),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000831 /// The date and time at which the key expires for signing and encryption
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800832 #[key_param(tag = ORIGINATION_EXPIRE_DATETIME, field = DateTime)]
833 OriginationExpireDateTime(i64),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000834 /// The date and time at which the key expires for verification and decryption
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800835 #[key_param(tag = USAGE_EXPIRE_DATETIME, field = DateTime)]
836 UsageExpireDateTime(i64),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000837 /// Minimum amount of time that elapses between allowed operations
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800838 #[key_param(tag = MIN_SECONDS_BETWEEN_OPS, field = Integer)]
839 MinSecondsBetweenOps(i32),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000840 /// Maximum number of times that a key may be used between system reboots
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800841 #[key_param(tag = MAX_USES_PER_BOOT, field = Integer)]
842 MaxUsesPerBoot(i32),
Qi Wub9433b52020-12-01 14:52:46 +0800843 /// The number of times that a limited use key can be used
844 #[key_param(tag = USAGE_COUNT_LIMIT, field = Integer)]
845 UsageCountLimit(i32),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000846 /// ID of the Android user that is permitted to use the key
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800847 #[key_param(tag = USER_ID, field = Integer)]
848 UserID(i32),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000849 /// A key may only be used under a particular secure user authentication state
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800850 #[key_param(tag = USER_SECURE_ID, field = LongInteger)]
851 UserSecureID(i64),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000852 /// No authentication is required to use this key
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800853 #[key_param(tag = NO_AUTH_REQUIRED, field = BoolValue)]
854 NoAuthRequired,
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000855 /// The types of user authenticators that may be used to authorize this key
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800856 #[key_param(tag = USER_AUTH_TYPE, field = HardwareAuthenticatorType)]
857 HardwareAuthenticatorType(HardwareAuthenticatorType),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000858 /// The time in seconds for which the key is authorized for use, after user authentication
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800859 #[key_param(tag = AUTH_TIMEOUT, field = Integer)]
860 AuthTimeout(i32),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000861 /// The key may be used after authentication timeout if device is still on-body
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800862 #[key_param(tag = ALLOW_WHILE_ON_BODY, field = BoolValue)]
863 AllowWhileOnBody,
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000864 /// The key must be unusable except when the user has provided proof of physical presence
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800865 #[key_param(tag = TRUSTED_USER_PRESENCE_REQUIRED, field = BoolValue)]
866 TrustedUserPresenceRequired,
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000867 /// Applicable to keys with KeyPurpose SIGN, and specifies that this key must not be usable
868 /// unless the user provides confirmation of the data to be signed
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800869 #[key_param(tag = TRUSTED_CONFIRMATION_REQUIRED, field = BoolValue)]
870 TrustedConfirmationRequired,
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000871 /// The key may only be used when the device is unlocked
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800872 #[key_param(tag = UNLOCKED_DEVICE_REQUIRED, field = BoolValue)]
873 UnlockedDeviceRequired,
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000874 /// When provided to generateKey or importKey, this tag specifies data
875 /// that is necessary during all uses of the key
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800876 #[key_param(tag = APPLICATION_ID, field = Blob)]
877 ApplicationID(Vec<u8>),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000878 /// When provided to generateKey or importKey, this tag specifies data
879 /// that is necessary during all uses of the key
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800880 #[key_param(tag = APPLICATION_DATA, field = Blob)]
881 ApplicationData(Vec<u8>),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000882 /// Specifies the date and time the key was created
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800883 #[key_param(tag = CREATION_DATETIME, field = DateTime)]
884 CreationDateTime(i64),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000885 /// Specifies where the key was created, if known
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800886 #[key_param(tag = ORIGIN, field = Origin)]
887 KeyOrigin(KeyOrigin),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000888 /// The key used by verified boot to validate the operating system booted
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800889 #[key_param(tag = ROOT_OF_TRUST, field = Blob)]
890 RootOfTrust(Vec<u8>),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000891 /// System OS version with which the key may be used
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800892 #[key_param(tag = OS_VERSION, field = Integer)]
893 OSVersion(i32),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000894 /// Specifies the system security patch level with which the key may be used
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800895 #[key_param(tag = OS_PATCHLEVEL, field = Integer)]
896 OSPatchLevel(i32),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000897 /// Specifies a unique, time-based identifier
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800898 #[key_param(tag = UNIQUE_ID, field = Blob)]
899 UniqueID(Vec<u8>),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000900 /// Used to deliver a "challenge" value to the attestKey() method
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800901 #[key_param(tag = ATTESTATION_CHALLENGE, field = Blob)]
902 AttestationChallenge(Vec<u8>),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000903 /// The set of applications which may use a key, used only with attestKey()
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800904 #[key_param(tag = ATTESTATION_APPLICATION_ID, field = Blob)]
905 AttestationApplicationID(Vec<u8>),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000906 /// Provides the device's brand name, to attestKey()
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800907 #[key_param(tag = ATTESTATION_ID_BRAND, field = Blob)]
908 AttestationIdBrand(Vec<u8>),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000909 /// Provides the device's device name, to attestKey()
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800910 #[key_param(tag = ATTESTATION_ID_DEVICE, field = Blob)]
911 AttestationIdDevice(Vec<u8>),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000912 /// Provides the device's product name, to attestKey()
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800913 #[key_param(tag = ATTESTATION_ID_PRODUCT, field = Blob)]
914 AttestationIdProduct(Vec<u8>),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000915 /// Provides the device's serial number, to attestKey()
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800916 #[key_param(tag = ATTESTATION_ID_SERIAL, field = Blob)]
917 AttestationIdSerial(Vec<u8>),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000918 /// Provides the IMEIs for all radios on the device, to attestKey()
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800919 #[key_param(tag = ATTESTATION_ID_IMEI, field = Blob)]
920 AttestationIdIMEI(Vec<u8>),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000921 /// Provides the MEIDs for all radios on the device, to attestKey()
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800922 #[key_param(tag = ATTESTATION_ID_MEID, field = Blob)]
923 AttestationIdMEID(Vec<u8>),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000924 /// Provides the device's manufacturer name, to attestKey()
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800925 #[key_param(tag = ATTESTATION_ID_MANUFACTURER, field = Blob)]
926 AttestationIdManufacturer(Vec<u8>),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000927 /// Provides the device's model name, to attestKey()
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800928 #[key_param(tag = ATTESTATION_ID_MODEL, field = Blob)]
929 AttestationIdModel(Vec<u8>),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000930 /// Specifies the vendor image security patch level with which the key may be used
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800931 #[key_param(tag = VENDOR_PATCHLEVEL, field = Integer)]
932 VendorPatchLevel(i32),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000933 /// Specifies the boot image (kernel) security patch level with which the key may be used
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800934 #[key_param(tag = BOOT_PATCHLEVEL, field = Integer)]
935 BootPatchLevel(i32),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000936 /// Provides "associated data" for AES-GCM encryption or decryption
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800937 #[key_param(tag = ASSOCIATED_DATA, field = Blob)]
938 AssociatedData(Vec<u8>),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000939 /// Provides or returns a nonce or Initialization Vector (IV) for AES-GCM,
940 /// AES-CBC, AES-CTR, or 3DES-CBC encryption or decryption
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800941 #[key_param(tag = NONCE, field = Blob)]
942 Nonce(Vec<u8>),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000943 /// Provides the requested length of a MAC or GCM authentication tag, in bits
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800944 #[key_param(tag = MAC_LENGTH, field = Integer)]
945 MacLength(i32),
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000946 /// Specifies whether the device has been factory reset since the
947 /// last unique ID rotation. Used for key attestation
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800948 #[key_param(tag = RESET_SINCE_ID_ROTATION, field = BoolValue)]
949 ResetSinceIdRotation,
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000950 /// Used to deliver a cryptographic token proving that the user
Janis Danisevskis2c084012021-01-31 22:23:17 -0800951 /// confirmed a signing request
Janis Danisevskis6f1bb562020-12-28 15:52:41 -0800952 #[key_param(tag = CONFIRMATION_TOKEN, field = Blob)]
953 ConfirmationToken(Vec<u8>),
Janis Danisevskis2c084012021-01-31 22:23:17 -0800954 /// Used to deliver the certificate serial number to the KeyMint instance
955 /// certificate generation.
956 #[key_param(tag = CERTIFICATE_SERIAL, field = Blob)]
957 CertificateSerial(Vec<u8>),
958 /// Used to deliver the certificate subject to the KeyMint instance
959 /// certificate generation. This must be DER encoded X509 name.
960 #[key_param(tag = CERTIFICATE_SUBJECT, field = Blob)]
961 CertificateSubject(Vec<u8>),
962 /// Used to deliver the not before date in milliseconds to KeyMint during key generation/import.
963 #[key_param(tag = CERTIFICATE_NOT_BEFORE, field = DateTime)]
964 CertificateNotBefore(i64),
965 /// Used to deliver the not after date in milliseconds to KeyMint during key generation/import.
966 #[key_param(tag = CERTIFICATE_NOT_AFTER, field = DateTime)]
967 CertificateNotAfter(i64),
Paul Crowley7c57bf12021-02-02 16:26:57 -0800968 /// Specifies a maximum boot level at which a key should function
969 #[key_param(tag = MAX_BOOT_LEVEL, field = Integer)]
970 MaxBootLevel(i32),
Janis Danisevskise6efb242020-12-19 13:58:01 -0800971}
972}
973
974impl From<&KmKeyParameter> for KeyParameterValue {
975 fn from(kp: &KmKeyParameter) -> Self {
976 kp.clone().into()
977 }
978}
979
980/// KeyParameter wraps the KeyParameterValue and the security level at which it is enforced.
981#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
982pub struct KeyParameter {
983 value: KeyParameterValue,
984 security_level: SecurityLevel,
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000985}
986
987impl KeyParameter {
988 /// Create an instance of KeyParameter, given the value and the security level.
Janis Danisevskise6efb242020-12-19 13:58:01 -0800989 pub fn new(value: KeyParameterValue, security_level: SecurityLevel) -> Self {
990 KeyParameter { value, security_level }
Hasini Gunasinghe12486362020-07-24 18:40:20 +0000991 }
992
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000993 /// Construct a KeyParameter from the data from a rusqlite row.
994 /// Note that following variants of KeyParameterValue should not be stored:
995 /// IncludeUniqueID, ApplicationID, ApplicationData, RootOfTrust, UniqueID,
996 /// Attestation*, AssociatedData, Nonce, MacLength, ResetSinceIdRotation, ConfirmationToken.
997 /// This filtering is enforced at a higher level and here we support conversion for all the
998 /// variants.
999 pub fn new_from_sql(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001000 tag_val: Tag,
Hasini Gunasingheaf993662020-07-24 18:40:20 +00001001 data: &SqlField,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001002 security_level_val: SecurityLevel,
Hasini Gunasingheaf993662020-07-24 18:40:20 +00001003 ) -> Result<Self> {
Janis Danisevskise6efb242020-12-19 13:58:01 -08001004 Ok(Self {
1005 value: KeyParameterValue::new_from_sql(tag_val, data)?,
1006 security_level: security_level_val,
1007 })
1008 }
Hasini Gunasingheaf993662020-07-24 18:40:20 +00001009
Janis Danisevskise6efb242020-12-19 13:58:01 -08001010 /// Get the KeyMint Tag of this this key parameter.
1011 pub fn get_tag(&self) -> Tag {
1012 self.value.get_tag()
1013 }
1014
1015 /// Returns key parameter value.
1016 pub fn key_parameter_value(&self) -> &KeyParameterValue {
1017 &self.value
1018 }
1019
1020 /// Returns the security level of this key parameter.
1021 pub fn security_level(&self) -> &SecurityLevel {
1022 &self.security_level
1023 }
1024
1025 /// An authorization is a KeyParameter with an associated security level that is used
1026 /// to convey the key characteristics to keystore clients. This function consumes
1027 /// an internal KeyParameter representation to produce the Authorization wire type.
1028 pub fn into_authorization(self) -> Authorization {
1029 Authorization { securityLevel: self.security_level, keyParameter: self.value.into() }
Hasini Gunasingheaf993662020-07-24 18:40:20 +00001030 }
1031}
1032
Janis Danisevskise6efb242020-12-19 13:58:01 -08001033#[cfg(test)]
1034mod generated_key_parameter_tests {
1035 use super::*;
1036 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::TagType::TagType;
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001037
Janis Danisevskise6efb242020-12-19 13:58:01 -08001038 fn get_field_by_tag_type(tag: Tag) -> KmKeyParameterValue {
1039 let tag_type = TagType((tag.0 as u32 & 0xF0000000) as i32);
1040 match tag {
1041 Tag::ALGORITHM => return KmKeyParameterValue::Algorithm(Default::default()),
1042 Tag::BLOCK_MODE => return KmKeyParameterValue::BlockMode(Default::default()),
1043 Tag::PADDING => return KmKeyParameterValue::PaddingMode(Default::default()),
1044 Tag::DIGEST => return KmKeyParameterValue::Digest(Default::default()),
1045 Tag::EC_CURVE => return KmKeyParameterValue::EcCurve(Default::default()),
1046 Tag::ORIGIN => return KmKeyParameterValue::Origin(Default::default()),
1047 Tag::PURPOSE => return KmKeyParameterValue::KeyPurpose(Default::default()),
1048 Tag::USER_AUTH_TYPE => {
1049 return KmKeyParameterValue::HardwareAuthenticatorType(Default::default())
1050 }
1051 Tag::HARDWARE_TYPE => return KmKeyParameterValue::SecurityLevel(Default::default()),
1052 _ => {}
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001053 }
Janis Danisevskise6efb242020-12-19 13:58:01 -08001054 match tag_type {
1055 TagType::INVALID => return KmKeyParameterValue::Invalid(Default::default()),
1056 TagType::ENUM | TagType::ENUM_REP => {}
1057 TagType::UINT | TagType::UINT_REP => {
1058 return KmKeyParameterValue::Integer(Default::default())
1059 }
1060 TagType::ULONG | TagType::ULONG_REP => {
1061 return KmKeyParameterValue::LongInteger(Default::default())
1062 }
1063 TagType::DATE => return KmKeyParameterValue::DateTime(Default::default()),
1064 TagType::BOOL => return KmKeyParameterValue::BoolValue(Default::default()),
1065 TagType::BIGNUM | TagType::BYTES => {
1066 return KmKeyParameterValue::Blob(Default::default())
1067 }
1068 _ => {}
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001069 }
Janis Danisevskise6efb242020-12-19 13:58:01 -08001070 panic!("Unknown tag/tag_type: {:?} {:?}", tag, tag_type);
1071 }
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001072
Janis Danisevskise6efb242020-12-19 13:58:01 -08001073 fn check_field_matches_tag_type(list_o_parameters: &[KmKeyParameter]) {
1074 for kp in list_o_parameters.iter() {
1075 match (&kp.value, get_field_by_tag_type(kp.tag)) {
1076 (&KmKeyParameterValue::Algorithm(_), KmKeyParameterValue::Algorithm(_))
1077 | (&KmKeyParameterValue::BlockMode(_), KmKeyParameterValue::BlockMode(_))
1078 | (&KmKeyParameterValue::PaddingMode(_), KmKeyParameterValue::PaddingMode(_))
1079 | (&KmKeyParameterValue::Digest(_), KmKeyParameterValue::Digest(_))
1080 | (&KmKeyParameterValue::EcCurve(_), KmKeyParameterValue::EcCurve(_))
1081 | (&KmKeyParameterValue::Origin(_), KmKeyParameterValue::Origin(_))
1082 | (&KmKeyParameterValue::KeyPurpose(_), KmKeyParameterValue::KeyPurpose(_))
1083 | (
1084 &KmKeyParameterValue::HardwareAuthenticatorType(_),
1085 KmKeyParameterValue::HardwareAuthenticatorType(_),
1086 )
1087 | (&KmKeyParameterValue::SecurityLevel(_), KmKeyParameterValue::SecurityLevel(_))
1088 | (&KmKeyParameterValue::Invalid(_), KmKeyParameterValue::Invalid(_))
1089 | (&KmKeyParameterValue::Integer(_), KmKeyParameterValue::Integer(_))
1090 | (&KmKeyParameterValue::LongInteger(_), KmKeyParameterValue::LongInteger(_))
1091 | (&KmKeyParameterValue::DateTime(_), KmKeyParameterValue::DateTime(_))
1092 | (&KmKeyParameterValue::BoolValue(_), KmKeyParameterValue::BoolValue(_))
1093 | (&KmKeyParameterValue::Blob(_), KmKeyParameterValue::Blob(_)) => {}
1094 (actual, expected) => panic!(
1095 "Tag {:?} associated with variant {:?} expected {:?}",
1096 kp.tag, actual, expected
1097 ),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001098 }
1099 }
Janis Danisevskise6efb242020-12-19 13:58:01 -08001100 }
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001101
Janis Danisevskise6efb242020-12-19 13:58:01 -08001102 #[test]
1103 fn key_parameter_value_field_matches_tag_type() {
1104 check_field_matches_tag_type(&KeyParameterValue::make_field_matches_tag_type_test_vector());
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001105 }
1106}
1107
1108#[cfg(test)]
1109mod basic_tests {
1110 use crate::key_parameter::*;
1111
1112 // Test basic functionality of KeyParameter.
1113 #[test]
1114 fn test_key_parameter() {
1115 let key_parameter = KeyParameter::new(
1116 KeyParameterValue::Algorithm(Algorithm::RSA),
1117 SecurityLevel::STRONGBOX,
1118 );
1119
1120 assert_eq!(key_parameter.get_tag(), Tag::ALGORITHM);
1121
1122 assert_eq!(
1123 *key_parameter.key_parameter_value(),
1124 KeyParameterValue::Algorithm(Algorithm::RSA)
1125 );
1126
1127 assert_eq!(*key_parameter.security_level(), SecurityLevel::STRONGBOX);
1128 }
1129}
1130
Hasini Gunasingheaf993662020-07-24 18:40:20 +00001131/// The storage_tests module first tests the 'new_from_sql' method for KeyParameters of different
1132/// data types and then tests 'to_sql' method for KeyParameters of those
1133/// different data types. The five different data types for KeyParameter values are:
1134/// i) enums of u32
1135/// ii) u32
1136/// iii) u64
1137/// iv) Vec<u8>
1138/// v) bool
1139#[cfg(test)]
1140mod storage_tests {
1141 use crate::error::*;
1142 use crate::key_parameter::*;
1143 use anyhow::Result;
1144 use rusqlite::types::ToSql;
1145 use rusqlite::{params, Connection, NO_PARAMS};
1146
1147 /// Test initializing a KeyParameter (with key parameter value corresponding to an enum of i32)
1148 /// from a database table row.
1149 #[test]
1150 fn test_new_from_sql_enum_i32() -> Result<()> {
1151 let db = init_db()?;
1152 insert_into_keyparameter(
1153 &db,
1154 1,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001155 Tag::ALGORITHM.0,
1156 &Algorithm::RSA.0,
1157 SecurityLevel::STRONGBOX.0,
Hasini Gunasingheaf993662020-07-24 18:40:20 +00001158 )?;
1159 let key_param = query_from_keyparameter(&db)?;
1160 assert_eq!(Tag::ALGORITHM, key_param.get_tag());
1161 assert_eq!(*key_param.key_parameter_value(), KeyParameterValue::Algorithm(Algorithm::RSA));
1162 assert_eq!(*key_param.security_level(), SecurityLevel::STRONGBOX);
1163 Ok(())
1164 }
1165
1166 /// Test initializing a KeyParameter (with key parameter value which is of i32)
1167 /// from a database table row.
1168 #[test]
1169 fn test_new_from_sql_i32() -> Result<()> {
1170 let db = init_db()?;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001171 insert_into_keyparameter(&db, 1, Tag::KEY_SIZE.0, &1024, SecurityLevel::STRONGBOX.0)?;
Hasini Gunasingheaf993662020-07-24 18:40:20 +00001172 let key_param = query_from_keyparameter(&db)?;
1173 assert_eq!(Tag::KEY_SIZE, key_param.get_tag());
1174 assert_eq!(*key_param.key_parameter_value(), KeyParameterValue::KeySize(1024));
1175 Ok(())
1176 }
1177
1178 /// Test initializing a KeyParameter (with key parameter value which is of i64)
1179 /// from a database table row.
1180 #[test]
1181 fn test_new_from_sql_i64() -> Result<()> {
1182 let db = init_db()?;
1183 // max value for i64, just to test corner cases
1184 insert_into_keyparameter(
1185 &db,
1186 1,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001187 Tag::RSA_PUBLIC_EXPONENT.0,
Hasini Gunasingheaf993662020-07-24 18:40:20 +00001188 &(i64::MAX),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001189 SecurityLevel::STRONGBOX.0,
Hasini Gunasingheaf993662020-07-24 18:40:20 +00001190 )?;
1191 let key_param = query_from_keyparameter(&db)?;
1192 assert_eq!(Tag::RSA_PUBLIC_EXPONENT, key_param.get_tag());
1193 assert_eq!(
1194 *key_param.key_parameter_value(),
1195 KeyParameterValue::RSAPublicExponent(i64::MAX)
1196 );
1197 Ok(())
1198 }
1199
1200 /// Test initializing a KeyParameter (with key parameter value which is of bool)
1201 /// from a database table row.
1202 #[test]
1203 fn test_new_from_sql_bool() -> Result<()> {
1204 let db = init_db()?;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001205 insert_into_keyparameter(&db, 1, Tag::CALLER_NONCE.0, &Null, SecurityLevel::STRONGBOX.0)?;
Hasini Gunasingheaf993662020-07-24 18:40:20 +00001206 let key_param = query_from_keyparameter(&db)?;
1207 assert_eq!(Tag::CALLER_NONCE, key_param.get_tag());
1208 assert_eq!(*key_param.key_parameter_value(), KeyParameterValue::CallerNonce);
1209 Ok(())
1210 }
1211
1212 /// Test initializing a KeyParameter (with key parameter value which is of Vec<u8>)
1213 /// from a database table row.
1214 #[test]
1215 fn test_new_from_sql_vec_u8() -> Result<()> {
1216 let db = init_db()?;
1217 let app_id = String::from("MyAppID");
1218 let app_id_bytes = app_id.into_bytes();
1219 insert_into_keyparameter(
1220 &db,
1221 1,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001222 Tag::APPLICATION_ID.0,
Hasini Gunasingheaf993662020-07-24 18:40:20 +00001223 &app_id_bytes,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001224 SecurityLevel::STRONGBOX.0,
Hasini Gunasingheaf993662020-07-24 18:40:20 +00001225 )?;
1226 let key_param = query_from_keyparameter(&db)?;
1227 assert_eq!(Tag::APPLICATION_ID, key_param.get_tag());
1228 assert_eq!(
1229 *key_param.key_parameter_value(),
1230 KeyParameterValue::ApplicationID(app_id_bytes)
1231 );
1232 Ok(())
1233 }
1234
1235 /// Test storing a KeyParameter (with key parameter value which corresponds to an enum of i32)
1236 /// in the database
1237 #[test]
1238 fn test_to_sql_enum_i32() -> Result<()> {
1239 let db = init_db()?;
1240 let kp = KeyParameter::new(
1241 KeyParameterValue::Algorithm(Algorithm::RSA),
1242 SecurityLevel::STRONGBOX,
1243 );
1244 store_keyparameter(&db, 1, &kp)?;
1245 let key_param = query_from_keyparameter(&db)?;
1246 assert_eq!(kp.get_tag(), key_param.get_tag());
1247 assert_eq!(kp.key_parameter_value(), key_param.key_parameter_value());
1248 assert_eq!(kp.security_level(), key_param.security_level());
1249 Ok(())
1250 }
1251
1252 /// Test storing a KeyParameter (with key parameter value which is of i32) in the database
1253 #[test]
1254 fn test_to_sql_i32() -> Result<()> {
1255 let db = init_db()?;
1256 let kp = KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::STRONGBOX);
1257 store_keyparameter(&db, 1, &kp)?;
1258 let key_param = query_from_keyparameter(&db)?;
1259 assert_eq!(kp.get_tag(), key_param.get_tag());
1260 assert_eq!(kp.key_parameter_value(), key_param.key_parameter_value());
1261 assert_eq!(kp.security_level(), key_param.security_level());
1262 Ok(())
1263 }
1264
1265 /// Test storing a KeyParameter (with key parameter value which is of i64) in the database
1266 #[test]
1267 fn test_to_sql_i64() -> Result<()> {
1268 let db = init_db()?;
1269 // max value for i64, just to test corner cases
1270 let kp = KeyParameter::new(
1271 KeyParameterValue::RSAPublicExponent(i64::MAX),
1272 SecurityLevel::STRONGBOX,
1273 );
1274 store_keyparameter(&db, 1, &kp)?;
1275 let key_param = query_from_keyparameter(&db)?;
1276 assert_eq!(kp.get_tag(), key_param.get_tag());
1277 assert_eq!(kp.key_parameter_value(), key_param.key_parameter_value());
1278 assert_eq!(kp.security_level(), key_param.security_level());
1279 Ok(())
1280 }
1281
1282 /// Test storing a KeyParameter (with key parameter value which is of Vec<u8>) in the database
1283 #[test]
1284 fn test_to_sql_vec_u8() -> Result<()> {
1285 let db = init_db()?;
1286 let kp = KeyParameter::new(
1287 KeyParameterValue::ApplicationID(String::from("MyAppID").into_bytes()),
1288 SecurityLevel::STRONGBOX,
1289 );
1290 store_keyparameter(&db, 1, &kp)?;
1291 let key_param = query_from_keyparameter(&db)?;
1292 assert_eq!(kp.get_tag(), key_param.get_tag());
1293 assert_eq!(kp.key_parameter_value(), key_param.key_parameter_value());
1294 assert_eq!(kp.security_level(), key_param.security_level());
1295 Ok(())
1296 }
1297
1298 /// Test storing a KeyParameter (with key parameter value which is of i32) in the database
1299 #[test]
1300 fn test_to_sql_bool() -> Result<()> {
1301 let db = init_db()?;
1302 let kp = KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::STRONGBOX);
1303 store_keyparameter(&db, 1, &kp)?;
1304 let key_param = query_from_keyparameter(&db)?;
1305 assert_eq!(kp.get_tag(), key_param.get_tag());
1306 assert_eq!(kp.key_parameter_value(), key_param.key_parameter_value());
1307 assert_eq!(kp.security_level(), key_param.security_level());
1308 Ok(())
1309 }
1310
1311 #[test]
1312 /// Test Tag::Invalid
1313 fn test_invalid_tag() -> Result<()> {
1314 let db = init_db()?;
1315 insert_into_keyparameter(&db, 1, 0, &123, 1)?;
1316 let key_param = query_from_keyparameter(&db)?;
1317 assert_eq!(Tag::INVALID, key_param.get_tag());
1318 Ok(())
1319 }
1320
1321 #[test]
1322 fn test_non_existing_enum_variant() -> Result<()> {
1323 let db = init_db()?;
1324 insert_into_keyparameter(&db, 1, 100, &123, 1)?;
Janis Danisevskise6efb242020-12-19 13:58:01 -08001325 let key_param = query_from_keyparameter(&db)?;
1326 assert_eq!(Tag::INVALID, key_param.get_tag());
Hasini Gunasingheaf993662020-07-24 18:40:20 +00001327 Ok(())
1328 }
1329
1330 #[test]
1331 fn test_invalid_conversion_from_sql() -> Result<()> {
1332 let db = init_db()?;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001333 insert_into_keyparameter(&db, 1, Tag::ALGORITHM.0, &Null, 1)?;
Hasini Gunasingheaf993662020-07-24 18:40:20 +00001334 tests::check_result_contains_error_string(
1335 query_from_keyparameter(&db),
1336 "Failed to read sql data for tag: ALGORITHM.",
1337 );
1338 Ok(())
1339 }
1340
1341 /// Helper method to init database table for key parameter
1342 fn init_db() -> Result<Connection> {
1343 let db = Connection::open_in_memory().context("Failed to initialize sqlite connection.")?;
1344 db.execute("ATTACH DATABASE ? as 'persistent';", params![""])
1345 .context("Failed to attach databases.")?;
1346 db.execute(
1347 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
1348 keyentryid INTEGER,
1349 tag INTEGER,
1350 data ANY,
1351 security_level INTEGER);",
1352 NO_PARAMS,
1353 )
1354 .context("Failed to initialize \"keyparameter\" table.")?;
1355 Ok(db)
1356 }
1357
1358 /// Helper method to insert an entry into key parameter table, with individual parameters
1359 fn insert_into_keyparameter<T: ToSql>(
1360 db: &Connection,
1361 key_id: i64,
1362 tag: i32,
1363 value: &T,
1364 security_level: i32,
1365 ) -> Result<()> {
1366 db.execute(
1367 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001368 VALUES(?, ?, ?, ?);",
Hasini Gunasingheaf993662020-07-24 18:40:20 +00001369 params![key_id, tag, *value, security_level],
1370 )?;
1371 Ok(())
1372 }
1373
1374 /// Helper method to store a key parameter instance.
1375 fn store_keyparameter(db: &Connection, key_id: i64, kp: &KeyParameter) -> Result<()> {
1376 db.execute(
1377 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001378 VALUES(?, ?, ?, ?);",
1379 params![key_id, kp.get_tag().0, kp.key_parameter_value(), kp.security_level().0],
Hasini Gunasingheaf993662020-07-24 18:40:20 +00001380 )?;
1381 Ok(())
1382 }
1383
1384 /// Helper method to query a row from keyparameter table
1385 fn query_from_keyparameter(db: &Connection) -> Result<KeyParameter> {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001386 let mut stmt =
1387 db.prepare("SELECT tag, data, security_level FROM persistent.keyparameter")?;
Hasini Gunasingheaf993662020-07-24 18:40:20 +00001388 let mut rows = stmt.query(NO_PARAMS)?;
1389 let row = rows.next()?.unwrap();
Matthew Maurerb77a28d2021-05-07 16:08:20 -07001390 KeyParameter::new_from_sql(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001391 Tag(row.get(0)?),
Janis Danisevskis4522c2b2020-11-27 18:04:58 -08001392 &SqlField::new(1, row),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001393 SecurityLevel(row.get(2)?),
Matthew Maurerb77a28d2021-05-07 16:08:20 -07001394 )
Hasini Gunasingheaf993662020-07-24 18:40:20 +00001395 }
1396}
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001397
1398/// The wire_tests module tests the 'convert_to_wire' and 'convert_from_wire' methods for
Janis Danisevskis85d47932020-10-23 16:12:59 -07001399/// KeyParameter, for the four different types used in KmKeyParameter, in addition to Invalid
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001400/// key parameter.
1401/// i) bool
1402/// ii) integer
1403/// iii) longInteger
Janis Danisevskis85d47932020-10-23 16:12:59 -07001404/// iv) blob
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001405#[cfg(test)]
1406mod wire_tests {
1407 use crate::key_parameter::*;
1408 /// unit tests for to conversions
1409 #[test]
1410 fn test_convert_to_wire_invalid() {
1411 let kp = KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::STRONGBOX);
Janis Danisevskise6efb242020-12-19 13:58:01 -08001412 assert_eq!(
1413 KmKeyParameter { tag: Tag::INVALID, value: KmKeyParameterValue::Invalid(0) },
1414 kp.value.into()
1415 );
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001416 }
1417 #[test]
1418 fn test_convert_to_wire_bool() {
1419 let kp = KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::STRONGBOX);
Janis Danisevskise6efb242020-12-19 13:58:01 -08001420 assert_eq!(
1421 KmKeyParameter { tag: Tag::CALLER_NONCE, value: KmKeyParameterValue::BoolValue(true) },
1422 kp.value.into()
1423 );
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001424 }
1425 #[test]
1426 fn test_convert_to_wire_integer() {
1427 let kp = KeyParameter::new(
1428 KeyParameterValue::KeyPurpose(KeyPurpose::ENCRYPT),
1429 SecurityLevel::STRONGBOX,
1430 );
Janis Danisevskise6efb242020-12-19 13:58:01 -08001431 assert_eq!(
1432 KmKeyParameter {
1433 tag: Tag::PURPOSE,
1434 value: KmKeyParameterValue::KeyPurpose(KeyPurpose::ENCRYPT)
1435 },
1436 kp.value.into()
1437 );
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001438 }
1439 #[test]
1440 fn test_convert_to_wire_long_integer() {
1441 let kp =
1442 KeyParameter::new(KeyParameterValue::UserSecureID(i64::MAX), SecurityLevel::STRONGBOX);
Janis Danisevskise6efb242020-12-19 13:58:01 -08001443 assert_eq!(
1444 KmKeyParameter {
1445 tag: Tag::USER_SECURE_ID,
1446 value: KmKeyParameterValue::LongInteger(i64::MAX)
1447 },
1448 kp.value.into()
1449 );
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001450 }
1451 #[test]
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001452 fn test_convert_to_wire_blob() {
1453 let kp = KeyParameter::new(
1454 KeyParameterValue::ConfirmationToken(String::from("ConfirmationToken").into_bytes()),
1455 SecurityLevel::STRONGBOX,
1456 );
Janis Danisevskis398e6be2020-12-17 09:29:25 -08001457 assert_eq!(
Janis Danisevskise6efb242020-12-19 13:58:01 -08001458 KmKeyParameter {
1459 tag: Tag::CONFIRMATION_TOKEN,
1460 value: KmKeyParameterValue::Blob(String::from("ConfirmationToken").into_bytes())
1461 },
1462 kp.value.into()
Janis Danisevskis398e6be2020-12-17 09:29:25 -08001463 );
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001464 }
1465
1466 /// unit tests for from conversion
1467 #[test]
1468 fn test_convert_from_wire_invalid() {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001469 let aidl_kp = KmKeyParameter { tag: Tag::INVALID, ..Default::default() };
Janis Danisevskise6efb242020-12-19 13:58:01 -08001470 assert_eq!(KeyParameterValue::Invalid, aidl_kp.into());
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001471 }
1472 #[test]
1473 fn test_convert_from_wire_bool() {
1474 let aidl_kp =
Janis Danisevskis398e6be2020-12-17 09:29:25 -08001475 KmKeyParameter { tag: Tag::CALLER_NONCE, value: KmKeyParameterValue::BoolValue(true) };
Janis Danisevskise6efb242020-12-19 13:58:01 -08001476 assert_eq!(KeyParameterValue::CallerNonce, aidl_kp.into());
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001477 }
1478 #[test]
1479 fn test_convert_from_wire_integer() {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001480 let aidl_kp = KmKeyParameter {
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001481 tag: Tag::PURPOSE,
Janis Danisevskis398e6be2020-12-17 09:29:25 -08001482 value: KmKeyParameterValue::KeyPurpose(KeyPurpose::ENCRYPT),
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001483 };
Janis Danisevskise6efb242020-12-19 13:58:01 -08001484 assert_eq!(KeyParameterValue::KeyPurpose(KeyPurpose::ENCRYPT), aidl_kp.into());
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001485 }
1486 #[test]
1487 fn test_convert_from_wire_long_integer() {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001488 let aidl_kp = KmKeyParameter {
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001489 tag: Tag::USER_SECURE_ID,
Janis Danisevskis398e6be2020-12-17 09:29:25 -08001490 value: KmKeyParameterValue::LongInteger(i64::MAX),
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001491 };
Janis Danisevskise6efb242020-12-19 13:58:01 -08001492 assert_eq!(KeyParameterValue::UserSecureID(i64::MAX), aidl_kp.into());
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001493 }
1494 #[test]
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001495 fn test_convert_from_wire_blob() {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001496 let aidl_kp = KmKeyParameter {
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001497 tag: Tag::CONFIRMATION_TOKEN,
Janis Danisevskis398e6be2020-12-17 09:29:25 -08001498 value: KmKeyParameterValue::Blob(String::from("ConfirmationToken").into_bytes()),
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001499 };
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001500 assert_eq!(
1501 KeyParameterValue::ConfirmationToken(String::from("ConfirmationToken").into_bytes()),
Janis Danisevskise6efb242020-12-19 13:58:01 -08001502 aidl_kp.into()
Hasini Gunasinghe3eb77c22020-08-28 15:45:06 +00001503 );
1504 }
1505}