api_impl/
storage.rs

1// Copyright 2024 The Fuchsia Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::cell::{Ref, RefCell, RefMut};
6use std::cmp::min;
7use std::collections::btree_map::Entry as BTreeMapEntry;
8use std::collections::hash_map::Entry as HashMapEntry;
9use std::collections::{BTreeMap, HashMap, HashSet};
10use std::ops::{Bound, Deref, DerefMut};
11use std::rc::Rc;
12
13use elliptic_curve::sec1::ToEncodedPoint as _;
14use num_traits::FromPrimitive as _;
15use p256::NistP256;
16use rsa::traits::{PrivateKeyParts as _, PublicKeyParts as _};
17use rsa::{BigUint, RsaPrivateKey};
18use tee_internal::{
19    Attribute, AttributeId, BufferOrValue, DATA_MAX_POSITION, EccCurve, Error, HandleFlags, MemRef,
20    OBJECT_ID_MAX_LEN, ObjectEnumHandle, ObjectHandle, ObjectInfo, Result as TeeResult,
21    Storage as TeeStorage, Type, Usage, ValueFields, Whence,
22};
23use thiserror::Error;
24
25use crate::ErrorWithSize;
26use crate::crypto::Rng;
27
28type P256SecretKey = elliptic_curve::SecretKey<NistP256>;
29
30pub struct Storage {
31    persistent_objects: PersistentObjects,
32    transient_objects: TransientObjects,
33}
34
35//
36// We establish the private convention that all persistent object handles are
37// odd in value, while all transient object handles are even.
38//
39
40fn is_persistent_handle(object: ObjectHandle) -> bool {
41    *object % 2 == 1
42}
43
44// We define the inverse of is_persistent_handle() for readability at callsites
45// where we want to more directly check for transience.
46fn is_transient_handle(object: ObjectHandle) -> bool {
47    !is_persistent_handle(object)
48}
49
50//
51// Key type definitions.
52//
53// See Table 5-9: TEE_AllocateTransientObject Object Types and Key Sizes 4.
54//
55
56// A representation of a retrieved buffer attribute. Ideally, we'd just use
57// Option<&[u8]>, but some of the APIs we're gluing here like to return vector
58// representations.
59pub enum BufferAttribute<'a> {
60    Slice(&'a [u8]),
61    Vector(Vec<u8>),
62}
63
64// A internal trait representing the common key operations.
65//
66// TODO(https://fxbug.dev/371213067): Right now it's convenient to give default
67// implementations to generate "unimplemented" stubs for the various key types
68// we don't yet support with minimal boilerplate. When more is
69// supported/implemented, we can remove these defaults.
70pub trait KeyType {
71    fn new(_max_size: u32) -> TeeResult<Self>
72    where
73        Self: Sized, // Not a subtrait to keep KeyType dyn-compatible
74    {
75        unimplemented!()
76    }
77
78    fn is_valid_size(_size: u32) -> bool
79    where
80        Self: Sized, // Not a subtrait to keep KeyType dyn-compatible
81    {
82        false
83    }
84
85    fn size(&self) -> u32 {
86        0
87    }
88
89    fn max_size(&self) -> u32 {
90        0
91    }
92
93    fn buffer_attribute(&self, _id: AttributeId) -> Option<BufferAttribute<'_>> {
94        None
95    }
96
97    fn value_attribute(&self, _id: AttributeId) -> Option<ValueFields> {
98        None
99    }
100
101    fn reset(&mut self) {
102        unimplemented!()
103    }
104
105    fn populate(&mut self, _attributes: &[Attribute]) -> TeeResult {
106        unimplemented!()
107    }
108
109    fn generate(&mut self, _size: u32, _params: &[Attribute]) -> TeeResult {
110        unimplemented!()
111    }
112}
113
114// An error type in service of extract_attributes!() below.
115#[derive(Error, Debug)]
116enum ExtractAttributeError {
117    #[error("{0:?} provided twice")]
118    ProvidedTwice(AttributeId),
119
120    #[error("Unexpected attribute: {0:?}")]
121    Unexpected(AttributeId),
122}
123
124// This trait exists only to aid in the definition of extract_attributes!
125// just below, injecting a dose of generics to support both the memory and
126// value attribute cases, which seems hard to do with macro tricks alone.
127trait ExtractAttributeInto<T> {
128    fn extract_into(self, value: &mut T) -> Result<(), ExtractAttributeError>;
129}
130
131impl<'a> ExtractAttributeInto<&'a [u8]> for &'a Attribute {
132    fn extract_into(self, value: &mut &'a [u8]) -> Result<(), ExtractAttributeError> {
133        if !value.is_empty() {
134            Err(ExtractAttributeError::ProvidedTwice(self.id))
135        } else {
136            *value = self.as_memory_reference().as_slice();
137            Ok(())
138        }
139    }
140}
141
142impl ExtractAttributeInto<Option<ValueFields>> for &Attribute {
143    fn extract_into(self, value: &mut Option<ValueFields>) -> Result<(), ExtractAttributeError> {
144        if value.is_some() {
145            Err(ExtractAttributeError::ProvidedTwice(self.id))
146        } else {
147            *value = Some(*self.as_value());
148            Ok(())
149        }
150    }
151}
152
153// Extracts the expected attributes from a list, returning
154// Result<(), ExtractAttributeError>, ensuring that only expected ones are
155// present and nothing expected is duplicated.
156//
157// Example usage:
158// ```
159// let mut mem_attr: &[u8] = &[];
160// let mut val_attr: Option<ValueFields> = None;
161// ...
162// extract_attributes!(
163//     attrs,
164//     AttributeId::A => mem_attr, // If present, will set mem_attr as the A payload
165//     AttributeId::B => val_attr, // If present, will val_attr as the B payload
166//     ...
167// ).unwrap();
168// ```
169macro_rules! extract_attributes {
170    ($attributes:expr, $($id:path => $var:ident),*) => {
171        || -> Result<(), ExtractAttributeError> {
172            for attr in $attributes {
173                match attr.id {
174                    $( $id => attr.extract_into(&mut $var)?, )*
175                    _ => return Err(ExtractAttributeError::Unexpected(attr.id)),
176                }
177            }
178            Ok(())
179        }()
180    };
181}
182
183#[derive(Clone)]
184pub struct SimpleSymmetricKey<const SIZE_MIN: u32, const SIZE_MAX: u32, const SIZE_MULTIPLE: u32> {
185    pub secret: Vec<u8>, // TEE_ATTR_SECRET_VALUE
186}
187
188impl<const SIZE_MIN: u32, const SIZE_MAX: u32, const SIZE_MULTIPLE: u32> KeyType
189    for SimpleSymmetricKey<SIZE_MIN, SIZE_MAX, SIZE_MULTIPLE>
190{
191    fn new(max_size: u32) -> TeeResult<Self> {
192        // Would that we could make these static asserts directly in the
193        // definition of the type, or out-of-line next to it.
194        const { assert!((SIZE_MIN % SIZE_MULTIPLE) == 0) };
195        const { assert!((SIZE_MAX % SIZE_MULTIPLE) == 0) };
196
197        if Self::is_valid_size(max_size) {
198            Ok(Self { secret: Vec::with_capacity((max_size / u8::BITS) as usize) })
199        } else {
200            Err(Error::NotSupported)
201        }
202    }
203
204    fn is_valid_size(size: u32) -> bool {
205        size >= SIZE_MIN && size <= SIZE_MAX && (size % SIZE_MULTIPLE) == 0
206    }
207
208    fn size(&self) -> u32 {
209        (self.secret.len() as u32) * u8::BITS
210    }
211
212    fn max_size(&self) -> u32 {
213        (self.secret.capacity() as u32) * u8::BITS
214    }
215
216    fn buffer_attribute(&self, id: AttributeId) -> Option<BufferAttribute<'_>> {
217        if id == AttributeId::SecretValue {
218            Some(BufferAttribute::Slice(&self.secret))
219        } else {
220            None
221        }
222    }
223
224    fn reset(&mut self) {
225        self.secret.clear();
226    }
227
228    fn populate(&mut self, attributes: &[Attribute]) -> TeeResult {
229        debug_assert!(self.secret.is_empty());
230
231        let mut secret: &[u8] = &[];
232        extract_attributes!(
233            attributes,
234            AttributeId::SecretValue => secret
235        )
236        .unwrap();
237        assert!(!secret.is_empty(), "Missing attribute for secret value");
238
239        assert!(secret.len() <= self.secret.capacity());
240        self.secret.extend_from_slice(secret);
241        Ok(())
242    }
243
244    fn generate(&mut self, size: u32, params: &[Attribute]) -> TeeResult {
245        assert!(Self::is_valid_size(size));
246        assert!(size <= self.max_size());
247        if !params.is_empty() {
248            return Err(Error::BadParameters);
249        }
250        self.secret.resize((size / u8::BITS) as usize, 0);
251        zx::cprng_draw(self.secret.as_mut_slice());
252        Ok(())
253    }
254}
255
256pub type AesKey = SimpleSymmetricKey<128, 256, 64>; // 128, 192, or 256
257pub type HmacSha1Key = SimpleSymmetricKey<80, 512, 8>;
258pub type HmacSha224Key = SimpleSymmetricKey<112, 512, 8>;
259pub type HmacSha256Key = SimpleSymmetricKey<192, 1024, 8>;
260pub type HmacSha384Key = SimpleSymmetricKey<256, 512, 8>;
261pub type HmacSha512Key = SimpleSymmetricKey<256, 512, 8>;
262
263pub struct RsaKeypair {
264    private: Option<Rc<RsaPrivateKey>>,
265    max_size: u32,
266}
267
268impl RsaKeypair {
269    pub fn private_key(&self) -> Rc<RsaPrivateKey> {
270        self.private.as_ref().unwrap().clone()
271    }
272}
273
274// A deep clone implementation as we don't want to the lifetimes of copied keys
275// to be tied to their originals.
276impl Clone for RsaKeypair {
277    fn clone(&self) -> Self {
278        let max_size = self.max_size;
279        if let Some(private) = &self.private {
280            Self { private: Some(Rc::new(private.deref().clone())), max_size }
281        } else {
282            Self { private: None, max_size }
283        }
284    }
285}
286
287impl KeyType for RsaKeypair {
288    fn new(max_size: u32) -> TeeResult<Self> {
289        if !Self::is_valid_size(max_size) {
290            return Err(Error::NotSupported);
291        }
292        Ok(Self { private: None, max_size })
293    }
294
295    fn is_valid_size(size: u32) -> bool {
296        (size % u8::BITS) == 0 && 512 <= size && size <= 4096
297    }
298
299    fn size(&self) -> u32 {
300        if let Some(private) = &self.private { (private.size() as u32) * u8::BITS } else { 0 }
301    }
302
303    fn max_size(&self) -> u32 {
304        self.max_size
305    }
306
307    fn buffer_attribute(&self, id: AttributeId) -> Option<BufferAttribute<'_>> {
308        let Some(private) = &self.private else {
309            return None;
310        };
311        match id {
312            AttributeId::RsaModulus => Some(BufferAttribute::Vector(private.n().to_bytes_be())),
313            AttributeId::RsaPublicExponent => {
314                Some(BufferAttribute::Vector(private.e().to_bytes_be()))
315            }
316            AttributeId::RsaPrivateExponent => {
317                Some(BufferAttribute::Vector(private.d().to_bytes_be()))
318            }
319            AttributeId::RsaPrime1 => {
320                Some(BufferAttribute::Vector(private.primes()[0].to_bytes_be()))
321            }
322            AttributeId::RsaPrime2 => {
323                Some(BufferAttribute::Vector(private.primes()[1].to_bytes_be()))
324            }
325            AttributeId::RsaExponent1 => {
326                Some(BufferAttribute::Vector(private.dp().unwrap().to_bytes_be()))
327            }
328            AttributeId::RsaExponent2 => {
329                Some(BufferAttribute::Vector(private.dq().unwrap().to_bytes_be()))
330            }
331            AttributeId::RsaCoefficient => {
332                Some(BufferAttribute::Vector(private.crt_coefficient().unwrap().to_bytes_be()))
333            }
334            _ => None,
335        }
336    }
337
338    fn reset(&mut self) {
339        self.private = None;
340    }
341
342    fn populate(&mut self, attributes: &[Attribute]) -> TeeResult {
343        assert!(self.private.is_none());
344
345        let mut modulus: &[u8] = &[];
346        let mut public_exponent: &[u8] = &[];
347        let mut private_exponent: &[u8] = &[];
348        let mut prime1: &[u8] = &[];
349        let mut prime2: &[u8] = &[];
350        let mut exponent1: &[u8] = &[];
351        let mut exponent2: &[u8] = &[];
352        let mut coefficient: &[u8] = &[];
353        extract_attributes!(
354            attributes,
355            AttributeId::RsaModulus => modulus,
356            AttributeId::RsaPublicExponent => public_exponent,
357            AttributeId::RsaPrivateExponent => private_exponent,
358            AttributeId::RsaPrime1 => prime1,
359            AttributeId::RsaPrime2 => prime2,
360            AttributeId::RsaExponent1 => exponent1,
361            AttributeId::RsaExponent2 => exponent2,
362            AttributeId::RsaCoefficient => coefficient
363        )
364        .unwrap();
365        assert!(!modulus.is_empty(), "Missing attribute for RSA modulus");
366        assert!(!public_exponent.is_empty(), "Missing attribute for RSA public exponent");
367        assert!(!private_exponent.is_empty(), "Missing attribute for RSA private exponent");
368
369        if !prime1.is_empty()
370            || prime2.is_empty()
371            || !exponent1.is_empty()
372            || !exponent2.is_empty()
373            || !coefficient.is_empty()
374        {
375            assert!(
376                !prime1.is_empty(),
377                "TEE_ATTR_RSA_PRIME1 is required if another CRT attribute is provided"
378            );
379            assert!(
380                !prime2.is_empty(),
381                "TEE_ATTR_RSA_PRIME2 is required if another CRT attribute is provided"
382            );
383            assert!(
384                !exponent1.is_empty(),
385                "TEE_ATTR_RSA_EXPONENT1 is required if another CRT attribute is provided"
386            );
387            assert!(
388                !exponent2.is_empty(),
389                "TEE_ATTR_RSA_EXPONENT2 is required if another CRT attribute is provided"
390            );
391            assert!(
392                !coefficient.is_empty(),
393                "TEE_ATTR_RSA_COEFFICIENT is required if another CRT attribute is provided"
394            );
395        }
396
397        let len: u32 = modulus.len().try_into().unwrap();
398        assert!(u8::BITS * len <= self.max_size());
399
400        let mut private_key = RsaPrivateKey::from_components(
401            BigUint::from_bytes_be(modulus),
402            BigUint::from_bytes_be(public_exponent),
403            BigUint::from_bytes_be(private_exponent),
404            vec![BigUint::from_bytes_be(prime1), BigUint::from_bytes_be(prime2)],
405        )
406        .map_err(|_| Error::BadParameters)?;
407
408        // Computes and populates the CRT coefficients accessed below and
409        // possibly in subsequent key use.
410        private_key.precompute().unwrap();
411
412        if !exponent1.is_empty() {
413            if *private_key.dp().unwrap() != BigUint::from_bytes_be(exponent1) {
414                return Err(Error::BadParameters);
415            }
416            if *private_key.dq().unwrap() != BigUint::from_bytes_be(exponent2) {
417                return Err(Error::BadParameters);
418            }
419            if private_key.crt_coefficient().unwrap() != BigUint::from_bytes_be(coefficient) {
420                return Err(Error::BadParameters);
421            }
422        }
423
424        self.private = Some(Rc::new(private_key));
425        Ok(())
426    }
427
428    fn generate(&mut self, size: u32, params: &[Attribute]) -> TeeResult {
429        assert!(Self::is_valid_size(size));
430        assert!(size <= self.max_size());
431        assert!(self.private.is_none());
432
433        let mut public_exponent: &[u8] = &[];
434        extract_attributes!(params, AttributeId::RsaPublicExponent => public_exponent)
435            .map_err(|_| Error::BadParameters)?;
436
437        let mut private_key = if public_exponent.is_empty() {
438            RsaPrivateKey::new(&mut Rng {}, size as usize)
439        } else {
440            RsaPrivateKey::new_with_exp(
441                &mut Rng {},
442                size as usize,
443                &BigUint::from_bytes_be(public_exponent),
444            )
445        }
446        .unwrap();
447
448        // Computes and populates the CRT coefficients accessed below and
449        // possibly in subsequent key use.
450        private_key.precompute().unwrap();
451
452        self.private = Some(Rc::new(private_key));
453
454        Ok(())
455    }
456}
457
458#[derive(Clone)]
459pub struct EccKeypair {
460    secret: Option<Box<P256SecretKey>>,
461}
462
463// Only NIST P-256 curves are supported at this time.
464impl KeyType for EccKeypair {
465    fn new(max_size: u32) -> TeeResult<Self> {
466        if !Self::is_valid_size(max_size) {
467            return Err(Error::NotSupported);
468        }
469        Ok(Self { secret: None })
470    }
471
472    fn is_valid_size(size: u32) -> bool {
473        size == 256
474    }
475
476    fn size(&self) -> u32 {
477        256
478    }
479
480    fn max_size(&self) -> u32 {
481        256
482    }
483
484    fn buffer_attribute(&self, id: AttributeId) -> Option<BufferAttribute<'_>> {
485        let Some(secret) = &self.secret else {
486            return None;
487        };
488        match id {
489            AttributeId::EccPrivateValue => {
490                Some(BufferAttribute::Vector(secret.to_be_bytes().as_slice().to_vec()))
491            }
492            AttributeId::EccPublicValueX => Some(BufferAttribute::Vector(
493                secret
494                    .public_key()
495                    .as_affine()
496                    .to_encoded_point(/*compress=*/ false)
497                    .x()
498                    .unwrap()
499                    .as_slice()
500                    .to_vec(),
501            )),
502            AttributeId::EccPublicValueY => Some(BufferAttribute::Vector(
503                secret
504                    .public_key()
505                    .as_affine()
506                    .to_encoded_point(/*compress=*/ false)
507                    .y()
508                    .unwrap()
509                    .as_slice()
510                    .to_vec(),
511            )),
512            _ => None,
513        }
514    }
515
516    fn value_attribute(&self, id: AttributeId) -> Option<ValueFields> {
517        match id {
518            AttributeId::EccCurve => Some(ValueFields { a: EccCurve::NistP256 as u32, b: 0 }),
519            _ => None,
520        }
521    }
522
523    fn reset(&mut self) {
524        self.secret = None;
525    }
526
527    fn populate(&mut self, attributes: &[Attribute]) -> TeeResult {
528        assert!(self.secret.is_none());
529
530        let mut private_value: &[u8] = &[];
531        let mut public_value_x: &[u8] = &[];
532        let mut public_value_y: &[u8] = &[];
533        let mut curve: Option<ValueFields> = None;
534        extract_attributes!(
535            attributes,
536            AttributeId::EccPrivateValue => private_value,
537            AttributeId::EccPublicValueX => public_value_x,
538            AttributeId::EccPublicValueY => public_value_y,
539            AttributeId::EccCurve => curve
540        )
541        .unwrap();
542        assert!(!private_value.is_empty(), "Missing attribute for ECC private value");
543        assert!(!public_value_x.is_empty(), "Missing attribute for ECC public value X");
544        assert!(!public_value_y.is_empty(), "Missing attribute for ECC public value Y");
545        assert!(curve.is_some(), "Missing attribute for ECC curve");
546
547        let curve = EccCurve::from_u32(curve.unwrap().a).ok_or(Error::NotSupported)?;
548        if curve != EccCurve::NistP256 {
549            return Err(Error::NotSupported);
550        }
551
552        let secret = P256SecretKey::from_be_bytes(private_value).unwrap();
553
554        // Check that provided public parameters coincide with those computed
555        // by the private key abstraction.
556        let point = secret.public_key().as_affine().to_encoded_point(/*compress=*/ false);
557        if point.x().unwrap().as_slice() != public_value_x {
558            return Err(Error::BadParameters);
559        }
560        if point.y().unwrap().as_slice() != public_value_y {
561            return Err(Error::BadParameters);
562        }
563        self.secret = Some(Box::new(secret));
564        Ok(())
565    }
566
567    fn generate(&mut self, size: u32, params: &[Attribute]) -> TeeResult {
568        assert!(Self::is_valid_size(size));
569        assert!(size <= self.max_size());
570        assert!(self.secret.is_none());
571
572        let mut curve: Option<ValueFields> = None;
573        extract_attributes!(params, AttributeId::EccCurve => curve)
574            .map_err(|_| Error::BadParameters)?;
575        assert!(curve.is_some(), "Missing attribute for ECC curve");
576
577        let curve = EccCurve::from_u32(curve.unwrap().a).ok_or(Error::NotSupported)?;
578        if curve != EccCurve::NistP256 {
579            return Err(Error::NotSupported);
580        }
581
582        self.secret = Some(Box::new(P256SecretKey::random(&mut Rng {})));
583        Ok(())
584    }
585}
586
587#[derive(Clone)]
588pub struct NoKey {}
589
590impl KeyType for NoKey {
591    fn new(max_size: u32) -> TeeResult<Self> {
592        if max_size == 0 { Ok(Self {}) } else { Err(Error::NotSupported) }
593    }
594
595    fn is_valid_size(size: u32) -> bool {
596        size == 0
597    }
598
599    fn reset(&mut self) {}
600
601    fn populate(&mut self, attributes: &[Attribute]) -> TeeResult {
602        assert!(attributes.is_empty());
603        Ok(())
604    }
605
606    fn generate(&mut self, size: u32, params: &[Attribute]) -> TeeResult {
607        assert_eq!(size, 0);
608        assert!(params.is_empty());
609        Ok(())
610    }
611}
612
613/// A cryptographic key (or key pair).
614#[derive(Clone)]
615pub enum Key {
616    Aes(AesKey),
617    HmacSha1(HmacSha1Key),
618    HmacSha224(HmacSha224Key),
619    HmacSha256(HmacSha256Key),
620    HmacSha384(HmacSha384Key),
621    HmacSha512(HmacSha512Key),
622    RsaKeypair(RsaKeypair),
623    EcdsaKeypair(EccKeypair),
624    EcdhKeypair(EccKeypair),
625    Data(NoKey),
626}
627
628// Reduces boilerplate a little.
629macro_rules! get_key_variant {
630    ($key:ident) => {
631        match $key {
632            Key::Aes(key) => key,
633            Key::HmacSha1(key) => key,
634            Key::HmacSha224(key) => key,
635            Key::HmacSha256(key) => key,
636            Key::HmacSha384(key) => key,
637            Key::HmacSha512(key) => key,
638            Key::RsaKeypair(key) => key,
639            Key::EcdsaKeypair(key) => key,
640            Key::EcdhKeypair(key) => key,
641            Key::Data(key) => key,
642        }
643    };
644}
645
646impl Key {
647    pub fn new(type_: Type, max_size: u32) -> TeeResult<Key> {
648        match type_ {
649            Type::Aes => AesKey::new(max_size).map(Self::Aes),
650            Type::HmacSha1 => HmacSha1Key::new(max_size).map(Self::HmacSha1),
651            Type::HmacSha224 => HmacSha224Key::new(max_size).map(Self::HmacSha224),
652            Type::HmacSha256 => HmacSha256Key::new(max_size).map(Self::HmacSha256),
653            Type::HmacSha384 => HmacSha384Key::new(max_size).map(Self::HmacSha384),
654            Type::HmacSha512 => HmacSha512Key::new(max_size).map(Self::HmacSha512),
655            Type::RsaKeypair => RsaKeypair::new(max_size).map(Self::RsaKeypair),
656            Type::EcdsaKeypair => EccKeypair::new(max_size).map(Self::EcdsaKeypair),
657            Type::EcdhKeypair => EccKeypair::new(max_size).map(Self::EcdhKeypair),
658            Type::Data => NoKey::new(max_size).map(Self::Data),
659            _ => Err(Error::NotSupported),
660        }
661    }
662
663    pub fn get_type(&self) -> Type {
664        match self {
665            Key::Aes(_) => Type::Aes,
666            Key::HmacSha1(_) => Type::HmacSha1,
667            Key::HmacSha224(_) => Type::HmacSha224,
668            Key::HmacSha256(_) => Type::HmacSha256,
669            Key::HmacSha384(_) => Type::HmacSha384,
670            Key::HmacSha512(_) => Type::HmacSha512,
671            Key::RsaKeypair(_) => Type::RsaKeypair,
672            Key::EcdsaKeypair(_) => Type::EcdsaKeypair,
673            Key::EcdhKeypair(_) => Type::EcdhKeypair,
674            Key::Data(_) => Type::Data,
675        }
676    }
677}
678
679impl Deref for Key {
680    type Target = dyn KeyType;
681
682    fn deref(&self) -> &Self::Target {
683        get_key_variant!(self)
684    }
685}
686
687impl DerefMut for Key {
688    fn deref_mut(&mut self) -> &mut Self::Target {
689        get_key_variant!(self)
690    }
691}
692
693// The common object abstraction implemented by transient and persistent
694// storage objects.
695pub trait Object {
696    fn key(&self) -> &Key;
697
698    fn usage(&self) -> &Usage;
699    fn usage_mut(&mut self) -> &mut Usage;
700
701    fn flags(&self) -> &HandleFlags;
702
703    fn restrict_usage(&mut self, restriction: Usage) {
704        let usage = self.usage_mut();
705        *usage = usage.intersection(restriction)
706    }
707
708    fn get_info(&self, data_size: usize, data_position: usize) -> ObjectInfo {
709        let all_info_flags = HandleFlags::PERSISTENT
710            | HandleFlags::INITIALIZED
711            | HandleFlags::DATA_ACCESS_READ
712            | HandleFlags::DATA_ACCESS_WRITE
713            | HandleFlags::DATA_ACCESS_WRITE_META
714            | HandleFlags::DATA_SHARE_READ
715            | HandleFlags::DATA_SHARE_WRITE;
716        let flags = self.flags().intersection(all_info_flags);
717        let key_size = self.key().size();
718        let object_size = if key_size > 0 { key_size } else { data_size.try_into().unwrap() };
719        ObjectInfo {
720            object_type: self.key().get_type(),
721            max_object_size: self.key().max_size(),
722            object_size,
723            object_usage: *self.usage(),
724            data_position: data_position,
725            data_size: data_size,
726            handle_flags: flags,
727        }
728    }
729}
730
731struct TransientObject {
732    key: Key,
733    usage: Usage,
734    flags: HandleFlags,
735}
736
737impl TransientObject {
738    fn new(key: Key) -> Self {
739        TransientObject { key, usage: Usage::default(), flags: HandleFlags::empty() }
740    }
741}
742
743impl Object for TransientObject {
744    fn key(&self) -> &Key {
745        &self.key
746    }
747
748    fn usage(&self) -> &Usage {
749        &self.usage
750    }
751    fn usage_mut(&mut self) -> &mut Usage {
752        &mut self.usage
753    }
754
755    fn flags(&self) -> &HandleFlags {
756        &self.flags
757    }
758}
759
760// A class abstraction implementing the transient storage interface.
761struct TransientObjects {
762    by_handle: HashMap<ObjectHandle, Rc<RefCell<TransientObject>>>,
763    next_handle_value: u64,
764}
765
766impl TransientObjects {
767    fn new() -> Self {
768        Self {
769            by_handle: HashMap::new(),
770            // Always even, per the described convention above - also non-null.
771            next_handle_value: 2,
772        }
773    }
774
775    fn allocate(&mut self, type_: Type, max_size: u32) -> TeeResult<ObjectHandle> {
776        let key = Key::new(type_, max_size)?;
777        let handle = self.mint_handle();
778        let prev =
779            self.by_handle.insert(handle.clone(), Rc::new(RefCell::new(TransientObject::new(key))));
780        debug_assert!(prev.is_none());
781
782        Ok(handle)
783    }
784
785    fn free(&mut self, handle: ObjectHandle) {
786        if handle.is_null() {
787            return;
788        }
789        match self.by_handle.entry(handle) {
790            HashMapEntry::Occupied(entry) => {
791                let _ = entry.remove();
792            }
793            HashMapEntry::Vacant(_) => panic!("{handle:?} is not a valid handle"),
794        }
795    }
796
797    fn reset(&self, handle: ObjectHandle) {
798        match self.by_handle.get(&handle) {
799            Some(obj) => {
800                let mut obj = obj.borrow_mut();
801                obj.flags.remove(HandleFlags::INITIALIZED);
802                obj.key.reset()
803            }
804            None => panic!("{handle:?} is not a valid handle"),
805        }
806    }
807
808    fn populate(&self, handle: ObjectHandle, attributes: &[Attribute]) -> TeeResult {
809        match self.by_handle.get(&handle) {
810            Some(obj) => {
811                let mut obj = obj.borrow_mut();
812                assert!(
813                    !obj.flags.contains(HandleFlags::INITIALIZED),
814                    "{handle:?} is already initialized"
815                );
816                obj.flags.insert(HandleFlags::INITIALIZED);
817                obj.key.populate(attributes)
818            }
819            None => panic!("{handle:?} is not a valid handle"),
820        }
821    }
822
823    fn generate_key(&self, handle: ObjectHandle, size: u32, params: &[Attribute]) -> TeeResult {
824        match self.by_handle.get(&handle) {
825            Some(obj) => {
826                let mut obj = obj.borrow_mut();
827                assert!(
828                    !obj.flags.contains(HandleFlags::INITIALIZED),
829                    "{handle:?} is already initialized"
830                );
831                obj.flags.insert(HandleFlags::INITIALIZED);
832                obj.key.generate(size, params)
833            }
834            None => panic!("{handle:?} is not a valid handle"),
835        }
836    }
837
838    // Returns a shared reference to the associated object, if `handle` is
839    // valid; panics otherwise.
840    fn get(&self, handle: ObjectHandle) -> Ref<'_, TransientObject> {
841        self.by_handle
842            .get(&handle)
843            .unwrap_or_else(|| panic!("{handle:?} is not a valid handle"))
844            .borrow()
845    }
846
847    // Returns an exclusive reference to the associated object view, if `handle` is
848    // valid; panics otherwise.
849    fn get_mut(&self, handle: ObjectHandle) -> RefMut<'_, TransientObject> {
850        self.by_handle
851            .get(&handle)
852            .unwrap_or_else(|| panic!("{handle:?} is not a valid handle"))
853            .borrow_mut()
854    }
855
856    fn mint_handle(&mut self) -> ObjectHandle {
857        let handle_value = self.next_handle_value;
858        self.next_handle_value += 2;
859        ObjectHandle::from_value(handle_value)
860    }
861}
862
863struct PersistentObject {
864    key: Key,
865    usage: Usage,
866    base_flags: HandleFlags,
867    data: zx::Vmo,
868    data_size: usize,
869    id: Vec<u8>,
870
871    // The open handles to this object. Tracking these in this way conveniently
872    // enables their invalidation in the case of object overwriting.
873    handles: HashSet<ObjectHandle>,
874}
875
876impl Object for PersistentObject {
877    fn key(&self) -> &Key {
878        &self.key
879    }
880
881    fn usage(&self) -> &Usage {
882        &self.usage
883    }
884    fn usage_mut(&mut self) -> &mut Usage {
885        &mut self.usage
886    }
887
888    fn flags(&self) -> &HandleFlags {
889        &self.base_flags
890    }
891}
892
893// A handle's view into a persistent object.
894struct PersistentObjectView {
895    object: Rc<RefCell<PersistentObject>>,
896    flags: HandleFlags,
897    data_position: usize,
898}
899
900impl PersistentObjectView {
901    fn get_info(&self) -> ObjectInfo {
902        let obj = self.object.borrow();
903        obj.get_info(obj.data_size, self.data_position)
904    }
905
906    // See read_object_data().
907    fn read_data<'a>(&mut self, buffer: &'a mut [u8]) -> TeeResult<&'a [u8]> {
908        let obj = self.object.borrow();
909        let read_size = min(obj.data_size - self.data_position, buffer.len());
910        let written = &mut buffer[..read_size];
911        if read_size > 0 {
912            obj.data.read(written, self.data_position as u64).unwrap();
913        }
914        self.data_position += read_size;
915        Ok(written)
916    }
917
918    // See write_object_data().
919    fn write_data(&mut self, data: &[u8]) -> TeeResult {
920        if data.is_empty() {
921            return Ok(());
922        }
923        let mut obj = self.object.borrow_mut();
924        let write_end = self.data_position + data.len();
925
926        if write_end > DATA_MAX_POSITION {
927            return Err(Error::Overflow);
928        }
929        if write_end > obj.data_size {
930            obj.data.set_size(write_end as u64).unwrap();
931            obj.data_size = write_end;
932        }
933        obj.data.write(data, self.data_position as u64).unwrap();
934        self.data_position = write_end;
935        Ok(())
936    }
937
938    // See truncate_object_data().
939    fn truncate_data(&self, size: usize) -> TeeResult {
940        let mut obj = self.object.borrow_mut();
941
942        // It's okay to set the size past the position in either direction.
943        // However, the spec does not actually cover the case where the
944        // provided size is is larger than DATA_MAX_POSITION. Since any
945        // part of the data stream past that would be inaccessible; it
946        // should be sensible and harmless to not exceed that in resizing.
947        let size = min(size, DATA_MAX_POSITION);
948        obj.data.set_size(size as u64).unwrap();
949        obj.data_size = size;
950        Ok(())
951    }
952
953    // See seek_object_data().
954    fn seek_data(&mut self, offset: isize, whence: Whence) -> TeeResult {
955        let start = match whence {
956            Whence::DataSeekCur => self.data_position,
957            Whence::DataSeekEnd => self.object.borrow().data_size,
958            Whence::DataSeekSet => 0,
959        };
960        let new_position = start.saturating_add_signed(offset);
961        if new_position > DATA_MAX_POSITION {
962            Err(Error::Overflow)
963        } else {
964            self.data_position = new_position;
965            Ok(())
966        }
967    }
968}
969
970// The state of an object enum handle.
971struct EnumState {
972    // None if in the allocated/unstarted state.
973    id: Option<Vec<u8>>,
974}
975
976// A B-tree since enumeration needs to deal in key (i.e., ID) ordering.
977//
978// Further, the key represents a separately owned copy of the ID; we do this
979// instead of representing the key as an Rc<Vec<u8>> as then we would no
980// longer be able to perform look-up with slices - since Borrow is not
981// implemented for Rc - and would instead have to dynamically allocate a new
982// key for the look-up. Better to not touch the heap when bad inputs are
983// provided.
984type PersistentIdMap = BTreeMap<Vec<u8>, Rc<RefCell<PersistentObject>>>;
985
986type PersistentHandleMap = HashMap<ObjectHandle, RefCell<PersistentObjectView>>;
987type PersistentEnumHandleMap = HashMap<ObjectEnumHandle, RefCell<EnumState>>;
988
989// A class abstraction implementing the persistent storage interface.
990struct PersistentObjects {
991    by_id: PersistentIdMap,
992    by_handle: PersistentHandleMap,
993    enum_handles: PersistentEnumHandleMap,
994    next_handle_value: u64,
995    next_enum_handle_value: u64,
996}
997
998impl PersistentObjects {
999    fn new() -> Self {
1000        Self {
1001            by_id: PersistentIdMap::new(),
1002            by_handle: PersistentHandleMap::new(),
1003            enum_handles: HashMap::new(),
1004            next_handle_value: 1, // Always odd, per the described convention above
1005            next_enum_handle_value: 1,
1006        }
1007    }
1008
1009    fn create(
1010        &mut self,
1011        key: Key,
1012        usage: Usage,
1013        flags: HandleFlags,
1014        id: &[u8],
1015        initial_data: &[u8],
1016    ) -> TeeResult<ObjectHandle> {
1017        assert!(id.len() <= OBJECT_ID_MAX_LEN);
1018
1019        let data = zx::Vmo::create_with_opts(zx::VmoOptions::RESIZABLE, initial_data.len() as u64)
1020            .unwrap();
1021        if !initial_data.is_empty() {
1022            data.write(initial_data, 0).unwrap();
1023        }
1024
1025        let flags = flags.union(HandleFlags::PERSISTENT | HandleFlags::INITIALIZED);
1026
1027        let obj = PersistentObject {
1028            key,
1029            usage,
1030            base_flags: flags,
1031            data,
1032            data_size: initial_data.len(),
1033            id: Vec::from(id),
1034            handles: HashSet::new(),
1035        };
1036
1037        let obj_ref = match self.by_id.get(id) {
1038            // If there's already an object with that ID, then
1039            // DATA_FLAG_OVERWRITE permits overwriting. This results in
1040            // existing handles being invalidated.
1041            Some(obj_ref) => {
1042                if !flags.contains(HandleFlags::DATA_FLAG_OVERWRITE) {
1043                    return Err(Error::AccessConflict);
1044                }
1045                {
1046                    let mut obj_old = obj_ref.borrow_mut();
1047                    for handle in obj_old.handles.iter() {
1048                        let removed = self.by_handle.remove(&handle).is_some();
1049                        debug_assert!(removed);
1050                    }
1051                    *obj_old = obj;
1052                }
1053                obj_ref.clone()
1054            }
1055            None => {
1056                let id = obj.id.clone();
1057                let obj_ref = Rc::new(RefCell::new(obj));
1058                let inserted = self.by_id.insert(id, obj_ref.clone());
1059                debug_assert!(inserted.is_none());
1060                obj_ref
1061            }
1062        };
1063        Ok(self.open_internal(obj_ref, flags))
1064    }
1065
1066    // See open_persistent_object().
1067    fn open(&mut self, id: &[u8], flags: HandleFlags) -> TeeResult<ObjectHandle> {
1068        assert!(id.len() <= OBJECT_ID_MAX_LEN);
1069
1070        let obj_ref = match self.by_id.get(id) {
1071            Some(obj_ref) => Ok(obj_ref),
1072            None => Err(Error::ItemNotFound),
1073        }?;
1074
1075        {
1076            let mut obj = obj_ref.borrow_mut();
1077
1078            // At any given time, the number of object references should be
1079            // greater than or equal to the number of handle map values + the
1080            // number of object ID map values, which should be equal to the #
1081            // of open handles to that object + 1.
1082            debug_assert!(Rc::strong_count(obj_ref) >= obj.handles.len() + 1);
1083
1084            // If we previously closed the last handle to the object and are
1085            // now reopening its first active handle, overwrite the base flags
1086            // with the handle's. The spec doesn't dictate this, but it's hard
1087            // to imagine what else an implementation could or should do in
1088            // this case.
1089            if obj.handles.is_empty() {
1090                obj.base_flags = flags.union(HandleFlags::PERSISTENT | HandleFlags::INITIALIZED);
1091            } else {
1092                let combined = flags.union(obj.base_flags);
1093                let intersection = flags.intersection(obj.base_flags);
1094
1095                // Check for shared read permissions.
1096                if flags.contains(HandleFlags::DATA_ACCESS_READ)
1097                    && !(intersection.contains(HandleFlags::DATA_SHARE_READ))
1098                {
1099                    return Err(Error::AccessConflict);
1100                }
1101
1102                // Check for shared read permission consistency.
1103                if combined.contains(HandleFlags::DATA_SHARE_READ)
1104                    == intersection.contains(HandleFlags::DATA_SHARE_READ)
1105                {
1106                    return Err(Error::AccessConflict);
1107                }
1108
1109                // Check for shared write permissions.
1110                if flags.contains(HandleFlags::DATA_ACCESS_WRITE)
1111                    && !(intersection.contains(HandleFlags::DATA_SHARE_WRITE))
1112                {
1113                    return Err(Error::AccessConflict);
1114                }
1115
1116                // Check for shared write permission consistency.
1117                if combined.contains(HandleFlags::DATA_SHARE_WRITE)
1118                    == intersection.contains(HandleFlags::DATA_SHARE_WRITE)
1119                {
1120                    return Err(Error::AccessConflict);
1121                }
1122            }
1123        }
1124
1125        Ok(self.open_internal(obj_ref.clone(), flags))
1126    }
1127
1128    // The common handle opening subroutine of create() and open(), which
1129    // expects that the operation has been validated.
1130    fn open_internal(
1131        &mut self,
1132        object: Rc<RefCell<PersistentObject>>,
1133        flags: HandleFlags,
1134    ) -> ObjectHandle {
1135        let handle = self.mint_handle();
1136        let inserted = object.borrow_mut().handles.insert(handle);
1137        debug_assert!(inserted);
1138        let view = PersistentObjectView { object, flags, data_position: 0 };
1139        let inserted = self.by_handle.insert(handle, RefCell::new(view)).is_none();
1140        debug_assert!(inserted);
1141        handle
1142    }
1143
1144    fn close(&mut self, handle: ObjectHandle) {
1145        // Note that even if all handle map entries associated with the object
1146        // are removed, the reference to the object in the ID map remains,
1147        // keeping it alive for future open() calls.
1148        match self.by_handle.entry(handle) {
1149            HashMapEntry::Occupied(entry) => {
1150                {
1151                    let view = entry.get().borrow_mut();
1152                    let mut obj = view.object.borrow_mut();
1153                    let removed = obj.handles.remove(&handle);
1154                    debug_assert!(removed);
1155                }
1156                let _ = entry.remove();
1157            }
1158            HashMapEntry::Vacant(_) => panic!("{handle:?} is not a valid handle"),
1159        }
1160    }
1161
1162    // See close_and_delete_persistent_object(). Although unlike that function,
1163    // this one returns Error::AccessDenied if `handle` was not opened with
1164    // DATA_ACCESS_WRITE_META.
1165    fn close_and_delete(&mut self, handle: ObjectHandle) -> TeeResult {
1166        // With both maps locked, removal of all entries with the associated
1167        // object handle should amount to dropping that object.
1168        match self.by_handle.entry(handle) {
1169            HashMapEntry::Occupied(entry) => {
1170                {
1171                    let state = entry.get().borrow();
1172                    if !state.flags.contains(HandleFlags::DATA_ACCESS_WRITE_META) {
1173                        return Err(Error::AccessDenied);
1174                    }
1175                    let obj = state.object.borrow();
1176                    debug_assert_eq!(obj.handles.len(), 1);
1177                    let removed = self.by_id.remove(&obj.id).is_some();
1178                    debug_assert!(removed);
1179                }
1180                let _ = entry.remove();
1181                Ok(())
1182            }
1183            HashMapEntry::Vacant(_) => panic!("{handle:?} is not a valid handle"),
1184        }
1185    }
1186
1187    // See rename_persistent_object(). Although unlike that function, this one
1188    // returns Error::AccessDenied if `handle` was not opened with
1189    // DATA_ACCESS_WRITE_META.
1190    fn rename(&mut self, handle: ObjectHandle, new_id: &[u8]) -> TeeResult {
1191        match self.by_handle.entry(handle) {
1192            HashMapEntry::Occupied(handle_entry) => {
1193                let state = handle_entry.get().borrow();
1194                if !state.flags.contains(HandleFlags::DATA_ACCESS_WRITE_META) {
1195                    return Err(Error::AccessDenied);
1196                }
1197                let new_id = Vec::from(new_id);
1198                match self.by_id.entry(new_id.clone()) {
1199                    BTreeMapEntry::Occupied(_) => return Err(Error::AccessConflict),
1200                    BTreeMapEntry::Vacant(id_entry) => {
1201                        let _ = id_entry.insert(state.object.clone());
1202                    }
1203                };
1204                let mut obj = state.object.borrow_mut();
1205                let removed = self.by_id.remove(&obj.id);
1206                debug_assert!(removed.is_some());
1207                obj.id = new_id;
1208                Ok(())
1209            }
1210            HashMapEntry::Vacant(_) => panic!("{handle:?} is not a valid handle"),
1211        }
1212    }
1213
1214    // Returns a shared reference to the associated object view, if `handle` is
1215    // valid; panics otherwise.
1216    fn get(&self, handle: ObjectHandle) -> Ref<'_, PersistentObjectView> {
1217        self.by_handle
1218            .get(&handle)
1219            .unwrap_or_else(|| panic!("{handle:?} is not a valid handle"))
1220            .borrow()
1221    }
1222
1223    // Returns an exclusive reference to the associated object view, if `handle` is
1224    // valid; panics otherwise.
1225    fn get_mut(&self, handle: ObjectHandle) -> RefMut<'_, PersistentObjectView> {
1226        self.by_handle
1227            .get(&handle)
1228            .unwrap_or_else(|| panic!("{handle:?} is not a valid handle"))
1229            .borrow_mut()
1230    }
1231
1232    // See allocate_persistent_object_enumerator().
1233    fn allocate_enumerator(&mut self) -> ObjectEnumHandle {
1234        let enumerator = self.mint_enumerator_handle();
1235
1236        let previous =
1237            self.enum_handles.insert(enumerator.clone(), RefCell::new(EnumState { id: None }));
1238        debug_assert!(previous.is_none());
1239        enumerator
1240    }
1241
1242    // See free_persistent_object_enumerator().
1243    fn free_enumerator(&mut self, enumerator: ObjectEnumHandle) -> () {
1244        match self.enum_handles.entry(enumerator) {
1245            HashMapEntry::Occupied(entry) => {
1246                let _ = entry.remove();
1247            }
1248            HashMapEntry::Vacant(_) => panic!("{enumerator:?} is not a valid enumerator handle"),
1249        }
1250    }
1251
1252    // See reset_persistent_object_enumerator().
1253    fn reset_enumerator(&mut self, enumerator: ObjectEnumHandle) -> () {
1254        match self.enum_handles.get(&enumerator) {
1255            Some(state) => {
1256                state.borrow_mut().id = None;
1257            }
1258            None => panic!("{enumerator:?} is not a valid enumerator handle"),
1259        }
1260    }
1261
1262    // See get_next_persistent_object().
1263    fn get_next_object<'a>(
1264        &self,
1265        enumerator: ObjectEnumHandle,
1266        id_buffer: &'a mut [u8],
1267    ) -> TeeResult<(ObjectInfo, &'a [u8])> {
1268        match self.enum_handles.get(&enumerator) {
1269            Some(state) => {
1270                let mut state = state.borrow_mut();
1271                let next = if state.id.is_none() {
1272                    self.by_id.first_key_value()
1273                } else {
1274                    // Since we're dealing with an ID-keyed B-tree, we can
1275                    // straightforwardly get the first entry with an ID larger
1276                    // than the current.
1277                    let curr_id = state.id.as_ref().unwrap();
1278                    self.by_id.range((Bound::Excluded(curr_id.clone()), Bound::Unbounded)).next()
1279                };
1280                if let Some((id, obj)) = next {
1281                    assert!(id_buffer.len() >= id.len());
1282                    let written = &mut id_buffer[..id.len()];
1283                    written.copy_from_slice(id);
1284                    state.id = Some(id.clone());
1285                    Ok((obj.borrow().get_info(/*data_size=*/ 0, /*data_position=*/ 0), written))
1286                } else {
1287                    Err(Error::ItemNotFound)
1288                }
1289            }
1290            None => panic!("{enumerator:?} is not a valid enumerator handle"),
1291        }
1292    }
1293
1294    fn mint_handle(&mut self) -> ObjectHandle {
1295        // Per the described convention above, always odd. (Initial value is 1.)
1296        let handle_value = self.next_handle_value;
1297        self.next_handle_value += 2;
1298        ObjectHandle::from_value(handle_value)
1299    }
1300
1301    fn mint_enumerator_handle(&mut self) -> ObjectEnumHandle {
1302        let handle_value = self.next_enum_handle_value;
1303        self.next_enum_handle_value += 1;
1304        ObjectEnumHandle::from_value(handle_value)
1305    }
1306}
1307
1308//
1309// Implementation
1310//
1311
1312impl Storage {
1313    pub fn new() -> Self {
1314        Self {
1315            persistent_objects: PersistentObjects::new(),
1316            transient_objects: TransientObjects::new(),
1317        }
1318    }
1319
1320    pub fn get(&self, object: ObjectHandle) -> Rc<RefCell<dyn Object>> {
1321        if is_transient_handle(object) {
1322            self.transient_objects.by_handle.get(&object).unwrap().clone()
1323        } else {
1324            self.persistent_objects.by_handle.get(&object).unwrap().borrow().object.clone()
1325        }
1326    }
1327
1328    /// Returns info about an open object as well of the state of its handle.
1329    ///
1330    /// Panics if `object` is not a valid handle.
1331    pub fn get_object_info(&self, object: ObjectHandle) -> ObjectInfo {
1332        if is_transient_handle(object) {
1333            self.transient_objects
1334                .get(object)
1335                .get_info(/*data_size=*/ 0, /*data_position=*/ 0)
1336        } else {
1337            self.persistent_objects.get(object).get_info()
1338        }
1339    }
1340
1341    /// Restricts the usage of an open object handle.
1342    ///
1343    /// Panics if `object` is not a valid handle.
1344    pub fn restrict_object_usage(&self, object: ObjectHandle, usage: Usage) {
1345        if is_transient_handle(object) {
1346            self.transient_objects.get_mut(object).restrict_usage(usage)
1347        } else {
1348            self.persistent_objects.get(object).object.borrow_mut().restrict_usage(usage)
1349        }
1350    }
1351}
1352
1353impl Storage {
1354    /// Returns the requested buffer-type attribute associated with the given
1355    /// object, if any. It is written to the provided buffer and the size of
1356    /// what is written is returned.
1357    ///
1358    /// Returns a wrapped value of Error::ItemNotFound if the object does not have
1359    /// such an attribute.
1360    ///
1361    /// Returns a wrapped value of Error::ShortBuffer if the buffer was too small
1362    /// to read the attribute value into, along with the length of the attribute.
1363    ///
1364    /// Panics if `object` is not a valid handle or if `attribute_id` is not of
1365    /// buffer type.
1366    pub fn get_object_buffer_attribute(
1367        &self,
1368        object: ObjectHandle,
1369        attribute_id: AttributeId,
1370        buffer: &mut [u8],
1371    ) -> Result<usize, ErrorWithSize> {
1372        assert!(!attribute_id.value());
1373
1374        let copy_from_key = |obj: &dyn Object, buffer: &mut [u8]| -> Result<usize, ErrorWithSize> {
1375            if !attribute_id.public() {
1376                assert!(obj.usage().contains(Usage::EXTRACTABLE));
1377            }
1378
1379            let attr = obj.key().buffer_attribute(attribute_id);
1380            let bytes = match &attr {
1381                None => return Err(ErrorWithSize::new(Error::ItemNotFound)),
1382                Some(BufferAttribute::Slice(bytes)) => bytes,
1383                Some(BufferAttribute::Vector(bytes)) => bytes.as_slice(),
1384            };
1385            if buffer.len() < bytes.len() {
1386                Err(ErrorWithSize::short_buffer(bytes.len()))
1387            } else {
1388                let written = &mut buffer[..bytes.len()];
1389                written.copy_from_slice(bytes);
1390                Ok(written.len())
1391            }
1392        };
1393
1394        if is_transient_handle(object) {
1395            copy_from_key(self.transient_objects.get(object).deref(), buffer)
1396        } else {
1397            copy_from_key(
1398                self.persistent_objects.get(object).object.as_ref().borrow().deref(),
1399                buffer,
1400            )
1401        }
1402    }
1403
1404    /// Returns the requested value-type attribute associated with the given
1405    /// object, if any.
1406    ///
1407    /// Returns Error::ItemNotFound if the object does not have such an attribute.
1408    ///
1409    /// Panics if `object` is not a valid handle or if `attribute_id` is not of
1410    /// value type.
1411    pub fn get_object_value_attribute(
1412        &self,
1413        object: ObjectHandle,
1414        attribute_id: AttributeId,
1415    ) -> TeeResult<ValueFields> {
1416        assert!(!attribute_id.value());
1417
1418        let copy_from_key = |obj: &dyn Object| {
1419            if !attribute_id.public() {
1420                assert!(obj.usage().contains(Usage::EXTRACTABLE));
1421            }
1422            if let Some(value) = obj.key().value_attribute(attribute_id) {
1423                Ok(value)
1424            } else {
1425                Err(Error::ItemNotFound)
1426            }
1427        };
1428
1429        if is_transient_handle(object) {
1430            copy_from_key(self.transient_objects.get(object).deref())
1431        } else {
1432            copy_from_key(self.persistent_objects.get(object).object.borrow().deref())
1433        }
1434    }
1435
1436    /// Closes the given object handle.
1437    ///
1438    /// Panics if `object` is neither null or a valid handle.
1439    pub fn close_object(&mut self, object: ObjectHandle) {
1440        if object.is_null() {
1441            return;
1442        }
1443
1444        if is_transient_handle(object) {
1445            self.transient_objects.free(object)
1446        } else {
1447            self.persistent_objects.close(object)
1448        }
1449    }
1450
1451    /// Creates a new transient object of the given type and maximum key size.
1452    ///
1453    /// Returns Error::NotSupported if the type is unsupported or if the
1454    /// maximum key size is itself not a valid key size.
1455    pub fn allocate_transient_object(
1456        &mut self,
1457        object_type: Type,
1458        max_size: u32,
1459    ) -> TeeResult<ObjectHandle> {
1460        self.transient_objects.allocate(object_type, max_size)
1461    }
1462
1463    /// Destroys a transient object.
1464    ///
1465    /// Panics if `object` is not a valid transient object handle.
1466    pub fn free_transient_object(&mut self, object: ObjectHandle) {
1467        assert!(is_transient_handle(object));
1468        self.transient_objects.free(object)
1469    }
1470
1471    /// Resets a transient object back to its uninitialized state.
1472    ///
1473    /// Panics if `object` is not a valid transient object handle.
1474    pub fn reset_transient_object(&mut self, object: ObjectHandle) {
1475        assert!(is_transient_handle(object));
1476        self.transient_objects.reset(object)
1477    }
1478
1479    /// Populates the key information of a transient object from a given list
1480    /// of attributes.
1481    ///
1482    /// Panics if `object` is not a valid transient object handle, or if
1483    /// `attrs` omits required attributes or includes unrelated ones.
1484    pub fn populate_transient_object(
1485        &self,
1486        object: ObjectHandle,
1487        attrs: &[Attribute],
1488    ) -> TeeResult {
1489        assert!(is_transient_handle(object));
1490        self.transient_objects.populate(object, attrs)
1491    }
1492}
1493
1494pub fn init_ref_attribute(id: AttributeId, buffer: &mut [u8]) -> Attribute {
1495    assert!(id.memory_reference(), "Attribute ID {id:?} does not represent a memory reference");
1496    Attribute { id, content: BufferOrValue { memref: MemRef::from_mut_slice(buffer) } }
1497}
1498
1499pub fn init_value_attribute(id: AttributeId, value: ValueFields) -> Attribute {
1500    assert!(id.value(), "Attribute ID {id:?} does not represent value fields");
1501    Attribute { id, content: BufferOrValue { value } }
1502}
1503
1504impl Storage {
1505    pub fn copy_object_attributes(&mut self, _src: ObjectHandle, dest: ObjectHandle) -> TeeResult {
1506        assert!(is_transient_handle(dest));
1507        unimplemented!()
1508    }
1509
1510    /// Generates key information on an uninitialized, transient object, given
1511    /// a key size and the attributes that serve as inputs to the generation
1512    /// process.
1513    ///
1514    /// Panics if `object` is not a valid handle to an uninitialized, transient
1515    /// object, if key size is invalid or larger than the prescribed maximum,
1516    /// or if a mandatory attribute is absent.
1517    pub fn generate_key(
1518        &mut self,
1519        object: ObjectHandle,
1520        key_size: u32,
1521        params: &[Attribute],
1522    ) -> TeeResult {
1523        self.transient_objects.generate_key(object, key_size, params)
1524    }
1525
1526    /// Opens a new handle to an existing persistent object.
1527    ///
1528    /// Returns Error::ItemNotFound: if `storage` does not correspond to a valid
1529    /// storage space, or if no object with `id` is found.
1530    ///
1531    /// Returns Error::AccessConflict if any of the following hold:
1532    ///   - The object is currently open with DATA_ACCESS_WRITE_META;
1533    ///   - The object is currently open and `flags` contains
1534    ///     DATA_ACCESS_WRITE_META
1535    ///   - The object is currently open without DATA_ACCESS_READ_SHARE
1536    ///     and `flags` contains DATA_ACCESS_READ or DATA_ACCESS_READ_SHARE;
1537    ///   - The object is currently open with DATA_ACCESS_READ_SHARE, but `flags`
1538    ///     does not;
1539    ///   - The object is currently open without DATA_ACCESS_WRITE_SHARE and
1540    ///     `flags` contains DATA_ACCESS_WRITE or DATA_ACCESS_WRITE_SHARE;
1541    ///   - The object is currently open with DATA_ACCESS_WRITE_SHARE, but `flags`
1542    ///     does not.
1543    pub fn open_persistent_object(
1544        &mut self,
1545        storage: TeeStorage,
1546        id: &[u8],
1547        flags: HandleFlags,
1548    ) -> TeeResult<ObjectHandle> {
1549        if storage == TeeStorage::Private {
1550            self.persistent_objects.open(id, flags)
1551        } else {
1552            Err(Error::ItemNotFound)
1553        }
1554    }
1555
1556    /// Creates a persistent object and returns a handle to it. The conferred type,
1557    /// usage, and attributes are given indirectly by `attribute_src`; if
1558    /// `attribute_src` is null then the conferred type is Data.
1559    ///
1560    /// Returns Error::ItemNotFound: if `storage` does not correspond to a valid
1561    /// storage spac
1562    ///
1563    /// Returns Error::AccessConflict if the provided ID already exists but
1564    /// `flags` does not contain DATA_FLAG_OVERWRITE.
1565    pub fn create_persistent_object(
1566        &mut self,
1567        storage: TeeStorage,
1568        id: &[u8],
1569        flags: HandleFlags,
1570        attribute_src: ObjectHandle,
1571        initial_data: &[u8],
1572    ) -> TeeResult<ObjectHandle> {
1573        if storage != TeeStorage::Private {
1574            return Err(Error::ItemNotFound);
1575        }
1576
1577        let (key, usage, base_flags) = if attribute_src.is_null() {
1578            (Key::Data(NoKey {}), Usage::default(), HandleFlags::empty())
1579        } else if is_persistent_handle(attribute_src) {
1580            let view = self.persistent_objects.get(attribute_src);
1581            let obj = view.object.borrow();
1582            (obj.key.clone(), obj.usage, obj.base_flags)
1583        } else {
1584            unimplemented!();
1585        };
1586        let flags = base_flags.union(flags);
1587        self.persistent_objects.create(key, usage, flags, id, initial_data)
1588    }
1589
1590    /// Closes the given handle to a persistent object and deletes the object.
1591    ///
1592    /// Panics if `object` is invalid or was not opened with
1593    /// DATA_ACCESS_WRITE_META.
1594    pub fn close_and_delete_persistent_object(&mut self, object: ObjectHandle) -> TeeResult {
1595        assert!(is_persistent_handle(object));
1596        self.persistent_objects.close_and_delete(object)
1597    }
1598
1599    /// Renames the object's, associating it with a new identifier.
1600    ///
1601    /// Returns Error::AccessConflict if `new_id` is the ID of an existing
1602    /// object.
1603    ///
1604    /// Panics if `object` is invalid or was not opened with
1605    /// DATA_ACCESS_WRITE_META.
1606    pub fn rename_persistent_object(&mut self, object: ObjectHandle, new_id: &[u8]) -> TeeResult {
1607        assert!(is_persistent_handle(object));
1608        self.persistent_objects.rename(object, new_id)
1609    }
1610
1611    /// Allocates a new object enumerator and returns a handle to it.
1612    pub fn allocate_persistent_object_enumerator(&mut self) -> ObjectEnumHandle {
1613        self.persistent_objects.allocate_enumerator()
1614    }
1615
1616    /// Deallocates an object enumerator.
1617    ///
1618    /// Panics if `enumerator` is not a valid handle.
1619    pub fn free_persistent_object_enumerator(&mut self, enumerator: ObjectEnumHandle) {
1620        self.persistent_objects.free_enumerator(enumerator)
1621    }
1622
1623    /// Resets an object enumerator.
1624    ///
1625    /// Panics if `enumerator` is not a valid handle.
1626    pub fn reset_persistent_object_enumerator(&mut self, enumerator: ObjectEnumHandle) {
1627        self.persistent_objects.reset_enumerator(enumerator)
1628    }
1629
1630    /// Starts an object enumerator's enumeration, or resets it if already started.
1631    ///
1632    /// Returns Error::ItemNotFound if `storage` is unsupported or it there are no
1633    /// objects yet created in that storage space.
1634    ///
1635    /// Panics if `enumerator` is not a valid handle.
1636    pub fn start_persistent_object_enumerator(
1637        &mut self,
1638        enumerator: ObjectEnumHandle,
1639        storage: TeeStorage,
1640    ) -> TeeResult {
1641        if storage == TeeStorage::Private {
1642            self.reset_persistent_object_enumerator(enumerator);
1643            Ok(())
1644        } else {
1645            Err(Error::ItemNotFound)
1646        }
1647    }
1648
1649    /// Returns the info and ID associated with the next object in the enumeration,
1650    /// advancing it in the process. The returns object ID is backed by the
1651    /// provided buffer.
1652    ///
1653    /// Returns Error::ItemNotFound if there are no more objects left to enumerate.
1654    ///
1655    /// Panics if `enumerator` is not a valid handle.
1656    pub fn get_next_persistent_object<'a>(
1657        &self,
1658        enumerator: ObjectEnumHandle,
1659        id_buffer: &'a mut [u8],
1660    ) -> TeeResult<(ObjectInfo, &'a [u8])> {
1661        self.persistent_objects.get_next_object(enumerator, id_buffer)
1662    }
1663
1664    /// Tries to read as much of the object's data stream from the handle's current
1665    /// data position as can fill the provided buffer.
1666    ///
1667    /// Panics if `object` is invalid or does not have read access.
1668    pub fn read_object_data<'a>(
1669        &self,
1670        object: ObjectHandle,
1671        buffer: &'a mut [u8],
1672    ) -> TeeResult<&'a [u8]> {
1673        assert!(is_persistent_handle(object));
1674        self.persistent_objects.get_mut(object).read_data(buffer)
1675    }
1676
1677    /// Writes the provided data to the object's data stream at the handle's
1678    /// data position, advancing that position to the end of the written data.
1679    ///
1680    /// Returns Error::AccessConflict if the object does not have write
1681    /// access.
1682    ///
1683    /// Returns Error::Overflow if writing the data would advance the data
1684    /// position past DATA_MAX_POSITION.
1685    ///
1686    /// Panics if `object` is invalid or does not have write access.
1687    pub fn write_object_data(&self, object: ObjectHandle, buffer: &[u8]) -> TeeResult {
1688        assert!(is_persistent_handle(object));
1689        self.persistent_objects.get_mut(object).write_data(buffer)
1690    }
1691
1692    /// Truncates or zero-extends the object's data stream to provided size.
1693    /// This does not affect any handle's data position.
1694    ///
1695    /// Returns Error::Overflow if `size` is larger than DATA_MAX_POSITION.
1696    ///
1697    /// Panics if `object` is invalid or does not have write access.
1698    pub fn truncate_object_data(&self, object: ObjectHandle, size: usize) -> TeeResult {
1699        assert!(is_persistent_handle(object));
1700        self.persistent_objects.get(object).truncate_data(size)
1701    }
1702
1703    /// Updates the handle's data positition, seeking at an offset from a
1704    /// position given by a whence value. The new position saturates at 0.
1705    ///
1706    /// Returns Error::Overflow if the would-be position exceeds
1707    /// DATA_MAX_POSITION.
1708    ///
1709    /// Panics if `object` is invalid.
1710    pub fn seek_data_object(
1711        &self,
1712        object: ObjectHandle,
1713        offset: isize,
1714        whence: Whence,
1715    ) -> TeeResult {
1716        assert!(is_persistent_handle(object));
1717        self.persistent_objects.get_mut(object).seek_data(offset, whence)
1718    }
1719}
1720
1721// TODO(https://fxbug.dev/376093162): Add TransientObjects testing.
1722// TODO(https://fxbug.dev/376093162): Add PersistentObjects testing.