tss-esapi 8.0.0-alpha

Rust-native wrapper around TSS 2.0 Enhanced System API
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
// Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use crate::{
    constants::tss::TPM2_RH_UNASSIGNED,
    context::handle_manager::HandleDropAction,
    ffi::to_owned_bytes,
    handles::ObjectHandle,
    handles::{handle_conversion::TryIntoNotNone, TpmHandle},
    structures::Auth,
    structures::Name,
    tss2_esys::{
        Esys_TR_Close, Esys_TR_Deserialize, Esys_TR_FromTPMPublic, Esys_TR_GetName,
        Esys_TR_Serialize, Esys_TR_SetAuth,
    },
    Context, Error, Result, ReturnCode, WrapperErrorKind,
};
use log::error;
use std::convert::{TryFrom, TryInto};
use std::ptr::null_mut;
use zeroize::Zeroize;

impl Context {
    /// Set the authentication value for a given object handle in the ESYS context.
    ///
    /// # Arguments
    /// * `object_handle` - The [ObjectHandle] associated with an object for which the auth is to be set.
    /// * `auth` -  The [Auth] that is to be set.
    ///
    /// ```rust
    /// # use tss_esapi::{Context, TctiNameConf};
    /// use tss_esapi::{handles::ObjectHandle, structures::Auth};
    /// # // Create context
    /// # let mut context =
    /// #     Context::new(
    /// #         TctiNameConf::from_environment_variable().expect("Failed to get TCTI"),
    /// #     ).expect("Failed to create Context");
    ///
    /// // Sets auth for Owner to empty string.
    /// context
    ///     .tr_set_auth(ObjectHandle::Owner, Auth::default())
    ///     .expect("Failed to call tr_set_auth");
    /// ```
    pub fn tr_set_auth(&mut self, object_handle: ObjectHandle, auth: Auth) -> Result<()> {
        let mut auth_value = auth.into();
        ReturnCode::ensure_success(
            unsafe { Esys_TR_SetAuth(self.mut_context(), object_handle.into(), &auth_value) },
            |ret| {
                auth_value.buffer.zeroize();
                error!("Error when setting authentication value: {:#010X}", ret);
            },
        )
    }

    /// Retrieve the name of an object from the object handle.
    ///
    /// # Arguments
    /// * `object_handle` - Handle to the object for which the 'name' shall be retrieved.
    ///
    /// # Returns
    /// The objects name.
    ///
    /// # Example
    /// ```rust
    /// # use tss_esapi::{
    /// #     Context, TctiNameConf, attributes::{SessionAttributes, NvIndexAttributes},
    /// #     constants::SessionType, handles::NvIndexTpmHandle,
    /// #     interface_types::{algorithm::HashingAlgorithm, resource_handles::Provision},
    /// #     structures::{SymmetricDefinition, NvPublic},
    /// # };
    /// # // Create context
    /// # let mut context =
    /// #     Context::new(
    /// #         TctiNameConf::from_environment_variable().expect("Failed to get TCTI"),
    /// #     ).expect("Failed to create Context");
    /// #
    /// # let session = context
    /// #     .start_auth_session(
    /// #         None,
    /// #         None,
    /// #         None,
    /// #         SessionType::Hmac,
    /// #         SymmetricDefinition::AES_256_CFB,
    /// #         HashingAlgorithm::Sha256,
    /// #     )
    /// #     .expect("Failed to create session")
    /// #     .expect("Received invalid handle");
    /// # let (session_attributes, session_attributes_mask) = SessionAttributes::builder()
    /// #     .with_decrypt(true)
    /// #     .with_encrypt(true)
    /// #     .build();
    /// # context.tr_sess_set_attributes(session, session_attributes, session_attributes_mask)
    /// #     .expect("Failed to set attributes on session");
    /// # context.set_sessions((Some(session), None, None));
    /// #
    /// # let nv_index = NvIndexTpmHandle::new(0x01500401)
    /// #     .expect("Failed to create NV index tpm handle");
    /// #
    /// # // Create NV index attributes
    /// # let owner_nv_index_attributes = NvIndexAttributes::builder()
    /// #     .with_owner_write(true)
    /// #     .with_owner_read(true)
    /// #     .build()
    /// #     .expect("Failed to create owner nv index attributes");
    /// #
    /// # // Create owner nv public.
    /// # let owner_nv_public = NvPublic::builder()
    /// #     .with_nv_index(nv_index)
    /// #     .with_index_name_algorithm(HashingAlgorithm::Sha256)
    /// #     .with_index_attributes(owner_nv_index_attributes)
    /// #     .with_data_area_size(32)
    /// #     .build()
    /// #     .expect("Failed to build NvPublic for owner");
    /// #
    /// # // Define the NV space.
    /// # let nv_index_handle = context
    /// #     .nv_define_space(Provision::Owner, None, owner_nv_public)
    /// #     .expect("Call to nv_define_space failed");
    ///
    /// // Get the name using tr_get_name
    /// let tr_get_name_result = context.tr_get_name(nv_index_handle.into());
    ///
    /// // Get the name from the NV by calling nv_read_public
    /// let nv_read_public_result = context.nv_read_public(nv_index_handle);
    /// #
    /// # context
    /// #    .nv_undefine_space(Provision::Owner, nv_index_handle)
    /// #    .expect("Call to nv_undefine_space failed");
    /// #
    /// // Process result by comparing the names
    /// let (_public_area, expected_name) = nv_read_public_result.expect("Call to nv_read_public failed");
    /// let actual_name = tr_get_name_result.expect("Call to tr_get_name failed");
    /// assert_eq!(expected_name, actual_name);
    /// ```
    pub fn tr_get_name(&mut self, object_handle: ObjectHandle) -> Result<Name> {
        let mut name_ptr = null_mut();
        ReturnCode::ensure_success(
            unsafe { Esys_TR_GetName(self.mut_context(), object_handle.into(), &mut name_ptr) },
            |ret| {
                error!("Error in getting name: {:#010X}", ret);
            },
        )?;
        Name::try_from(Context::ffi_data_to_owned(name_ptr))
    }

