1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use crate::{Error, ErrorKind, Result};
use crate::{Identity, Uuid};
use alloc::{ffi::CString, string::String, vec::Vec};
use optee_utee_sys as raw;

/// Represents a TEE property set according to the TEE Internal API.
/// The property set is a collection of properties that can be
/// queried from the TEE. The property set is identified by a
/// handle, which is a pointer to a TEE_PropSetHandle structure.
pub enum PropertySet {
    TeeImplementation,
    CurrentClient,
    CurrentTa,
}

impl PropertySet {
    fn as_raw(&self) -> raw::TEE_PropSetHandle {
        match self {
            PropertySet::TeeImplementation => raw::TEE_PROPSET_TEE_IMPLEMENTATION,
            PropertySet::CurrentClient => raw::TEE_PROPSET_CURRENT_CLIENT,
            PropertySet::CurrentTa => raw::TEE_PROPSET_CURRENT_TA,
        }
    }
}

/// Represents a TEE property value.
/// The property value can be of different types, such as
/// string, bool, u32, TEE_UUID, TEE_Identity, etc.
/// The property value is obtained from the TEE
/// property set using the TEE_GetPropertyAs* functions.
pub trait PropertyValue: Sized {
    fn from_raw(set: raw::TEE_PropSetHandle, key: CString) -> Result<Self>;
}

/// Implements the PropertyValue trait for all return types:
/// String, Bool, u32, u64, BinaryBlock, UUID, Identity.
impl PropertyValue for String {
    fn from_raw(set: raw::TEE_PropSetHandle, key: CString) -> Result<Self> {
        let mut out_size = 0;

        // The first call is to get the size of the string
        // So we pass a null pointer and a size of 0
        let res = unsafe {
            raw::TEE_GetPropertyAsString(
                set,
                key.as_ptr() as *const core::ffi::c_char,
                core::ptr::null_mut(),
                &mut out_size,
            )
        };
        match res {
            raw::TEE_SUCCESS => {
                if out_size == 0 {
                    // return an empty string
                    return Ok(String::new());
                }
                else {
                    return Err(Error::new(ErrorKind::Generic));
                }
            }
            raw::TEE_ERROR_SHORT_BUFFER => {
                // Resize the string to the actual size
                let mut out_buffer = vec![0; out_size as usize];
                let res = unsafe {
                    raw::TEE_GetPropertyAsString(
                        set,
                        key.as_ptr() as *const core::ffi::c_char,
                        out_buffer.as_mut_ptr() as *mut core::ffi::c_char,
                        &mut out_size,
                    )
                };
                if res != raw::TEE_SUCCESS {
                    return Err(Error::from_raw_error(res));
                }

                // Convert the char buffer with null terminator to a C string
                let c_str = core::ffi::CStr::from_bytes_with_nul(&out_buffer)
                    .map_err(|_| Error::new(ErrorKind::BadFormat))?;
                // Convert the C string to a Rust string
                let result = c_str.to_string_lossy().into_owned();

                Ok(result)
            }
            _ => {
                return Err(Error::from_raw_error(res));
            }
        }
    }
}

impl PropertyValue for bool {
    fn from_raw(set: raw::TEE_PropSetHandle, key: CString) -> Result<Self> {
        let mut b: bool = false;

        let res = unsafe { raw::TEE_GetPropertyAsBool(set, key.as_ptr() as *const core::ffi::c_char, &mut b) };
        if res != 0 {
            return Err(Error::from_raw_error(res));
        }

        Ok(b)
    }
}

impl PropertyValue for u32 {
    fn from_raw(set: raw::TEE_PropSetHandle, key: CString) -> Result<Self> {
        let mut value = 0;

        let res = unsafe { raw::TEE_GetPropertyAsU32(set, key.as_ptr() as *const core::ffi::c_char, &mut value) };
        if res != 0 {
            return Err(Error::from_raw_error(res));
        }

        Ok(value)
    }
}

impl PropertyValue for u64 {
    fn from_raw(set: raw::TEE_PropSetHandle, key: CString) -> Result<Self> {
        let mut value = 0;

        let res = unsafe { raw::TEE_GetPropertyAsU64(set, key.as_ptr() as *const core::ffi::c_char, &mut value) };
        if res != 0 {
            return Err(Error::from_raw_error(res));
        }

        Ok(value)
    }
}

