Skip to main content

optee_utee/
property.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 crate::{Error, ErrorKind, Result, tee_check};
19use crate::{Identity, Uuid};
20use alloc::{ffi::CString, string::String, vec::Vec};
21use optee_utee_sys as raw;
22
23/// Represents a TEE property set according to the TEE Internal API.
24/// The property set is a collection of properties that can be
25/// queried from the TEE. The property set is identified by a
26/// handle, which is a pointer to a TEE_PropSetHandle structure.
27pub enum PropertySet {
28    TeeImplementation,
29    CurrentClient,
30    CurrentTa,
31}
32
33impl PropertySet {
34    fn as_raw(&self) -> raw::TEE_PropSetHandle {
35        match self {
36            PropertySet::TeeImplementation => raw::TEE_PROPSET_TEE_IMPLEMENTATION,
37            PropertySet::CurrentClient => raw::TEE_PROPSET_CURRENT_CLIENT,
38            PropertySet::CurrentTa => raw::TEE_PROPSET_CURRENT_TA,
39        }
40    }
41}
42
43/// Represents a TEE property value.
44/// The property value can be of different types, such as
45/// string, bool, u32, TEE_UUID, TEE_Identity, etc.
46/// The property value is obtained from the TEE
47/// property set using the TEE_GetPropertyAs* functions.
48pub trait PropertyValue: Sized {
49    /// # Safety
50    /// This function is unsafe because it dereferences raw pointers from the TEE API.
51    /// The caller must ensure that the `set` handle is valid and that the TEE environment
52    /// is properly initialized.
53    unsafe fn from_raw(set: raw::TEE_PropSetHandle, key: CString) -> Result<Self>;
54}
55
56/// Implements the PropertyValue trait for all return types:
57/// String, Bool, u32, u64, BinaryBlock, UUID, Identity.
58impl PropertyValue for String {
59    unsafe fn from_raw(set: raw::TEE_PropSetHandle, key: CString) -> Result<Self> {
60        let mut out_size = 0;
61
62        // The first call is to get the size of the string
63        // So we pass a null pointer and a size of 0
64        let res = unsafe {
65            raw::TEE_GetPropertyAsString(
66                set,
67                key.as_ptr() as *const _,
68                core::ptr::null_mut(),
69                &mut out_size,
70            )
71        };
72        match res {
73            raw::TEE_SUCCESS => {
74                if out_size == 0 {
75                    // return an empty string
76                    Ok(String::new())
77                } else {
78                    Err(Error::new(ErrorKind::Generic))
79                }
80            }
81            raw::TEE_ERROR_SHORT_BUFFER => {
82                // Resize the string to the actual size
83                let mut out_buffer = vec![0; out_size];
84                let res = unsafe {
85                    raw::TEE_GetPropertyAsString(
86                        set,
87                        key.as_ptr() as *const _,
88                        out_buffer.as_mut_ptr() as *mut _,
89                        &mut out_size,
90                    )
91                };
92                tee_check(res)?;
93
94                // Convert the char buffer with null terminator to a C string
95                let c_str = core::ffi::CStr::from_bytes_with_nul(&out_buffer)
96                    .map_err(|_| Error::new(ErrorKind::BadFormat))?;
97                // Convert the C string to a Rust string
98                let result = c_str.to_string_lossy().into_owned();
99
100                Ok(result)
101            }
102            _ => Err(Error::from_raw_error(res)),
103        }
104    }
105}
106
107impl PropertyValue for bool {
108    unsafe fn from_raw(set: raw::TEE_PropSetHandle, key: CString) -> Result<Self> {
109        let mut b: bool = false;
110
111        let res = unsafe { raw::TEE_GetPropertyAsBool(set, key.as_ptr() as *const _, &mut b) };
112        tee_check(res)?;
113
114        Ok(b)
115    }
116}
117
118impl PropertyValue for u32 {
119    unsafe fn from_raw(set: raw::TEE_PropSetHandle, key: CString) -> Result<Self> {
120        let mut value = 0;
121
122        let res = unsafe { raw::TEE_GetPropertyAsU32(set, key.as_ptr() as *const _, &mut value) };
123        tee_check(res)?;
124
125        Ok(value)
126    }
127}
128
129impl PropertyValue for u64 {
130    unsafe fn from_raw(set: raw::TEE_PropSetHandle, key: CString) -> Result<Self> {
131        let mut value = 0;
132
133        let res = unsafe { raw::TEE_GetPropertyAsU64(set, key.as_ptr() as *const _, &mut value) };
134        tee_check(res)?;
135
136        Ok(value)
137    }
138}
139
140impl PropertyValue for Vec<u8> {
141    unsafe fn from_raw(set: raw::TEE_PropSetHandle, key: CString) -> Result<Self> {
142        let mut out_size = 0;
143
144        // The first call is to get the size of the binary block
145        // So we pass a null pointer and a size of 0
146        let res = unsafe {
147            raw::TEE_GetPropertyAsBinaryBlock(
148                set,
149                key.as_ptr() as *const _,
150                core::ptr::null_mut(),
151                &mut out_size,
152            )
153        };
154
155        match res {
156            raw::TEE_SUCCESS => {
157                if out_size == 0 {
158                    // return an empty buffer
159                    Ok(vec![])
160                } else {
161                    Err(Error::new(ErrorKind::Generic))
162                }
163            }
164            raw::TEE_ERROR_SHORT_BUFFER => {
165                let mut buf = vec![0; out_size];
166
167                let res = unsafe {
168                    raw::TEE_GetPropertyAsBinaryBlock(
169                        set,
170                        key.as_ptr() as *const _,
171                        buf.as_mut_ptr() as *mut _,
172                        &mut out_size,
173                    )
174                };
175                tee_check(res)?;
176                Ok(buf)
177            }
178            _ => Err(Error::from_raw_error(res)),
179        }
180    }
181}
182
183impl PropertyValue for Uuid {
184    unsafe fn from_raw(set: raw::TEE_PropSetHandle, key: CString) -> Result<Self> {
185        let mut raw_uuid = raw::TEE_UUID {
186            timeLow: 0,
187            timeMid: 0,
188            timeHiAndVersion: 0,
189            clockSeqAndNode: [0; 8],
190        };
191
192        let res =
193            unsafe { raw::TEE_GetPropertyAsUUID(set, key.as_ptr() as *const _, &mut raw_uuid) };
194        tee_check(res)?;
195
196        Ok(Uuid::from(raw_uuid))
197    }
198}
199
200impl PropertyValue for Identity {
201    unsafe fn from_raw(set: raw::TEE_PropSetHandle, key: CString) -> Result<Self> {
202        // Allocate a buffer for the raw identity
203        let mut raw_id = raw::TEE_Identity {
204            login: 0,
205            uuid: raw::TEE_UUID {
206                timeLow: 0,
207                timeMid: 0,
208                timeHiAndVersion: 0,
209                clockSeqAndNode: [0; 8],
210            },
211        };
212
213        let res =
214            unsafe { raw::TEE_GetPropertyAsIdentity(set, key.as_ptr() as *const _, &mut raw_id) };
215        tee_check(res)?;
216
217        Ok(Identity::from(raw_id))
218    }
219}
220
221/// Represents a TEE property key.
222/// The property key is used to identify a specific property
223/// within a property set. The property key is a string that
224/// is used to query the property value from the TEE property
225/// set. The property key is defined in the TEE Internal API,
226/// such as "gpd.client.identity" or "gpd.tee.apiversion".
227pub trait PropertyKey {
228    type Output: PropertyValue;
229    fn key(&self) -> CString;
230    fn set(&self) -> PropertySet;
231
232    fn get(&self) -> Result<Self::Output> {
233        unsafe { Self::Output::from_raw(self.set().as_raw(), self.key()) }
234    }
235}
236
237/// Macro to define a property key.
238/// This macro generates a struct that implements the
239/// PropertyKey trait.
240#[macro_export]
241macro_rules! define_property_key {
242    (
243        $name:ident,
244        $set:ident,
245        $key:literal,
246        $output:ty
247    ) => {
248        pub struct $name;
249
250        impl PropertyKey for $name {
251            type Output = $output;
252
253            fn key(&self) -> CString {
254                CString::new($key).unwrap_or_default()
255            }
256
257            fn set(&self) -> PropertySet {
258                PropertySet::$set
259            }
260        }
261    };
262}
263
264// Define all existing property keys for the TEE property set.
265// The format is:
266// `define_property_key!(Name, Set, "key", OutputType);`
267// The `Set` is one of the PropertySet it belongs to.
268// The `key` is the raw property key string.
269// The `OutputType` is the type of the property value.
270//
271// To get the property value, use the `get` method.
272// Example usage:
273//
274// ``` no_run
275// use optee_utee::{PropertyKey, TaAppId};
276//
277// let my_property = TaAppId.get()?;
278// ```
279define_property_key!(TaAppId, CurrentTa, "gpd.ta.appID", Uuid);
280define_property_key!(TaSingleInstance, CurrentTa, "gpd.ta.singleInstance", bool);
281define_property_key!(TaMultiSession, CurrentTa, "gpd.ta.multiSession", bool);
282define_property_key!(
283    TaInstanceKeepAlive,
284    CurrentTa,
285    "gpd.ta.instanceKeepAlive",
286    bool
287);
288define_property_key!(
289    TaInstanceKeepCrashed,
290    CurrentTa,
291    "gpd.ta.instanceKeepCrashed",
292    bool
293);
294define_property_key!(TaDataSize, CurrentTa, "gpd.ta.dataSize", u32);
295define_property_key!(TaStackSize, CurrentTa, "gpd.ta.stackSize", u32);
296define_property_key!(TaVersion, CurrentTa, "gpd.ta.version", String);
297define_property_key!(TaDescription, CurrentTa, "gpd.ta.description", String);
298define_property_key!(TaEndian, CurrentTa, "gpd.ta.endian", u32);
299define_property_key!(
300    TaDoesNotCloseHandleOnCorruptObject,
301    CurrentTa,
302    "gpd.ta.doesNotCloseHandleOnCorruptObject",
303    bool
304);
305define_property_key!(
306    ClientIdentity,
307    CurrentClient,
308    "gpd.client.identity",
309    Identity
310);
311define_property_key!(ClientEndian, CurrentClient, "gpd.client.endian", u32);
312define_property_key!(
313    TeeApiVersion,
314    TeeImplementation,
315    "gpd.tee.apiversion",
316    String
317);
318define_property_key!(
319    TeeInternalCoreVersion,
320    TeeImplementation,
321    "gpd.tee.internalCore.version",
322    u32
323);
324define_property_key!(
325    TeeDescription,
326    TeeImplementation,
327    "gpd.tee.description",
328    String
329);
330define_property_key!(TeeDeviceId, TeeImplementation, "gpd.tee.deviceID", Uuid);
331define_property_key!(
332    TeeSystemTimeProtectionLevel,
333    TeeImplementation,
334    "gpd.tee.systemTime.protectionLevel",
335    u32
336);
337define_property_key!(
338    TeeTaPersistentTimeProtectionLevel,
339    TeeImplementation,
340    "gpd.tee.TAPersistentTime.protectionLevel",
341    u32
342);
343define_property_key!(
344    TeeArithMaxBigIntSize,
345    TeeImplementation,
346    "gpd.tee.arith.maxBigIntSize",
347    u32
348);
349define_property_key!(
350    TeeCryptographyEcc,
351    TeeImplementation,
352    "gpd.tee.cryptography.ecc",
353    bool
354);
355define_property_key!(
356    TeeCryptographyNist,
357    TeeImplementation,
358    "gpd.tee.cryptography.nist",
359    bool
360);
361define_property_key!(
362    TeeCryptographyBsiR,
363    TeeImplementation,
364    "gpd.tee.cryptography.bsi-r",
365    bool
366);
367define_property_key!(
368    TeeCryptographyBsiT,
369    TeeImplementation,
370    "gpd.tee.cryptography.bsi-t",
371    bool
372);
373define_property_key!(
374    TeeCryptographyIetf,
375    TeeImplementation,
376    "gpd.tee.cryptography.ietf",
377    bool
378);
379define_property_key!(
380    TeeCryptographyOcta,
381    TeeImplementation,
382    "gpd.tee.cryptography.octa",
383    bool
384);
385define_property_key!(
386    TeeTrustedStoragePrivateRollbackProtection,
387    TeeImplementation,
388    "gpd.tee.trustedStorage.private.rollbackProtection",
389    u32
390);
391define_property_key!(
392    TeeTrustedStoragePersoRollbackProtection,
393    TeeImplementation,
394    "gpd.tee.trustedStorage.perso.rollbackProtection",
395    u32
396);
397define_property_key!(
398    TeeTrustedStorageProtectedRollbackProtection,
399    TeeImplementation,
400    "gpd.tee.trustedStorage.protected.rollbackProtection",
401    u32
402);
403define_property_key!(
404    TeeTrustedStorageAntiRollbackProtectionLevel,
405    TeeImplementation,
406    "gpd.tee.trustedStorage.antiRollback.protectionLevel",
407    u32
408);
409define_property_key!(
410    TeeTrustedStorageRollbackDetectionProtectionLevel,
411    TeeImplementation,
412    "gpd.tee.trustedStorage.rollbackDetection.protectionLevel",
413    u32
414);
415define_property_key!(
416    TeeTrustedOsImplementationVersion,
417    TeeImplementation,
418    "gpd.tee.trustedos.implementation.version",
419    String
420);
421define_property_key!(
422    TeeTrustedOsImplementationBinaryVersion,
423    TeeImplementation,
424    "gpd.tee.trustedos.implementation.binaryversion",
425    u32
426);
427define_property_key!(
428    TeeTrustedOsManufacturer,
429    TeeImplementation,
430    "gpd.tee.trustedos.manufacturer",
431    String
432);
433define_property_key!(
434    TeeFirmwareImplementationVersion,
435    TeeImplementation,
436    "gpd.tee.firmware.implementation.version",
437    String
438);
439define_property_key!(
440    TeeFirmwareImplementationBinaryVersion,
441    TeeImplementation,
442    "gpd.tee.firmware.implementation.binaryversion",
443    u32
444);
445define_property_key!(
446    TeeFirmwareManufacturer,
447    TeeImplementation,
448    "gpd.tee.firmware.manufacturer",
449    String
450);
451define_property_key!(
452    TeeEventMaxSources,
453    TeeImplementation,
454    "gpd.tee.event.maxSources",
455    u32
456);