    /// Used to construct an esys object from the resources inside the TPM.
    ///
    /// # Arguments
    /// * `tpm_handle` - The TPM handle that references the TPM object for which
    ///                  the ESYS object is being created.
    ///
    /// # Returns
    /// A handle to the ESYS object that was created from a TPM resource.
    ///
    /// # Example
    /// ```rust
    /// # use tss_esapi::{
    /// #     Context, TctiNameConf, attributes::{SessionAttributes, NvIndexAttributes},
    /// #     constants::SessionType,
    /// #     interface_types::{algorithm::HashingAlgorithm, resource_handles::Provision},
    /// #     structures::{SymmetricDefinition, NvPublic},
    /// # };
    /// use tss_esapi::{
    ///     handles::NvIndexTpmHandle,
    /// };
    /// # // Create context
    /// # let mut context =
    /// #     Context::new(
    /// #         TctiNameConf::from_environment_variable().expect("Failed to get TCTI"),
    /// #     ).expect("Failed to create Context");
    /// #
    /// # let session = context
    /// #     .start_auth_session(
    /// #         None,
    /// #         None,
    /// #         None,
    /// #         SessionType::Hmac,
    /// #         SymmetricDefinition::AES_256_CFB,
    /// #         HashingAlgorithm::Sha256,
    /// #     )
    /// #     .expect("Failed to create session")
    /// #     .expect("Received invalid handle");
    /// # let (session_attributes, session_attributes_mask) = SessionAttributes::builder()
    /// #     .with_decrypt(true)
    /// #     .with_encrypt(true)
    /// #     .build();
    /// # context.tr_sess_set_attributes(session, session_attributes, session_attributes_mask)
    /// #     .expect("Failed to set attributes on session");
    /// # context.set_sessions((Some(session), None, None));
    /// #
    /// let nv_index = NvIndexTpmHandle::new(0x01500402)
    ///     .expect("Failed to create NV index tpm handle");
    /// #
    /// # // Create NV index attributes
    /// # let owner_nv_index_attributes = NvIndexAttributes::builder()
    /// #     .with_owner_write(true)
    /// #     .with_owner_read(true)
    /// #     .build()
    /// #     .expect("Failed to create owner nv index attributes");
    /// #
    /// # // Create owner nv public.
    /// # let owner_nv_public = NvPublic::builder()
    /// #     .with_nv_index(nv_index)
    /// #     .with_index_name_algorithm(HashingAlgorithm::Sha256)
    /// #     .with_index_attributes(owner_nv_index_attributes)
    /// #     .with_data_area_size(32)
    /// #     .build()
    /// #     .expect("Failed to build NvPublic for owner");
    /// #
    /// # // Define the NV space.
    /// # let nv_index_handle = context
    /// #     .nv_define_space(Provision::Owner, None, owner_nv_public)
    /// #     .expect("Call to nv_define_space failed");
    /// #
    /// # // Retrieve the name of the NV space.
    /// # let nv_read_public_result = context.nv_read_public(nv_index_handle);
    /// #
    /// # // Close the handle (remove all the metadata).
    /// # let mut handle_to_be_closed = nv_index_handle.into();
    /// # let tr_close_result = context
    /// #     .tr_close(&mut handle_to_be_closed);
    /// #
    /// // Call function without session (session can be provided in order to
    /// // verify that the public data read actually originates from this TPM).
    /// let retrieved_handle = context.execute_without_session(|ctx| {
    ///       ctx.tr_from_tpm_public(nv_index.into())
    /// })
    /// .expect("Call to tr_from_tpm_public failed.");
    /// #
    /// # // Use the retrieved handle to get the name of the object.
    /// # let tr_get_name_result = context
    /// #     .tr_get_name(retrieved_handle);
    /// #
    /// # context
    /// #    .nv_undefine_space(Provision::Owner, retrieved_handle.into())
    /// #    .expect("Call to nv_undefine_space failed");
    /// #
    /// # // Process results.
    /// # tr_close_result.expect("Call to tr_close_result failed");
    /// # let (_, expected_name) = nv_read_public_result.expect("Call to nv_read_public failed");
    /// # let actual_name = tr_get_name_result.expect("Call to tr_get_name failed");
    /// # assert_eq!(expected_name, actual_name);
    /// ```
    pub fn tr_from_tpm_public(&mut self, tpm_handle: TpmHandle) -> Result<ObjectHandle> {
        let mut object = ObjectHandle::None.into();
        ReturnCode::ensure_success(
            unsafe {
                Esys_TR_FromTPMPublic(
                    self.mut_context(),
                    tpm_handle.into(),
                    self.optional_session_1(),
                    self.optional_session_2(),
                    self.optional_session_3(),
                    &mut object,
                )
            },
            |ret| {
                error!(
                    "Error when getting ESYS handle from TPM handle: {:#010X}",
                    ret
                );
            },
        )?;
        self.handle_manager.add_handle(
            object.into(),
            if tpm_handle.may_be_flushed() {
                HandleDropAction::Flush
            } else {
                HandleDropAction::Close
            },
        )?;
        Ok(object.into())
    }

