optee_utee/object/transient_object.rs
1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use alloc::vec::Vec;
19
20use optee_utee_sys as raw;
21
22use super::{Attribute, GenericObject, ObjectHandle};
23use crate::{Result, tee_check};
24
25/// Define types of [TransientObject](crate::TransientObject) with
26/// predefined maximum sizes.
27#[derive(Clone, Copy, strum::Display)]
28#[repr(u32)]
29pub enum TransientObjectType {
30 /// 128, 192, or 256 bits
31 Aes = 0xA0000010,
32 /// Always 64 bits including the parity bits. This gives an effective key
33 /// size of 56 bits
34 Des = 0xA0000011,
35 /// 128 or 192 bits including the parity bits. This gives effective key
36 /// sizes of 112 or 168 bits
37 Des3 = 0xA0000013,
38 /// Between 64 and 512 bits, multiple of 8 bits
39 HmacMd5 = 0xA0000001,
40 /// Between 80 and 512 bits, multiple of 8 bits
41 HmacSha1 = 0xA0000002,
42 /// Between 112 and 512 bits, multiple of 8 bits
43 HmacSha224 = 0xA0000003,
44 /// Between 192 and 1024 bits, multiple of 8 bits
45 HmacSha256 = 0xA0000004,
46 /// Between 256 and 1024 bits, multiple of 8 bits
47 HmacSha384 = 0xA0000005,
48 /// Between 256 and 1024 bits, multiple of 8 bits
49 HmacSha512 = 0xA0000006,
50 /// The number of bits in the modulus. 256, 512, 768, 1024, 1536 and
51 /// 2048-bit keys SHALL be supported.
52 /// Support for other key sizes including bigger key sizes is
53 /// implementation-dependent. Minimum key size is 256 bits
54 RsaPublicKey = 0xA0000030,
55 /// Same as [RsaPublicKey](crate::TransientObjectType::RsaPublicKey) key
56 /// size.
57 RsaKeypair = 0xA1000030,
58 /// Depends on Algorithm:
59 /// 1) [DsaSha1](crate::AlgorithmId::DsaSha1):
60 /// Between 512 and 1024 bits, multiple of 64 bits
61 /// 2) [DsaSha224](crate::AlgorithmId::DsaSha224): 2048 bits
62 /// 3) [DsaSha256](crate::AlgorithmId::DsaSha256): 2048 or 3072 bits
63 DsaPublicKey = 0xA0000031,
64 /// Same as [DsaPublicKey](crate::TransientObjectType::DsaPublicKey) key
65 /// size.
66 DsaKeypair = 0xA1000031,
67 /// From 256 to 2048 bits, multiple of 8 bits.
68 DhKeypair = 0xA1000032,
69 /// Password for PBKDF2 key derivation. Size in bits, multiple of 8 bits.
70 Pbkdf2Password = 0xA10000C2,
71 /// Between 160 and 521 bits. Conditional: Available only if at least
72 /// one of the ECC the curves defined in Table 6-14 with "generic"
73 /// equal to "Y" is supported.
74 EcdsaPublicKey = 0xA0000041,
75 /// Between 160 and 521 bits. Conditional: Available only if at least
76 /// one of the ECC curves defined in Table 6-14 with "generic" equal to
77 /// "Y" is supported. SHALL be same value as for ECDSA public key size.
78 EcdsaKeypair = 0xA1000041,
79 /// Between 160 and 521 bits. Conditional: Available only if at least
80 /// one of the ECC curves defined in Table 6-14 with "generic" equal to
81 /// "Y" is supported.
82 EcdhPublicKey = 0xA0000042,
83 /// Between 160 and 521 bits. Conditional: Available only if at least
84 /// one of the ECC curves defined in Table 6-14 with "generic" equal to
85 /// "Y" is supported. SHALL be same value as for ECDH public key size
86 EcdhKeypair = 0xA1000042,
87 /// 256 bits. Conditional: Available only if TEE_ECC_CURVE_25519
88 /// defined in Table 6-14 is supported.
89 Ed25519PublicKey = 0xA0000043,
90 /// 256 bits. Conditional: Available only if TEE_ECC_CURVE_25519
91 /// defined in Table 6-14 is supported.
92 Ed25519Keypair = 0xA1000043,
93 /// 256 bits. Conditional: Available only if TEE_ECC_CURVE_25519
94 /// defined in Table 6-14 is supported.
95 X25519PublicKey = 0xA0000044,
96 /// 256 bits. Conditional: Available only if TEE_ECC_CURVE_25519
97 /// defined in Table 6-14 is supported.
98 X25519Keypair = 0xA1000044,
99 /// Multiple of 8 bits, up to 4096 bits. This type is intended for secret
100 /// data that has been derived from a key derivation scheme.
101 GenericSecret = 0xA0000000,
102 /// Object is corrupted.
103 CorruptedObject = 0xA00000BE,
104 /// 0 – All data is in the associated data stream.
105 Data = 0xA00000BF,
106}
107
108/// An object containing attributes but no data stream, which is reclaimed
109/// when closed or when the TA instance is destroyed.
110/// Transient objects are used to hold a cryptographic object (key or key-pair).
111///
112/// Contrast [PersistentObject](crate::PersistentObject).
113#[derive(Debug)]
114pub struct TransientObject(ObjectHandle);
115
116impl TransientObject {
117 /// Create an object with a null handle which points to nothing.
118 //
119 // TODO: This function is only used in examples and should be removed when
120 // TransientObject is fully refactored in the future. Keep it for now and
121 // leave it for future PR.
122 pub fn null_object() -> Self {
123 Self(ObjectHandle::new_null())
124 }
125
126 /// Check if current object is created with null handle.
127 ///
128 /// # See Also
129 ///
130 /// - [Self::null_object](Self::null_object).
131 pub fn is_null_object(&self) -> bool {
132 self.0.is_null()
133 }
134
135 /// Allocate an uninitialized object, i.e. a container for attributes.
136 ///
137 /// As allocated, the object is uninitialized.
138 /// It can be initialized by subsequently importing the object material,
139 /// generating an object, deriving an object, or loading an object from the
140 /// Trusted Storage.
141 ///
142 /// # Parameters
143 ///
144 /// 1) `object_type`: Type of uninitialized object container to be created
145 /// as defined in [TransientObjectType](crate::TransientObjectType).
146 /// 2) `max_object_size`: Key Size of the object. Valid values depend on the
147 /// object type and are defined in
148 /// [TransientObjectType](crate::TransientObjectType).
149 ///
150 /// # Example
151 ///
152 /// ``` rust,no_run
153 /// # use optee_utee::{TransientObject, TransientObjectType};
154 /// # fn main() -> optee_utee::Result<()> {
155 /// match TransientObject::allocate(TransientObjectType::Aes, 128) {
156 /// Ok(object) =>
157 /// {
158 /// // ...
159 /// Ok(())
160 /// }
161 /// Err(e) => Err(e),
162 /// }
163 /// # }
164 /// ```
165 ///
166 /// # Errors
167 ///
168 /// 1) `OutOfMemory`: If not enough resources are available to allocate the
169 /// object handle.
170 /// 2) `NotSupported`: If the key size is not supported or the object type
171 /// is not supported.
172 ///
173 /// # Panics
174 ///
175 /// 1) If the Implementation detects any error associated with this function
176 /// which is not explicitly associated with a defined return code for
177 /// this function.
178 pub fn allocate(object_type: TransientObjectType, max_object_size: usize) -> Result<Self> {
179 let mut handle: raw::TEE_ObjectHandle = core::ptr::null_mut();
180 // Move as much code as possible out of unsafe blocks to maximize Rust’s
181 // safety checks.
182 let handle_mut = &mut handle;
183 tee_check(unsafe {
184 raw::TEE_AllocateTransientObject(object_type as u32, max_object_size as u32, handle_mut)
185 })?;
186 Ok(Self(ObjectHandle::from_raw(handle)?))
187 }
188
189 /// Reset the object to its initial state after allocation.
190 /// If the object is currently initialized, the function clears the object
191 /// of all its material.
192 /// The object is then uninitialized again.
193 pub fn reset(&mut self) {
194 unsafe {
195 raw::TEE_ResetTransientObject(*self.as_raw_ref());
196 }
197 }
198
199 /// Populate an uninitialized object container with object attributes passed
200 /// by the TA in the `attrs` parameter.
201 /// When this function is called, the object SHALL be uninitialized.
202 /// If the object is initialized, the caller SHALL first clear it using the
203 /// function reset.
204 /// Note that if the object type is a key-pair, then this function sets both
205 /// the private and public attributes of the keypair.
206 ///
207 /// # Parameters
208 ///
209 /// 1) `attrs`: Array of object attributes.
210 ///
211 /// # Example
212 ///
213 /// ``` rust,no_run
214 /// # use optee_utee::{
215 /// # TransientObject,
216 /// # TransientObjectType,
217 /// # AttributeMemref,
218 /// # AttributeId,
219 /// # };
220 /// # fn main() -> optee_utee::Result<()> {
221 /// match TransientObject::allocate(TransientObjectType::Aes, 128) {
222 /// Ok(mut object) =>
223 /// {
224 /// let attrs = [AttributeMemref::from_ref(AttributeId::SecretValue, &[0u8;1]).into()];
225 /// object.populate(&attrs);
226 /// Ok(())
227 /// }
228 /// Err(e) => Err(e),
229 /// }
230 /// # }
231 /// ```
232 ///
233 /// # Errors
234 ///
235 /// 1) `BadParameters`: If an incorrect or inconsistent attribute value is
236 /// detected. In this case, the content of the object SHALL remain
237 /// uninitialized.
238 ///
239 /// # Panics
240 ///
241 /// 1) If object is not a valid opened object that is transient and
242 /// uninitialized.
243 /// 2) If some mandatory attribute is missing.
244 /// 3) If an attribute which is not defined for the object’s type is
245 /// present in attrs.
246 /// 4) If an attribute value is too big to fit within the maximum object
247 /// size specified when the object was created.
248 /// 5) If the Implementation detects any other error associated with this
249 /// function which is not explicitly associated with a defined return
250 /// code for this function.
251 pub fn populate(&mut self, attrs: &[Attribute]) -> Result<()> {
252 let p: Vec<raw::TEE_Attribute> = attrs.iter().map(|p| p.raw()).collect();
253 tee_check(unsafe {
254 raw::TEE_PopulateTransientObject(
255 *self.0.as_raw_ref(),
256 p.as_ptr() as _,
257 attrs.len() as u32,
258 )
259 })
260 }
261
262 /// Populates an uninitialized object handle with the attributes of another
263 /// object handle;
264 /// that is, it populates the attributes of this handle with the attributes
265 /// of src_handle.
266 /// It is most useful in the following situations:
267 /// 1) To extract the public key attributes from a key-pair object.
268 /// 2) To copy the attributes from a
269 /// [PersistentObject](crate::PersistentObject) into a
270 /// [TransientObject](crate::TransientObject).
271 ///
272 /// # Parameters
273 ///
274 /// 1) `src_object`: Can be either a
275 /// [TransientObject](crate::TransientObject) or
276 /// [PersistentObject](crate::PersistentObject).
277 ///
278 /// # Example
279 ///
280 /// ``` rust,no_run
281 /// # use optee_utee::{TransientObject, TransientObjectType};
282 /// # fn main() -> optee_utee::Result<()> {
283 /// match TransientObject::allocate(TransientObjectType::Aes, 128) {
284 /// Ok(mut object1) =>
285 /// {
286 /// match TransientObject::allocate(TransientObjectType::Aes, 256) {
287 /// Ok(object2) => {
288 /// object1.copy_attribute_from(&object2);
289 /// Ok(())
290 /// }
291 /// Err(e) => Err(e),
292 /// }
293 /// }
294 /// Err(e) => Err(e),
295 /// }
296 /// # }
297 /// ```
298 ///
299 /// # Errors
300 ///
301 /// 1) `CorruptObject`: If the persistent object is corrupt. The object
302 /// handle SHALL behave based on the
303 /// `gpd.ta.doesNotCloseHandleOnCorruptObject` property.
304 /// 2) `StorageNotAvailable`: If the persistent object is stored in a
305 /// storage area which is currently inaccessible.
306 ///
307 /// # Panics
308 ///
309 /// 1) If src_object is not initialized.
310 /// 2) If self is initialized.
311 /// 3) If the type and size of src_object and self are not compatible.
312 /// 4) If the Implementation detects any other error associated with this
313 /// function which is not explicitly associated with a defined return
314 /// code for this function.
315 pub fn copy_attribute_from<T: GenericObject>(&mut self, src_object: &T) -> Result<()> {
316 tee_check(unsafe {
317 raw::TEE_CopyObjectAttributes1(*self.as_raw_ref(), *src_object.as_raw_ref())
318 })
319 }
320
321 /// Generates a random key or a key-pair and populates a transient key
322 /// object with the generated key material.
323 ///
324 /// # Parameters
325 ///
326 /// 1) `key_size`: the size of the desired key. It SHALL be less than or
327 /// equal to the maximum key size specified when the transient object
328 /// was created.
329 ///
330 /// # Example
331 ///
332 /// ``` rust,no_run
333 /// # use optee_utee::{TransientObject, TransientObjectType};
334 /// # fn main() -> optee_utee::Result<()> {
335 /// match TransientObject::allocate(TransientObjectType::Aes, 128) {
336 /// Ok(object) =>
337 /// {
338 /// object.generate_key(128, &[])?;
339 /// Ok(())
340 /// }
341 /// Err(e) => Err(e),
342 /// }
343 /// # }
344 /// ```
345 ///
346 /// # Errors
347 ///
348 /// 1) `BadParameters`: If an incorrect or inconsistent attribute value is detected. In this
349 /// case, the content of the object SHALL remain uninitialized.
350 ///
351 /// # Panics
352 ///
353 /// 1) If object is not a valid opened object.
354 /// 2) If some mandatory attribute is missing.
355 /// 3) If an attribute which is not defined for the object’s type is present
356 /// in attrs.
357 /// 4) If an attribute value is too big to fit within the maximum object
358 /// size specified when the object was created.
359 /// 5) If the Implementation detects any other error associated with this
360 /// function which is not explicitly associated with a defined return
361 /// code for this function.
362 pub fn generate_key(&self, key_size: usize, params: &[Attribute]) -> Result<()> {
363 let p: Vec<raw::TEE_Attribute> = params.iter().map(|p| p.raw()).collect();
364 tee_check(unsafe {
365 raw::TEE_GenerateKey(
366 *self.as_raw_ref(),
367 key_size as u32,
368 p.as_slice().as_ptr() as _,
369 p.len() as u32,
370 )
371 })
372 }
373}
374
375impl GenericObject for TransientObject {
376 unsafe fn as_raw_ref(&self) -> &optee_utee_sys::TEE_ObjectHandle {
377 unsafe { self.0.as_raw_ref() }
378 }
379}
380
381#[cfg(test)]
382mod tests {
383 use optee_utee_sys::{
384 mock_api,
385 mock_utils::{SERIAL_TEST_LOCK, object::MockHandle},
386 };
387
388 use super::*;
389
390 #[test]
391 // If a transient object is successfully allocated, TEE_CloseObject will be
392 // called when it is dropped.
393 //
394 // According to `GPD_TEE_Internal_Core_API_Specification_v1.3.1`:
395 // At 5.5.5 TEE_CloseObject:
396 // The `TEE_CloseObject` function closes an opened object handle. The object
397 // can be persistent or transient.
398 // For transient objects, `TEE_CloseObject` is equivalent to
399 // `TEE_FreeTransientObject`.
400 fn test_allocate_and_drop() {
401 let _lock = SERIAL_TEST_LOCK.lock().expect("should get the lock");
402
403 let mut raw_handle = MockHandle::new();
404 let handle = raw_handle.as_handle();
405 let fn1 = mock_api::TEE_AllocateTransientObject_context();
406 let fn2 = mock_api::TEE_CloseObject_context();
407
408 fn1.expect().return_once_st(move |_, _, obj| {
409 unsafe { *obj = handle.clone() };
410 raw::TEE_SUCCESS
411 });
412 fn2.expect().return_once_st(move |obj| {
413 debug_assert_eq!(obj, handle.clone());
414 });
415
416 let _obj =
417 TransientObject::allocate(TransientObjectType::Aes, 128).expect("it should be ok");
418 }
419
420 #[test]
421 fn test_allocate_fail() {
422 let _lock = SERIAL_TEST_LOCK.lock().expect("should get the lock");
423
424 static RETURN_CODE: raw::TEE_Result = raw::TEE_ERROR_BAD_STATE;
425 let fn1 = mock_api::TEE_AllocateTransientObject_context();
426
427 fn1.expect().return_const(RETURN_CODE);
428
429 let err =
430 TransientObject::allocate(TransientObjectType::Aes, 128).expect_err("it should be err");
431
432 assert_eq!(err.raw_code(), RETURN_CODE);
433 }
434}