pub struct Context { /* private fields */ }
Expand description

Safe abstraction over an ESYS_CONTEXT.

Serves as a low-level abstraction interface to the TPM, providing a thin wrapper around the unsafe FFI calls. It is meant for more advanced uses of the TSS where control over all parameters is necessary or important.

The methods it exposes take the parameters advertised by the specification, with some of the parameters being passed as generated by bindgen and others in a more convenient/Rust-efficient way.

The context also keeps track of all object allocated and deallocated through it and, before being dropped, will attempt to close all outstanding handles. However, care must be taken by the client to not exceed the maximum number of slots available from the RM.

Code safety-wise, the methods should cover the two kinds of problems that might arise:

  • in terms of memory safety, all parameters passed down to the TSS are verified and the library stack is then trusted to provide back valid outputs
  • in terms of thread safety, all methods require a mutable reference to the context object, ensuring that no two threads can use the context at the same time for an operation (barring use of unsafe constructs on the client side) More testing and verification will be added to ensure this.

For most methods, if the wrapped TSS call fails and returns a non-zero TPM2_RC, a corresponding Tss2ResponseCode will be created and returned as an Error. Wherever this is not the case or additional error types can be returned, the method definition should mention it.

Implementations

Perform an asymmetric RSA encryption.

Perform an asymmetric RSA decryption.

Generate a quote on the selected PCRs

Errors
  • if the qualifying data provided is too long, a WrongParamSize wrapper error will be returned

Get current capability information about the TPM.

Test if the given parameters are supported by the TPM.

Errors
  • if any of the public parameters is not compatible with the TPM, an Err containing the specific unmarshalling error will be returned.

Save the context of an object from the TPM and return it.

Errors
  • if conversion from TPMS_CONTEXT to TpmsContext fails, a WrongParamSize error will be returned

Load a previously saved context into the TPM and return the object handle.

Errors
  • if conversion from TpmsContext to the native TPMS_CONTEXT fails, a WrongParamSize error will be returned

Flush the context of an object from the TPM.

Example

// Create session for a key
let session = context
    .start_auth_session(
        None,
        None,
        None,
        SessionType::Hmac,
        SymmetricDefinition::AES_256_CFB,
        HashingAlgorithm::Sha256,
    )
    .expect("Failed to create session")
    .expect("Recived invalid handle");
let (session_attributes, session_attributes_mask) = SessionAttributesBuilder::new()
    .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");

// Create public area for a rsa key
let public_area = create_unrestricted_signing_rsa_public(
        AsymSchemeUnion::RSASSA(HashingAlgorithm::Sha256),
        2048,
        0,
    )
    .expect("Failed to create rsa public area");

// Execute context methods using the session
context.execute_with_session(Some(session), |ctx| {
    let random_digest = ctx.get_random(16)
        .expect("Call to get_random failed");
    let key_auth = Auth::try_from(random_digest.value().to_vec())
        .expect("Failed to create Auth");
    let key_handle = ctx
        .create_primary(
            Hierarchy::Owner,
            &public_area,
            Some(&key_auth),
            None,
            None,
            None,
        )
        .expect("Failed to create primary key")
        .key_handle;

        // Flush the context of the key.
        ctx.flush_context(key_handle.into()).expect("Call to flush_context failed");
        assert!(ctx.read_public(key_handle).is_err());
})

Evicts persistent objects or allows certain transient objects to be made peristent.

Details

In order to be able to perform this action an authorization session is required.

Arguments
  • auth - An a handle used for authorization that is limited to the ones specified in Provision.
  • object_handle - The handle of a loaded object.
  • persistant - If the object_handle is transient object then this then this will become the persistant handle of that object. If the object_handle refers to a persistant object then this shall be the persistant handle of that object.
Returns

If the input object_handle was transient object then it will be made persistent and the returned ObjectHandle will refer to the persistent object.

If the input object_handle refers to a presistent object the returned value will be ObjectHandle::None and the input object_handle will not be valid after this call is made.

Example

Make transient object peristent:

use tss_esapi::{
    interface_types::{
        resource_handles::Provision,
        dynamic_handles::Persistent,
        session_handles::AuthSession,
    },
};
// Create interface type Persistent by using the persistent tpm handle.
let persistent = Persistent::Persistent(persistent_tpm_handle);
// Make transient_object_handle persistent.
// An authorization session is required!
let mut persistent_object_handle = context.execute_with_session(Some(AuthSession::Password), |ctx| {
    ctx
        .evict_control(Provision::Owner, transient_object_handle.into(), persistent)
        .expect("Failed to make the transient_object_handle handle persistent")
});

Make persistent object transient

use tss_esapi::{
    interface_types::{
        resource_handles::Provision,
        dynamic_handles::Persistent,
        session_handles::AuthSession,
    },
};
// Create interface type Persistent by using the persistent tpm handle.
let persistent = Persistent::Persistent(persistent_tpm_handle);
// Evict the persitent handle from the tpm
// An authorization session is required!
let _ = context.execute_with_session(Some(AuthSession::Password), |ctx| {
    ctx
        .evict_control(Provision::Owner, retireved_persistant_handle, persistent)
        .expect("Failed to evict persistent handle")
});

Cause the policy to include a signed authorization

Cause the policy to require a secret in authValue

Cause conditional gating of a policy based on an OR’d condition.

The TPM will ensure that the current policy digest equals at least one of the digests. If this is the case, the policyDigest of the policy session is replaced by the value of the different hashes.

Constraints
  • hash_list must be at least 2 and at most 8 elements long
Errors
  • if the hash list provided is too short or too long, a WrongParamSize wrapper error will be returned

Cause conditional gating of a policy based on PCR.

Details

The TPM will use the hash algorithm of the policy_session to calculate a digest from the values of the pcr slots specified in the pcr_selections. This is then compared to pcr_policy_digest if they match then the policyDigest of the policy session is extended.

Errors
  • if the pcr policy digest provided is too long, a WrongParamSize wrapper error will be returned

Cause conditional gating of a policy based on locality.

The TPM will ensure that the current policy can only complete in the specified locality (extended) or any of the specified localities (non-extended).

Cause conditional gating of a policy based on command code of authorized command.

The TPM will ensure that the current policy can only be used to complete the command indicated by code.

Cause conditional gating of a policy based on physical presence.

The TPM will ensure that the current policy can only complete when physical presence is asserted. The way this is done is implementation-specific.

Cause conditional gating of a policy based on command parameters.

The TPM will ensure that the current policy can only be used to authorize a command where the parameters are hashed into cp_hash_a.

Cause conditional gating of a policy based on name hash.

The TPM will ensure that the current policy can only be used to authorize a command acting on an object whose name hashes to name_hash.

Cause conditional gating of a policy based on an authorized policy

The TPM will ensure that the current policy digest is correctly signed by the ticket in check_ticket and that check_ticket is signed by the key named in key_sign. If this is the case, the policyDigest of the policy session is replaced by the value of the key_sign and policy_ref values.

Cause conditional gating of a policy based on authValue.

The TPM will ensure that the current policy requires the user to know the authValue used when creating the object.

Cause conditional gating of a policy based on password.

The TPM will ensure that the current policy requires the user to know the password used when creating the object.

Function for retriving the current policy digest for the session.

Cause conditional gating of a policy based on NV written state.

The TPM will ensure that the NV index that is used has a specific written state.

Bind policy to a specific creation template.

Arguments
  • policy_session - The policy session being extended.
  • template_hash - The digest to be added to the policy.

Create a primary key and return the handle.

The authentication value, initial data, outside info and creation PCRs are passed as slices which are then converted by the method into TSS native structures.

Errors
  • if either of the slices is larger than the maximum size of the native objects, a WrongParamSize wrapper error is returned

Clear all TPM context associated with a specific Owner

Disable or enable the TPM2_CLEAR command

Change authorization for a hierarchy root

Extends a PCR with the specified digests.

Arguments
  • pcr_handle- A PcrHandle to the PCR slot that is to be extended.
  • digests - The DigestValues with which the slot shall be extended.
Details