    /// Instructs the ESAPI to release the metadata and resources allocated for a specific ObjectHandle.
    ///
    /// This is useful for cleaning up handles for which the context cannot be flushed.
    ///
    /// # Arguments
    /// * object_handle`- An [ObjectHandle] referring to an object for which all metadata and
    ///                   resources is going to be released.
    ///
    /// # Example
    /// ```rust
    /// # use tss_esapi::{
    /// #     Context, TctiNameConf, attributes::{SessionAttributes, NvIndexAttributes},
    /// #     constants::SessionType, handles::NvIndexTpmHandle,
    /// #     interface_types::{algorithm::HashingAlgorithm, resource_handles::Provision},
    /// #     structures::{SymmetricDefinition, NvPublic},
    /// # };
    /// # // Create context
    /// # let mut context =
    /// #     Context::new(
    /// #         TctiNameConf::from_environment_variable().expect("Failed to get TCTI"),
    /// #     ).expect("Failed to create Context");
    /// #
    /// # let session = context
    /// #     .start_auth_session(
    /// #         None,
    /// #         None,
    /// #         None,
    /// #         SessionType::Hmac,
    /// #         SymmetricDefinition::AES_256_CFB,
    /// #         HashingAlgorithm::Sha256,
    /// #     )
    /// #     .expect("Failed to create session")
    /// #     .expect("Received invalid handle");
    /// # let (session_attributes, session_attributes_mask) = SessionAttributes::builder()
    /// #     .with_decrypt(true)
    /// #     .with_encrypt(true)
    /// #     .build();
    /// # context.tr_sess_set_attributes(session, session_attributes, session_attributes_mask)
    /// #     .expect("Failed to set attributes on session");
    /// # context.set_sessions((Some(session), None, None));
    /// #
    /// let nv_index = NvIndexTpmHandle::new(0x01500403)
    ///     .expect("Failed to create NV index tpm handle");
    /// #
    /// # // Create NV index attributes
    /// # let owner_nv_index_attributes = NvIndexAttributes::builder()
    /// #     .with_owner_write(true)
    /// #     .with_owner_read(true)
    /// #     .build()
    /// #     .expect("Failed to create owner nv index attributes");
    /// #
    /// # // Create owner nv public.
    /// # let owner_nv_public = NvPublic::builder()
    /// #     .with_nv_index(nv_index)
    /// #     .with_index_name_algorithm(HashingAlgorithm::Sha256)
    /// #     .with_index_attributes(owner_nv_index_attributes)
    /// #     .with_data_area_size(32)
    /// #     .build()
    /// #     .expect("Failed to build NvPublic for owner");
    /// #
    /// # // Define the NV space.
    /// # let nv_index_handle = context
    /// #     .nv_define_space(Provision::Owner, None, owner_nv_public)
    /// #     .expect("Call to nv_define_space failed");
    /// #
    /// # // Close the handle (remove all the metadata).
    /// # let mut handle_to_be_closed = nv_index_handle.into();
    /// let tr_close_result = context
    ///     .tr_close(&mut handle_to_be_closed);
    /// #
    /// # // Use the retrieved handle to get the name of the object.
    /// # let tr_get_name_result = context
    /// #     .tr_get_name(nv_index_handle.into());
    /// #
    /// # // Call function without session (session can be provided in order to
    /// # // verify that the public data read actually originates from this TPM).
    /// # let retrieved_handle = context.execute_without_session(|ctx| {
    /// #       ctx.tr_from_tpm_public(nv_index.into())
    /// # })
    /// # .expect("Call to tr_from_tpm_public failed.");
    /// #
    /// # context
    /// #    .nv_undefine_space(Provision::Owner, retrieved_handle.into())
    /// #    .expect("Call to nv_undefine_space failed");
    /// #
    /// // Process results.
    /// tr_close_result.expect("Call to tr_close failed.");
    /// # tr_get_name_result.expect_err("Calling tr_get_name with invalid handle did not result in an error.");
    /// ```
    pub fn tr_close(&mut self, object_handle: &mut ObjectHandle) -> Result<()> {
        let mut rsrc_handle = object_handle.try_into_not_none()?;
        ReturnCode::ensure_success(
            unsafe { Esys_TR_Close(self.mut_context(), &mut rsrc_handle) },
            |ret| {
                error!("Error when closing an ESYS handle: {:#010X}", ret);
            },
        )?;

        self.handle_manager.set_as_closed(*object_handle)?;
        *object_handle = ObjectHandle::from(rsrc_handle);
        Ok(())
    }