impl PropertyValue for Vec<u8> {
    fn from_raw(set: raw::TEE_PropSetHandle, key: CString) -> Result<Self> {
        let mut out_size = 0;

        // The first call is to get the size of the binary block
        // So we pass a null pointer and a size of 0
        let res = unsafe {
            raw::TEE_GetPropertyAsBinaryBlock(
                set,
                key.as_ptr() as *const core::ffi::c_char,
                core::ptr::null_mut(),
                &mut out_size,
            )
        };

        match res {
            raw::TEE_SUCCESS => {
                if out_size == 0 {
                    // return an empty buffer
                    return Ok(vec![]);
                }
                else {
                    return Err(Error::new(ErrorKind::Generic));
                }
            }
            raw::TEE_ERROR_SHORT_BUFFER => {
                let mut buf = vec![0; out_size as usize];

                let res = unsafe {
                    raw::TEE_GetPropertyAsBinaryBlock(
                        set,
                        key.as_ptr() as *const core::ffi::c_char,
                        buf.as_mut_ptr() as *mut core::ffi::c_void,
                        &mut out_size,
                    )
                };
                if res != raw::TEE_SUCCESS {
                    return Err(Error::from_raw_error(res));
                }

                Ok(buf)
            }
            _ => {
                return Err(Error::from_raw_error(res));
            }
        }
    }
}

impl PropertyValue for Uuid {
    fn from_raw(set: raw::TEE_PropSetHandle, key: CString) -> Result<Self> {
        let mut raw_uuid = raw::TEE_UUID {
            timeLow: 0,
            timeMid: 0,
            timeHiAndVersion: 0,
            clockSeqAndNode: [0; 8],
        };

        let res =
            unsafe { raw::TEE_GetPropertyAsUUID(set, key.as_ptr() as *const core::ffi::c_char, &mut raw_uuid) };
        if res != 0 {
            return Err(Error::from_raw_error(res));
        }

        Ok(Uuid::from(raw_uuid))
    }
}

impl PropertyValue for Identity {
    fn from_raw(set: raw::TEE_PropSetHandle, key: CString) -> Result<Self> {
        // Allocate a buffer for the raw identity
        let mut raw_id = raw::TEE_Identity {
            login: 0,
            uuid: raw::TEE_UUID {
                timeLow: 0,
                timeMid: 0,
                timeHiAndVersion: 0,
                clockSeqAndNode: [0; 8],
            },
        };

        let res = unsafe {
            raw::TEE_GetPropertyAsIdentity(set, key.as_ptr() as *const core::ffi::c_char, &mut raw_id)
        };
        if res != 0 {
            return Err(Error::from_raw_error(res));
        }

        Ok(Identity::from(raw_id))
    }
}

/// Represents a TEE property key.
/// The property key is used to identify a specific property
/// within a property set. The property key is a string that
/// is used to query the property value from the TEE property
/// set. The property key is defined in the TEE Internal API,
/// such as "gpd.client.identity" or "gpd.tee.apiversion".
pub trait PropertyKey {
    type Output: PropertyValue;
    fn key(&self) -> CString;
    fn set(&self) -> PropertySet;

    fn get(&self) -> Result<Self::Output> {
        Self::Output::from_raw(self.set().as_raw(), self.key())
    }
}

/// Macro to define a property key.
/// This macro generates a struct that implements the
/// PropertyKey trait.
macro_rules! define_property_key {
    (
        $name:ident,
        $set:ident,
        $key:literal,
        $output:ty
    ) => {
        pub struct $name;

        impl PropertyKey for $name {
            type Output = $output;

            fn key(&self) -> CString {
                CString::new($key).unwrap_or_default()
            }

            fn set(&self) -> PropertySet {
                PropertySet::$set
            }
        }
    };
}