This method is used to cause an update to the indicated PCR. The digests param contains the digests for specific algorithms that are to be used.

Example
use std::convert::TryFrom;
use tss_esapi::{
    structures::{DigestValues},
    interface_types::algorithm::HashingAlgorithm,
};
// Extend both sha256 and sha1
let mut vals = DigestValues::new();
vals.set(
    HashingAlgorithm::Sha1,
    digest_sha1,
);
vals.set(
    HashingAlgorithm::Sha256,
    digest_sha256,
);
// Use pcr_session for authorization when extending
// PCR 16 with the values for the banks specified in
// vals.
context.execute_with_session(Some(pcr_session), |ctx| {
    ctx.pcr_extend(PcrHandle::Pcr16, vals).expect("Call to pcr_extend failed");
});

Reads the values of a PCR.

Arguments
  • pcr_selection_list - A PcrSelectionList that contains pcr slots in different banks that is going to be read.
Details

The provided PcrSelectionList contains the pcr slots in the different banks that is going to be read. It is possible to select more pcr slots then what will fit in the returned result so the method returns a PcrSelectionList that indicates what values that was read. The values that was read are returned in the PcrData.

Errors
  • Several different errors can occur if conversion of return data fails.
Example
use tss_esapi::{
    interface_types::algorithm::HashingAlgorithm,
    structures::{PcrSelectionListBuilder, PcrSlot},
};
// Create PCR selection list with slots in a bank
// that is going to be read.
let pcr_selection_list = PcrSelectionListBuilder::new()
    .with_selection(HashingAlgorithm::Sha256, &[PcrSlot::Slot0, PcrSlot::Slot1])
    .build();

let (update_counter, read_pcr_list, pcr_data) = context.pcr_read(&pcr_selection_list)
    .expect("Call to pcr_read failed");

Resets the value in a PCR.

Arguments
  • pcr_handle - A PcrHandle to the PCR slot that is to be resetted.
Details

If the attributes of the PCR indicates that it is allowed to reset them and the proper authorization is provided then this method can be used to set the the specified PCR in all banks to 0.

Example

use tss_esapi::{
     handles::PcrHandle
};
context.execute_with_session(Some(pcr_session), |ctx| {
    ctx.pcr_reset(PcrHandle::Pcr16).expect("Call to pcr_reset failed");
});

Allocates an index in the non volatile storage.

Details

This method will instruct the TPM to reserve space for an NV index with the attributes defined in the provided parameters.

Arguments
  • nv_auth - The Provision used for authorization.
  • auth - The authorization value.
  • public_info - The public parameters of the NV area.

Deletes an index in the non volatile storage.

Details

The method will instruct the TPM to remove a nv index.

Arguments
  • nv_auth - The Provision used for authorization.
  • nv_index_handle- The NvIndexHandle associated with the nv area that is to be removed.

Reads the public part of an nv index.

Details

This method is used to read the public area and name of a nv index.

Writes data to an nv index.

Details

This method is used to write a value to the nv memory in the TPM.

Reads data from the nv index.

Details

This method is used to read a value from an area in NV memory of the TPM.

Create a key and return the handle.

The authentication value, initial data, outside info and creation PCRs are passed as slices which are then converted by the method into TSS native structures.

Parameters
  • parent_handle - The KeyHandle of the parent for the new object that is being created.
  • public - The public part of the object that is being created.
  • auth_value - The value used to be used for authorize usage of the object.
  • sensitive_data - The data that is to be sealed, a key or derivation values.
  • outside_info - Data that will be included in the creation data for this object to provide permanent, verifiable linkage between the object that is being created and some object owner data.
  • creation_pcrs- PCRs that will be used in creation data.
Errors
  • if either of the slices is larger than the maximum size of the native objects, a WrongParamSize wrapper error is returned

Load a previously generated key back into the TPM and return its new handle.

Load an external key into the TPM and return its new handle.

Load the public part of an external key and return its new handle.

Read the public part of a key currently in the TPM and return it.

Activates a credential in a way that ensures parameters are validated.

Perform actions to create a IDObject containing an activation credential.