    #[cfg(has_esys_tr_get_tpm_handle)]
    /// Retrieve the `TpmHandle` stored in the given object.
    pub fn tr_get_tpm_handle(&mut self, object_handle: ObjectHandle) -> Result<TpmHandle> {
        use crate::tss2_esys::Esys_TR_GetTpmHandle;
        let mut tpm_handle = TPM2_RH_UNASSIGNED;
        ReturnCode::ensure_success(
            unsafe {
                Esys_TR_GetTpmHandle(self.mut_context(), object_handle.into(), &mut tpm_handle)
            },
            |ret| {
                error!(
                    "Error when getting TPM handle from ESYS handle: {:#010X}",
                    ret
                );
            },
        )?;
        TpmHandle::try_from(tpm_handle)
    }

    /// Serialize the metadata of the object identified by `handle` into a new buffer.
    ///
    /// This can subsequently be used to recreate the object in the future.
    /// The object can only be recreated in a new context, if it was made persistent
    /// with `evict_control`.
    ///
    /// # Arguments
    /// * `handle` - A handle to the object which should be serialized.
    ///
    /// # Returns
    /// A buffer that can be stored and later deserialized.
    ///
    /// # Errors
    /// * if the TPM cannot serialize the handle, a TSS error is returned.
    /// * if the buffer length cannot be converted to a `usize`, an `InvalidParam`
    /// wrapper error is returned.
    ///
    /// ```rust
    /// # use tss_esapi::{
    /// #     Context, TctiNameConf,
    /// #     interface_types::resource_handles::Hierarchy,
    /// #     structures::HashScheme,
    /// #     utils::create_unrestricted_signing_ecc_public,
    /// #     interface_types::{
    /// #         ecc::EccCurve,
    /// #         algorithm::HashingAlgorithm,
    /// #         session_handles::AuthSession,
    /// #     },
    /// #     structures::EccScheme,
    /// # };
    /// # let mut context =
    /// #     Context::new(
    /// #         TctiNameConf::from_environment_variable().expect("Failed to get TCTI"),
    /// #     ).expect("Failed to create Context");
    /// # context.set_sessions((Some(AuthSession::Password), None, None));
    /// # let public = create_unrestricted_signing_ecc_public(
    /// #     EccScheme::EcDsa(HashScheme::new(HashingAlgorithm::Sha256)),
    /// #     EccCurve::NistP256)
    /// #     .unwrap();
    /// let key_handle = context
    ///     .create_primary(
    ///         Hierarchy::Owner,
    ///         public,
    ///         None,
    ///         None,
    ///         None,
    ///         None,
    ///     ).unwrap()
    ///     .key_handle;
    /// let data = context.tr_serialize(key_handle.into()).unwrap();
    /// ```
    pub fn tr_serialize(&mut self, handle: ObjectHandle) -> Result<Vec<u8>> {
        let mut len = 0;
        let mut buffer: *mut u8 = null_mut();
        ReturnCode::ensure_success(
            unsafe { Esys_TR_Serialize(self.mut_context(), handle.into(), &mut buffer, &mut len) },
            |ret| {
                error!("Error while serializing handle: {}", ret);
            },
        )?;
        Ok(to_owned_bytes(
            buffer,
            len.try_into().map_err(|e| {
                error!("Failed to convert buffer len to usize: {}", e);
                Error::local_error(WrapperErrorKind::InvalidParam)
            })?,
        ))
    }

