Struct tss_esapi::Context

source ·
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§

source§

impl Context

source

pub fn rsa_encrypt( &mut self, key_handle: KeyHandle, message: PublicKeyRsa, in_scheme: RsaDecryptionScheme, label: Data ) -> Result<PublicKeyRsa>

Perform an asymmetric RSA encryption.

source

pub fn rsa_decrypt( &mut self, key_handle: KeyHandle, cipher_text: PublicKeyRsa, in_scheme: RsaDecryptionScheme, label: Data ) -> Result<PublicKeyRsa>

Perform an asymmetric RSA decryption.

source

pub fn ecdh_key_gen( &mut self, key_handle: KeyHandle ) -> Result<(EccPoint, EccPoint)>

Generate an ephemeral key pair.

§Arguments
  • key_handle- A KeyHandle of ECC key which curve parameters will be used to generate the ephemeral key.
§Details

This command uses the TPM to generate an ephemeral key pair. It uses the private ephemeral key and a loaded public key to compute the shared secret value.

§Example
// Create a key suitable for ECDH key generation
let ecc_parms = PublicEccParametersBuilder::new()
    .with_ecc_scheme(
        EccScheme::EcDh(HashScheme::new(HashingAlgorithm::Sha256)),
    )
    .with_curve(EccCurve::NistP256)
    .with_is_signing_key(false)
    .with_is_decryption_key(true)
    .with_restricted(false)
    .with_key_derivation_function_scheme(KeyDerivationFunctionScheme::Null)
    .build()
    .unwrap();

let object_attributes = ObjectAttributesBuilder::new()
    .with_fixed_tpm(true)
    .with_fixed_parent(true)
    .with_sensitive_data_origin(true)
    .with_user_with_auth(true)
    .with_decrypt(true)
    .with_sign_encrypt(false)
    .with_restricted(false)
    .build()
    .unwrap();

let public = PublicBuilder::new()
    .with_public_algorithm(PublicAlgorithm::Ecc)
    .with_name_hashing_algorithm(HashingAlgorithm::Sha256)
    .with_object_attributes(object_attributes)
    .with_ecc_parameters(ecc_parms)
    .with_ecc_unique_identifier(EccPoint::default())
    .build()
    .unwrap();

let key_handle = context
    .create_primary(
        Hierarchy::Owner,
        public,
        Some(key_auth),
        None,
        None,
        None,
    )
    .unwrap()
    .key_handle;

// Generate ephemeral key pair and a shared secret
let (z_point, pub_point) = context.ecdh_key_gen(key_handle).unwrap();
source

pub fn ecdh_z_gen( &mut self, key_handle: KeyHandle, in_point: EccPoint ) -> Result<EccPoint>

Recover Z value from a public point and a private key.

§Arguments
  • key_handle - A KeyHandle of ECC key which curve parameters will be used to generate the ephemeral key.
  • in_point - An EccPoint on the curve of the key referenced by key_handle
§Details

This command uses the TPM to recover the Z value from a public point and a private key. It will perform the multiplication of the provided in_point with the private key and return the coordinates of the resultant point.

§Example
// Create a key suitable for ECDH key generation
let ecc_parms = PublicEccParametersBuilder::new()
    .with_ecc_scheme(
        EccScheme::EcDh(HashScheme::new(HashingAlgorithm::Sha256)),
    )
    .with_curve(EccCurve::NistP256)
    .with_is_signing_key(false)
    .with_is_decryption_key(true)
    .with_restricted(false)
    .with_key_derivation_function_scheme(KeyDerivationFunctionScheme::Null)
    .build()
    .unwrap();

let object_attributes = ObjectAttributesBuilder::new()
    .with_fixed_tpm(true)
    .with_fixed_parent(true)
    .with_sensitive_data_origin(true)
    .with_user_with_auth(true)
    .with_decrypt(true)
    .with_sign_encrypt(false)
    .with_restricted(false)
    .build()
    .unwrap();

let public = PublicBuilder::new()
    .with_public_algorithm(PublicAlgorithm::Ecc)
    .with_name_hashing_algorithm(HashingAlgorithm::Sha256)
    .with_object_attributes(object_attributes)
    .with_ecc_parameters(ecc_parms)
    .with_ecc_unique_identifier(EccPoint::default())
    .build()
    .unwrap();