// Define all existing property keys for the TEE property set.
// The format is:
// `define_property_key!(Name, Set, "key", OutputType);`
// The `Set` is one of the PropertySet it belongs to.
// The `key` is the raw property key string.
// The `OutputType` is the type of the property value.
// 
// To get the property value, use the `get` method.
// Example usage:
// 
// ``` no_run
// use optee_utee::{PropertyKey, TaAppId};
// 
// let my_property = TaAppId.get()?;
// ```
define_property_key!(TaAppId, CurrentTa, "gpd.ta.appID", Uuid);
define_property_key!(
    TaSingleInstance,
    CurrentTa,
    "gpd.ta.singleInstance",
    bool
);
define_property_key!(
    TaMultiSession,
    CurrentTa,
    "gpd.ta.multiSession",
    bool
);
define_property_key!(
    TaInstanceKeepAlive,
    CurrentTa,
    "gpd.ta.instanceKeepAlive",
    bool
);
define_property_key!(TaDataSize, CurrentTa, "gpd.ta.dataSize", u32);
define_property_key!(TaStackSize, CurrentTa, "gpd.ta.stackSize", u32);
define_property_key!(TaVersion, CurrentTa, "gpd.ta.version", String);
define_property_key!(
    TaDescription,
    CurrentTa,
    "gpd.ta.description",
    String
);
define_property_key!(TaEndian, CurrentTa, "gpd.ta.endian", u32);
define_property_key!(
    TaDoesNotCloseHandleOnCorruptObject,
    CurrentTa,
    "gpd.ta.doesNotCloseHandleOnCorruptObject",
    bool
);
define_property_key!(
    ClientIdentity,
    CurrentClient,
    "gpd.client.identity",
    Identity
);
define_property_key!(ClientEndian, CurrentClient, "gpd.client.endian", u32);
define_property_key!(
    TeeApiVersion,
    TeeImplementation,
    "gpd.tee.apiversion",
    String
);
define_property_key!(
    TeeInternalCoreVersion,
    TeeImplementation,
    "gpd.tee.internalCore.version",
    u32
);
define_property_key!(
    TeeDescription,
    TeeImplementation,
    "gpd.tee.description",
    String
);
define_property_key!(
    TeeDeviceId,
    TeeImplementation,
    "gpd.tee.deviceID",
    Uuid
);
define_property_key!(
    TeeSystemTimeProtectionLevel,
    TeeImplementation,
    "gpd.tee.systemTime.protectionLevel",
    u32
);
define_property_key!(
    TeeTaPersistentTimeProtectionLevel,
    TeeImplementation,
    "gpd.tee.TAPersistentTime.protectionLevel",
    u32
);
define_property_key!(
    TeeArithMaxBigIntSize,
    TeeImplementation,
    "gpd.tee.arith.maxBigIntSize",
    u32
);
define_property_key!(
    TeeCryptographyEcc,
    TeeImplementation,
    "gpd.tee.cryptography.ecc",
    bool
);
define_property_key!(
    TeeCryptographyNist,
    TeeImplementation,
    "gpd.tee.cryptography.nist",
    bool
);
define_property_key!(
    TeeCryptographyBsiR,
    TeeImplementation,
    "gpd.tee.cryptography.bsi-r",
    bool
);
define_property_key!(
    TeeCryptographyBsiT,
    TeeImplementation,
    "gpd.tee.cryptography.bsi-t",
    bool
);
define_property_key!(
    TeeCryptographyIetf,
    TeeImplementation,
    "gpd.tee.cryptography.ietf",
    bool
);
define_property_key!(
    TeeCryptographyOcta,
    TeeImplementation,
    "gpd.tee.cryptography.octa",
    bool
);
define_property_key!(
    TeeTrustedStoragePrivateRollbackProtection,
    TeeImplementation,
    "gpd.tee.trustedStorage.private.rollbackProtection",
    u32
);
define_property_key!(
    TeeTrustedStoragePersoRollbackProtection,
    TeeImplementation,
    "gpd.tee.trustedStorage.perso.rollbackProtection",
    u32
);
define_property_key!(
    TeeTrustedStorageProtectedRollbackProtection,
    TeeImplementation,
    "gpd.tee.trustedStorage.protected.rollbackProtection",
    u32
);
define_property_key!(
    TeeTrustedStorageAntiRollbackProtectionLevel,
    TeeImplementation,
    "gpd.tee.trustedStorage.antiRollback.protectionLevel",
    u32
);
define_property_key!(
    TeeTrustedStorageRollbackDetectionProtectionLevel,
    TeeImplementation,
    "gpd.tee.trustedStorage.rollbackDetection.protectionLevel",
    u32
);
define_property_key!(
    TeeTrustedOsImplementationVersion,
    TeeImplementation,
    "gpd.tee.trustedos.implementation.version",
    String
);
define_property_key!(
    TeeTrustedOsImplementationBinaryVersion,
    TeeImplementation,
    "gpd.tee.trustedos.implementation.binaryversion",
    Vec<u8>
);
define_property_key!(
    TeeTrustedOsManufacturer,
    TeeImplementation,
    "gpd.tee.trustedos.manufacturer",
    String
);
define_property_key!(
    TeeFirmwareImplementationVersion,
    TeeImplementation,
    "gpd.tee.firmware.implementation.version",
    String
);
define_property_key!(
    TeeFirmwareImplementationBinaryVersion,
    TeeImplementation,
    "gpd.tee.firmware.implementation.binaryversion",
    Vec<u8>
);
define_property_key!(
    TeeFirmwareManufacturer,
    TeeImplementation,
    "gpd.tee.firmware.manufacturer",
    String
);
define_property_key!(
    TeeEventMaxSources,
    TeeImplementation,
    "gpd.tee.event.maxSources",
    u32
);