    /// Deserialize the metadata from `buffer` into a new object.
    ///
    /// This can be used to restore an object from a context in the past.
    ///
    /// # Arguments
    /// * `buffer` - The buffer containing the data to restore the object.
    ///              It can be created using [`tr_serialize`](Self::tr_serialize).
    ///
    /// # Returns
    /// A handle to the object that was created from the buffer.
    ///
    /// # Errors
    /// * if the TPM cannot deserialize the buffer, a TSS error is returned.
    /// * if the buffer length cannot be converted to a `usize`, an `InvalidParam`
    /// wrapper error is returned.
    ///
    /// ```rust
    /// # use tss_esapi::{
    /// #     Context, TctiNameConf,
    /// #     interface_types::resource_handles::Hierarchy,
    /// #     structures::HashScheme,
    /// #     utils::create_unrestricted_signing_ecc_public,
    /// #     interface_types::{
    /// #         ecc::EccCurve,
    /// #         algorithm::HashingAlgorithm,
    /// #         session_handles::AuthSession,
    /// #     },
    /// #     structures::EccScheme,
    /// # };
    /// # let mut context =
    /// #     Context::new(
    /// #         TctiNameConf::from_environment_variable().expect("Failed to get TCTI"),
    /// #     ).expect("Failed to create Context");
    /// # context.set_sessions((Some(AuthSession::Password), None, None));
    /// # let public = create_unrestricted_signing_ecc_public(
    /// #     EccScheme::EcDsa(HashScheme::new(HashingAlgorithm::Sha256)),
    /// #     EccCurve::NistP256)
    /// #     .unwrap();
    /// let key_handle = context
    ///     .create_primary(
    ///         Hierarchy::Owner,
    ///         public,
    ///         None,
    ///         None,
    ///         None,
    ///         None,
    ///     ).unwrap()
    ///     .key_handle;
    /// # context.set_sessions((None, None, None));
    /// let public_key = context.read_public(key_handle).unwrap();
    /// let data = context.tr_serialize(key_handle.into()).unwrap();
    /// let new_handle = context.tr_deserialize(&data).unwrap();
    /// assert_eq!(public_key, context.read_public(new_handle.into()).unwrap());
    /// ```
    pub fn tr_deserialize(&mut self, buffer: &Vec<u8>) -> Result<ObjectHandle> {
        let mut handle = TPM2_RH_UNASSIGNED;
        ReturnCode::ensure_success(
            unsafe {
                Esys_TR_Deserialize(
                    self.mut_context(),
                    buffer.as_ptr(),
                    buffer.len().try_into().map_err(|e| {
                        error!("Failed to convert buffer len to usize: {}", e);
                        Error::local_error(WrapperErrorKind::InvalidParam)
                    })?,
                    &mut handle,
                )
            },
            |ret| {
                error!("Error while deserializing buffer: {}", ret);
            },
        )?;
        Ok(ObjectHandle::from(handle))
    }
}