let key_handle = context
    .create_primary(
        Hierarchy::Owner,
        public,
        Some(key_auth),
        None,
        None,
        None,
    )
    .unwrap()
    .key_handle;

// Generate ephemeral key pair and a shared secret
let (z_point, pub_point) = context.ecdh_key_gen(key_handle).unwrap();
let z_point_gen = context.ecdh_z_gen(key_handle, pub_point).unwrap();
assert_eq!(z_point.x().value(), z_point_gen.x().value());
source§

impl Context

source

pub fn certify( &mut self, object_handle: ObjectHandle, signing_key_handle: KeyHandle, qualifying_data: Data, signing_scheme: SignatureScheme ) -> Result<(Attest, Signature)>

Prove that an object is loaded in the TPM

§Arguments
  • object_handle - Handle of the object to be certified
  • signing_key_handle - Handle of the key used to sign the attestation buffer
  • qualifying_data - Qualifying data
  • signing_scheme - Signing scheme to use if the scheme for signing_key_handle is Null.

The object may be any object that is loaded with Self::load() or Self::create_primary(). An object that only has its public area loaded may not be certified.

The signing_key_handle must be usable for signing.

If signing_key_handle has the Restricted attribute set to true then signing_scheme must be SignatureScheme::Null.

§Returns

The command returns a tuple consisting of:

  • attest_data - TPM-generated attestation data.
  • signature - Signature for the attestation data.
§Errors
  • if the qualifying data provided is too long, a WrongParamSize wrapper error will be returned
§Examples
use std::convert::TryInto;
use tss_esapi::{
    structures::{Data, SignatureScheme},
    interface_types::session_handles::AuthSession,
};
let qualifying_data = vec![0xff; 16];
let (attest, signature) = context
    .execute_with_sessions(
        (
            Some(AuthSession::Password),
            Some(AuthSession::Password),
            None,
        ),
        |ctx| {
            ctx.certify(
                obj_key_handle.into(),
                sign_key_handle,
                Data::try_from(qualifying_data).unwrap(),
                SignatureScheme::Null,
            )
        },
    )
    .expect("Failed to certify object handle");
source

pub fn quote( &mut self, signing_key_handle: KeyHandle, qualifying_data: Data, signing_scheme: SignatureScheme, pcr_selection_list: PcrSelectionList ) -> Result<(Attest, Signature)>

Generate a quote on the selected PCRs

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

impl Context

source

pub fn get_capability( &mut self, capability: CapabilityType, property: u32, property_count: u32 ) -> Result<(CapabilityData, bool)>

Get current capability information about the TPM.

§Warning
  • If CapabilityType::AuthPolicies is used but the version of the tpm2-tss library used does not have the ‘authPolicies’ field in the TPMU_CAPABILITIES defined then the call using this method will fail.

  • If CapabilityType::Act is used but the the version of the tpm2-tss library used does not have the ‘actData’ field in the TPMU_CAPABILITIES defined then the call using this method will fail.

§Example
use tss_esapi::constants::CapabilityType;

let (_capabilities, _more) = context
    .get_capability(CapabilityType::Algorithms, 0, 80)
    .expect("Failed to call get_capability");
source

pub fn test_parms(&mut self, public_parmeters: PublicParameters) -> Result<()>

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.
source§

impl Context

source

pub fn context_save(&mut self, handle: ObjectHandle) -> Result<TpmsContext>

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
source

pub fn context_load(&mut self, context: TpmsContext) -> Result<ObjectHandle>

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
source

pub fn flush_context(&mut self, handle: ObjectHandle) -> Result<()>

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("Received 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(
        RsaScheme::create(RsaSchemeAlgorithm::RsaSsa, Some(HashingAlgorithm::Sha256))
            .expect("Failed to create RSA scheme"),
        RsaKeyBits::Rsa2048,
        RsaExponent::default(),
    )
    .expect("Failed to create rsa public area");

// Execute context methods using the session
context.execute_with_session(Some(session), |ctx| {
    let mut random_digest = vec![0u8; 16];
    getrandom::getrandom(&mut random_digest).expect("Call to getrandom failed");
    let key_auth = Auth::try_from(random_digest).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());
})
source