This does not use any TPM secrets, and is really just a convenience function.

Unseal and return data from a Sealed Data Object

Change authorization for a TPM-resident object.

Get a number of random bytes from the TPM and return them.

Errors
  • if converting num_bytes to u16 fails, a WrongParamSize will be returned

Add additional information into the TPM RNG state

Start new authentication session and return the Session object associated with the session.

If the returned session handle from ESYS api is ESYS_TR_NONE then the value of the option in the result will be None.

Example
// Create auth session without key_handle, bind_handle
// and Nonce
let session = context
    .start_auth_session(
        None,
        None,
        None,
        SessionType::Hmac,
        SymmetricDefinition::AES_256_CFB,
        HashingAlgorithm::Sha256,
    )
    .expect("Failed to create session")
    .expect("Recived invalid handle");

Restart the TPM Policy

Verify if a signature was generated by signing a given digest with a key in the TPM.

Sign a digest with a key present in the TPM and return the signature.

Send a TPM2_STARTUP command to the TPM

Send a TPM2_SHUTDOWN command to the TPM

Performs symmetric encryption or decryption of the data using the key associated with the key_handle

Arguments
  • key_handle - A KeyHandle to the key to be used.
  • decrypt - A boolean indicating if the data should be decrypted or encrypted. If set to true the data will be decrypted else encrypted.
  • mode - The SymmetricMode to be used.
  • in_data - The data that is going to be decrypted or encrypted.
  • initial_value_in - An initial value as required by the algorithm.
Example
use tss_esapi::interface_types::session_handles::AuthSession;
use tss_esapi::interface_types::algorithm::SymmetricMode;
// Encrypt the data
let (encrypted_data, _initial_value_out) =
    context.execute_with_session(Some(AuthSession::Password), |ctx| {
        ctx.encrypt_decrypt_2(
            symmetric_key_handle, // Handle to a symmetric key
            false,                // false, indicates that the data should be encrypted.
            SymmetricMode::Cfb,   // The symmetric mode of the encryption.
            &data,                // The data that is to be encrypted.
            &initial_value,       // Initial value needed by the algorithmen.
        )
        .expect("Call to encrypt_decrypt_2 failed when encrypting data")
    });

assert_ne!(data, encrypted_data);

Hashes the provided data using the specified algorithm.

Details

Performs the specified hash operation on a data buffer and return the result. The HashCheckTicket indicates if the hash can be used in a signing operation that uses restricted signing key.

Example
let input_data = MaxBuffer::try_from("There is no spoon".as_bytes().to_vec())
    .expect("Failed to create buffer for input data.");
let expected_hashed_data: [u8; 32] = [
    0x6b, 0x38, 0x4d, 0x2b, 0xfb, 0x0e, 0x0d, 0xfb, 0x64, 0x89, 0xdb, 0xf4, 0xf8, 0xe9,
    0xe5, 0x2f, 0x71, 0xee, 0xb1, 0x0d, 0x06, 0x4c, 0x56, 0x59, 0x70, 0xcd, 0xd9, 0x44,
    0x43, 0x18, 0x5d, 0xc1,
];
let expected_hierarchy = Hierarchy::Owner;
let (actual_hashed_data, ticket) = context
    .hash(
        &input_data,
        HashingAlgorithm::Sha256,
        expected_hierarchy,
    )
    .expect("Call to hash failed.");
assert_eq!(expected_hashed_data.len(), actual_hashed_data.len());
assert_eq!(&expected_hashed_data[..], &actual_hashed_data[..]);
assert_eq!(ticket.hierarchy(), expected_hierarchy);

Asks the TPM to compute an HMAC over buffer with the specified key

Example
// Create a key
let object_attributes = ObjectAttributesBuilder::new()
    .with_sign_encrypt(true)
    .with_sensitive_data_origin(true)
    .with_user_with_auth(true)
    .build()
    .expect("Failed to build object attributes");