pub fn evict_control( &mut self, auth: Provision, object_handle: ObjectHandle, persistent: Persistent ) -> Result<ObjectHandle>

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

§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.
  • persistent - If the object_handle is transient object then this then this will become the persistent handle of that object. If the object_handle refers to a persistent object then this shall be the persistent 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 persistent 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 persistent:

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, retrieved_persistent_handle, persistent)
        .expect("Failed to evict persistent handle")
});
source§

impl Context

source

pub fn duplicate( &mut self, object_to_duplicate: ObjectHandle, new_parent_handle: ObjectHandle, encryption_key_in: Option<Data>, symmetric_alg: SymmetricDefinitionObject ) -> Result<(Data, Private, EncryptedSecret)>

Duplicate a loaded object so that it may be used in a different hierarchy.

§Details

This command duplicates a loaded object so that it may be used in a different hierarchy. The new parent key for the duplicate may be on the same or different TPM or the Null hierarchy. Only the public area of new_parent_handle is required to be loaded.

§Arguments
  • object_to_duplicate - An ObjectHandle of the object that will be duplicated.
  • new_parent_handle - An ObjectHandle of the new parent.
  • encryption_key_in - An optional encryption key. If this parameter is None then a default value is used.
  • symmetric_alg - Symmetric algorithm to be used for the inner wrapper.

The object_to_duplicate need to be have Fixed TPM and Fixed Parent attributes set to false.

§Returns

The command returns a tuple consisting of:

  • encryption_key_out - TPM generated, symmetric encryption key for the inner wrapper if symmetric_alg is not Null.
  • duplicate - Private area that may be encrypted.
  • out_sym_seed - Seed protected by the asymmetric algorithms of new parent.
§Example
use tss_esapi::structures::SymmetricDefinitionObject;

let (encryption_key_out, duplicate, out_sym_seed) = context
    .duplicate(
        object_to_duplicate_handle,
        new_parent_handle,
        None,
        SymmetricDefinitionObject::Null,
    )
    .unwrap();
source

pub fn import( &mut self, parent_handle: ObjectHandle, encryption_key: Option<Data>, public: Public, duplicate: Private, encrypted_secret: EncryptedSecret, symmetric_alg: SymmetricDefinitionObject ) -> Result<Private>

Import attaches imported object to a new parent.

§Details

This command allows an object to be encrypted using the symmetric encryption values of a Storage Key. After encryption, the object may be loaded and used in the new hierarchy. The imported object (duplicate) may be singly encrypted, multiply encrypted, or unencrypted.

§Arguments
  • parent_handle - An ObjectHandle of the new parent for the object.
  • encryption_key - An optional symmetric encryption key used as the inner wrapper. If encryption_key is None then a default value is used.
  • public - A Public of the imported object.
  • duplicate - A symmetrically encrypted duplicated object.
  • encrypted_secret - The seed for the symmetric key and HMAC key.
  • symmetric_alg - Symmetric algorithm to be used for the inner wrapper.

The public is needed to check the integrity value for duplicate.

§Returns

The command returns the sensitive area encrypted with the symmetric key of parent_handle.

§Example
use tss_esapi::structures::SymmetricDefinitionObject;

// `encryption_key_out`, `duplicate` and `out_sym_seed` are generated
// by `duplicate` function
let private = context.import(
    new_parent_handle,
    Some(encryption_key_out),
    public,
    duplicate,
    out_sym_seed,
    SymmetricDefinitionObject::Null,
 ).unwrap();
source§

impl Context

source

pub fn policy_signed( &mut self, policy_session: PolicySession, auth_object: ObjectHandle, nonce_tpm: Nonce, cp_hash_a: Digest, policy_ref: Nonce, expiration: Option<Duration>, signature: Signature ) -> Result<(Timeout, AuthTicket)>

Cause the policy to include a signed authorization

source

pub fn policy_secret( &mut self, policy_session: PolicySession, auth_handle: AuthHandle, nonce_tpm: Nonce, cp_hash_a: Digest, policy_ref: Nonce, expiration: Option<Duration> ) -> Result<(Timeout, AuthTicket)>

Cause the policy to require a secret in authValue

source

pub fn policy_or( &mut self, policy_session: PolicySession, digest_list: DigestList ) -> Result<()>

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
  • digest_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
source

pub fn policy_pcr( &mut self, policy_session: PolicySession, pcr_policy_digest: Digest, pcr_selection_list: PcrSelectionList ) -> Result<()>

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
source

pub fn policy_locality( &mut self, policy_session: PolicySession, locality: LocalityAttributes ) -> Result<()>

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).

source

pub fn policy_command_code( &mut self, policy_session: PolicySession, code: CommandCode ) -> Result<()>

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.

source

pub fn policy_physical_presence( &mut self, policy_session: PolicySession ) -> Result<()>

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.

source

pub fn policy_cp_hash( &mut self, policy_session: PolicySession, cp_hash_a: Digest ) -> Result<()>

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.

source

pub fn policy_name_hash( &mut self, policy_session: PolicySession, name_hash: Digest ) -> Result<()>

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.

source

pub fn policy_duplication_select( &mut self, policy_session: PolicySession, object_name: Name, new_parent_name: Name, include_object: bool ) -> Result<()>

Cause conditional gating of a policy based on duplication parent’s name.

§Arguments
  • policy_session - The policy session being extended.
  • object_name - The name of the object being duplicated.
  • new_parent_name - The name of the new parent.
  • include_object - Flag indicating if object_name will be included in policy calculation.
§Details

Set include_object only when this command is used in conjunction with policy_authorize.

§Example
context
    .policy_duplication_select(policy_session, object_name, parent_name, false)
    .expect("Policy command code");
source

pub fn policy_authorize( &mut self, policy_session: PolicySession, approved_policy: Digest, policy_ref: Nonce, key_sign: &Name, check_ticket: VerifiedTicket ) -> Result<()>

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.

source

pub fn policy_auth_value(&mut self, policy_session: PolicySession) -> Result<()>

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.

source

pub fn policy_password(&mut self, policy_session: PolicySession) -> Result<()>

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.

source

pub fn policy_get_digest( &mut self, policy_session: PolicySession ) -> Result<Digest>

Function for retrieving the current policy digest for the session.

source

pub fn policy_nv_written( &mut self, policy_session: PolicySession, written_set: bool ) -> Result<()>

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.

source

pub fn policy_template( &mut self, policy_session: PolicySession, template_hash: Digest ) -> Result<()>

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.
source§

impl Context

source

pub fn create_primary( &mut self, primary_handle: Hierarchy, public: Public, auth_value: Option<Auth>, initial_data: Option<SensitiveData>, outside_info: Option<Data>, creation_pcrs: Option<PcrSelectionList> ) -> Result<CreatePrimaryKeyResult>

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
source

pub fn clear(&mut self, auth_handle: AuthHandle) -> Result<()>

Clear all TPM context associated with a specific Owner

source

pub fn clear_control( &mut self, auth_handle: AuthHandle, disable: bool ) -> Result<()>

Disable or enable the TPM2_CLEAR command

source

pub fn hierarchy_change_auth( &mut self, auth_handle: AuthHandle, new_auth: Auth ) -> Result<()>

Change authorization for a hierarchy root

source§

impl Context

source

pub fn pcr_extend( &mut self, pcr_handle: PcrHandle, digests: DigestValues ) -> Result<()>

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");
});
source

pub fn pcr_read( &mut self, pcr_selection_list: PcrSelectionList ) -> Result<(u32, PcrSelectionList, DigestList)>

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 were read. The values that were read are returned in a DigestList.

§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()
    .expect("Failed to build PcrSelectionList");

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

pub fn pcr_reset(&mut self, pcr_handle: PcrHandle) -> Result<()>

Resets the value in a PCR.

§Arguments
  • pcr_handle - A PcrHandle to the PCR slot that is to be reset.
§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");
});
source§

impl Context

source

pub fn nv_define_space( &mut self, nv_auth: Provision, auth: Option<Auth>, public_info: NvPublic ) -> Result<NvIndexHandle>

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.
source

pub fn nv_undefine_space( &mut self, nv_auth: Provision, nv_index_handle: NvIndexHandle ) -> Result<()>

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.
source

pub fn nv_read_public( &mut self, nv_index_handle: NvIndexHandle ) -> Result<(NvPublic, Name)>