let key_pub = Tpm2BPublicBuilder::new()
    .with_type(TPM2_ALG_KEYEDHASH)
    .with_name_alg(TPM2_ALG_SHA256)
    .with_parms(PublicParmsUnion::KeyedHashDetail(KeyedHashParameters::new(
        KeyedHashScheme::HMAC_SHA_256,
    )))
    .with_object_attributes(object_attributes)
    .build()
    .unwrap();

let input_data = MaxBuffer::try_from("There is no spoon".as_bytes().to_vec())
    .expect("Failed to create buffer for input data.");

let hmac = context.execute_with_nullauth_session(|ctx| {
    let key = ctx.create_primary(Hierarchy::Owner, &key_pub, None, None, None, None).unwrap();

    ctx.hmac(key.key_handle.into(), &input_data, HashingAlgorithm::Sha256)
}).unwrap();
Errors
  • if any of the public parameters is not compatible with the TPM, an Err containing the specific unmarshalling error will be returned.

Execute the TPM self test and returns the result

Get the TPM self test result

The returned buffer data is manufacturer-specific information.

Set the given attributes on a given session.

Get session attribute flags.

Set the authentication value for a given object handle in the ESYS context.

Retrieve the name of an object from the object handle

Used to construct an esys object from the resources inside the TPM.

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.

Create a new ESYS context based on the desired TCTI

Warning

The client is responsible for ensuring that the context can be initialized safely, threading-wise. Some TCTI are not safe to execute with multiple commands in parallel. If the sequence of commands to the TPM is interrupted by another application, commands might fail unexpectedly. If multiple applications are using the TPM in parallel, make sure to use the TABRMD TCTI which will offer multi-user support to a single TPM device. See the specification for more information.

Errors
  • if either Tss2_TctiLdr_Initiialize or Esys_Initialize fail, a corresponding Tss2ResponseCode will be returned

Create a new ESYS context based on the TAB Ressource Manager Daemon. The TABRMD will make sure that multiple users can use the TPM safely.

Errors
  • if either Tss2_TctiLdr_Initiialize or Esys_Initialize fail, a corresponding Tss2ResponseCode will be returned

Set the sessions to be used in calls to ESAPI.

Details

In some calls these sessions are optional and in others they are required.

Example
// Create auth session without key_handle, bind_handle
// and Nonce
let auth_session = context
    .start_auth_session(
        None,
        None,
        None,
        SessionType::Hmac,
        SymmetricDefinition::AES_256_CFB,
        HashingAlgorithm::Sha256,
    )
    .expect("Failed to create session");

// Set auth_session as the first handle to be
// used in calls to ESAPI no matter if it None
// or not.
context.set_sessions((auth_session, None, None));

Clears any sessions that have been set

This will result in the None handle being used in all calls to ESAPI.

Example
// Use password session for auth
context.set_sessions((Some(AuthSession::Password), None, None));

// Clear auth sessions
context.clear_sessions();

Returns the sessions that are currently set.

Example
// Use password session for auth
context.set_sessions((Some(AuthSession::Password), None, None));

// Retreive sessions in use
let (session_1, session_2, session_3) = context.sessions();
assert_eq!(Some(AuthSession::Password), session_1);
assert_eq!(None, session_2);
assert_eq!(None, session_3);

Execute the closure in f with the specified set of sessions, and sets the original sessions back afterwards

Executes the closure with a single session set, and the others set to None

Executes the closure without any sessions,

Executes the closure with a newly generated empty session

Details

The session attributes for the generated empty session that is used to execute closure will have the attributes decrypt and encrypt set.

Execute the closure in f, and clear up the object after it’s done before returning the result This is a convenience function that ensures object is always closed, even if an error occurs

Determine a TPM property

Details

Returns the value of the provided TpmProperty if the TPM has a value for it else None will be returned. If None is returned then use default from specification.

Errors

If the TPM returns a value that is wrong when its capabilities is being retrieved then a WrongValueFromTpm is returned.

Example
let rev = context
    .get_tpm_property(PropertyTag::Revision)
    .expect("Wrong value from TPM")
    .expect("Value is not supported");

Trait Implementations

Formats the value using the given formatter. Read more

Executes the destructor for this type. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Drops the content pointed by this pointer and frees it. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.