Reads the public part of an nv index.

§Details

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

source

pub fn nv_write( &mut self, auth_handle: NvAuth, nv_index_handle: NvIndexHandle, data: MaxNvBuffer, offset: u16 ) -> Result<()>

Writes data to an nv index.

§Details

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

source

pub fn nv_increment( &mut self, auth_handle: NvAuth, nv_index_handle: NvIndexHandle ) -> Result<()>

Increment monotonic counter index

§Details

This method is used to increment monotonic counter in the TPM.

source

pub fn nv_read( &mut self, auth_handle: NvAuth, nv_index_handle: NvIndexHandle, size: u16, offset: u16 ) -> Result<MaxNvBuffer>

Reads data from the nv index.

§Details

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

source§

impl Context

source

pub fn create( &mut self, parent_handle: KeyHandle, public: Public, auth_value: Option<Auth>, sensitive_data: Option<SensitiveData>, outside_info: Option<Data>, creation_pcrs: Option<PcrSelectionList> ) -> Result<CreateKeyResult>

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
source

pub fn load( &mut self, parent_handle: KeyHandle, private: Private, public: Public ) -> Result<KeyHandle>

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

source

pub fn load_external( &mut self, private: Sensitive, public: Public, hierarchy: Hierarchy ) -> Result<KeyHandle>

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

source

pub fn load_external_public( &mut self, public: Public, hierarchy: Hierarchy ) -> Result<KeyHandle>

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

source

pub fn read_public( &mut self, key_handle: KeyHandle ) -> Result<(Public, Name, Name)>

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

source

pub fn activate_credential( &mut self, activate_handle: KeyHandle, key_handle: KeyHandle, credential_blob: IdObject, secret: EncryptedSecret ) -> Result<Digest>

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

source

pub fn make_credential( &mut self, key_handle: KeyHandle, credential: Digest, object_name: Name ) -> Result<(IdObject, EncryptedSecret)>

Perform actions to create a IdObject containing an activation credential.

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

source

pub fn unseal(&mut self, item_handle: ObjectHandle) -> Result<SensitiveData>

Unseal and return data from a Sealed Data Object

source

pub fn object_change_auth( &mut self, object_handle: ObjectHandle, parent_handle: ObjectHandle, new_auth: Auth ) -> Result<Private>

Change authorization for a TPM-resident object.

source§

impl Context

source

pub fn get_random(&mut self, num_bytes: usize) -> Result<Digest>

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
source

pub fn stir_random(&mut self, in_data: SensitiveData) -> Result<()>

Add additional information into the TPM RNG state

source§

impl Context

source

pub fn start_auth_session( &mut self, tpm_key: Option<KeyHandle>, bind: Option<ObjectHandle>, nonce: Option<Nonce>, session_type: SessionType, symmetric: SymmetricDefinition, auth_hash: HashingAlgorithm ) -> Result<Option<AuthSession>>

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("Received invalid handle");
source

pub fn policy_restart(&mut self, policy_session: PolicySession) -> Result<()>

Restart the TPM Policy

source§

impl Context

source

pub fn verify_signature( &mut self, key_handle: KeyHandle, digest: Digest, signature: Signature ) -> Result<VerifiedTicket>

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

source

pub fn sign( &mut self, key_handle: KeyHandle, digest: Digest, scheme: SignatureScheme, validation: HashcheckTicket ) -> Result<Signature>

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

source§

impl Context

source

pub fn startup(&mut self, startup_type: StartupType) -> Result<()>

Send a TPM2_STARTUP command to the TPM

source

pub fn shutdown(&mut self, shutdown_type: StartupType) -> Result<()>

Send a TPM2_SHUTDOWN command to the TPM

source§

impl Context

source

pub fn encrypt_decrypt_2( &mut self, key_handle: KeyHandle, decrypt: bool, mode: SymmetricMode, in_data: MaxBuffer, initial_value_in: InitialValue ) -> Result<(MaxBuffer, InitialValue)>

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.clone(),                // The data that is to be encrypted.
            initial_value.clone(),       // Initial value needed by the algorithm.
        )
        .expect("Call to encrypt_decrypt_2 failed when encrypting data")
    });

assert_ne!(data.clone(), encrypted_data);
source

pub fn hash( &mut self, data: MaxBuffer, hashing_algorithm: HashingAlgorithm, hierarchy: Hierarchy ) -> Result<(Digest, HashcheckTicket)>

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);
source

pub fn hmac( &mut self, handle: ObjectHandle, buffer: MaxBuffer, alg_hash: HashingAlgorithm ) -> Result<Digest>

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 = PublicBuilder::new()
    .with_public_algorithm(PublicAlgorithm::KeyedHash)
    .with_name_hashing_algorithm(HashingAlgorithm::Sha256)
    .with_object_attributes(object_attributes)
    .with_keyed_hash_parameters(PublicKeyedHashParameters::new(KeyedHashScheme::HMAC_SHA_256))
    .with_keyed_hash_unique_identifier(Digest::default())
    .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.
source§

impl Context

source

pub fn self_test(&mut self, full_test: bool) -> Result<()>

Execute the TPM self test and returns the result

source

pub fn get_test_result(&mut self) -> Result<(MaxBuffer, Result<()>)>

Get the TPM self test result

The returned buffer data is manufacturer-specific information.

source§

impl Context

source

pub fn tr_sess_set_attributes( &mut self, session: AuthSession, attributes: SessionAttributes, mask: SessionAttributesMask ) -> Result<()>

Set the given attributes on a given session.

source

pub fn tr_sess_get_attributes( &mut self, session: AuthSession ) -> Result<SessionAttributes>

Get session attribute flags.

source§

impl Context

source

pub fn tr_set_auth( &mut self, object_handle: ObjectHandle, auth: Auth ) -> Result<()>

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

source

pub fn tr_get_name(&mut self, object_handle: ObjectHandle) -> Result<Name>

Retrieve the name of an object from the object handle

source

pub fn tr_from_tpm_public( &mut self, tpm_handle: TpmHandle ) -> Result<ObjectHandle>

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

source

pub fn tr_close(&mut self, object_handle: &mut ObjectHandle) -> Result<()>

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.

source§

impl Context

source

pub fn new(tcti_name_conf: TctiNameConf) -> Result<Self>

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
source

pub fn new_with_tabrmd(tabrmd_conf: TabrmdConfig) -> Result<Self>

Create a new ESYS context based on the TAB Resource 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
source

pub fn set_sessions( &mut self, session_handles: (Option<AuthSession>, Option<AuthSession>, Option<AuthSession>) )

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));
source

pub fn clear_sessions(&mut self)

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();
source

pub fn sessions( &self ) -> (Option<AuthSession>, Option<AuthSession>, Option<AuthSession>)

Returns the sessions that are currently set.

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

// Retrieve 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);
source

pub fn execute_with_sessions<F, T>( &mut self, session_handles: (Option<AuthSession>, Option<AuthSession>, Option<AuthSession>), f: F ) -> T
where F: FnOnce(&mut Context) -> T,

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

source

pub fn execute_with_session<F, T>( &mut self, session_handle: Option<AuthSession>, f: F ) -> T
where F: FnOnce(&mut Context) -> T,

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

source

pub fn execute_without_session<F, T>(&mut self, f: F) -> T
where F: FnOnce(&mut Context) -> T,

Executes the closure without any sessions,

source

pub fn execute_with_nullauth_session<F, T, E>(&mut self, f: F) -> Result<T, E>
where F: FnOnce(&mut Context) -> Result<T, E>, E: From<Error>,

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.

source

pub fn execute_with_temporary_object<F, T>( &mut self, object: ObjectHandle, f: F ) -> Result<T>
where F: FnOnce(&mut Context, ObjectHandle) -> Result<T>,

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

source

pub fn get_tpm_property(&mut self, property: PropertyTag) -> Result<Option<u32>>

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§

source§

impl AsMut<Context> for TransientKeyContext

source§

fn as_mut(&mut self) -> &mut Context

Converts this type into a mutable reference of the (usually inferred) input type.
source§

impl AsRef<Context> for TransientKeyContext

source§

fn as_ref(&self) -> &Context

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl Debug for Context

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Drop for Context

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> Free for T

source§

unsafe fn free(ptr_ref: NonNull<T>)

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

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

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

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.