Skip to main content

Context

Struct 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: impl Into<Option<Data>>, ) -> Result<PublicKeyRsa>

Perform an asymmetric RSA encryption.

§Arguments
  • key_handle - A KeyHandle to to public portion of RSA key to use for encryption.
  • message - The message to be encrypted.
  • in_scheme - The padding scheme to use if scheme associated with the key_handle is RsaDecryptionScheme::Null.
  • label - An optional label to be associated with the message.
§Details

From the specification

This command performs RSA encryption using the indicated padding scheme according to IETF RFC 8017.

The label parameter is optional. If provided (label.size != 0) then the TPM shall return TPM_RC_VALUE if the last octet in label is not zero. The terminating octet of zero is included in the label used in the padding scheme. If the scheme does not use a label, the TPM will still verify that label is properly formatted if label is present.

§Returns

The encrypted output.

§Example
// Because the key was created with RsaScheme::Null it is possible to
// provide a scheme for the rsa_encrypt function to use.
let scheme =
       RsaDecryptionScheme::create(RsaDecryptAlgorithm::Oaep, Some(HashingAlgorithm::Sha256))
           .expect("Failed to create rsa decryption scheme");
let plain_text_bytes = vec![1, 2, 3, 4];
let message_in = PublicKeyRsa::try_from(plain_text_bytes.clone())
    .expect("Should be possible to create a PublicKeyRsa object from valid bytes.");
let cipher_text = context.rsa_encrypt(key_handle, message_in, scheme, None)
    .expect("Should be possible to call rsa_encrypt using valid arguments.");
Source

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

Perform an asymmetric RSA decryption.

§Arguments
  • key_handle - A KeyHandle of the RSA key to use for decryption.
  • cipher_text - The cipher text to be decrypted.
  • in_scheme - The padding scheme to use if scheme associated with the key_handle is RsaDecryptionScheme::Null.
  • label - An optional label whose association with the message is to be verified.
§Details

From the specification

This command performs RSA decryption using the indicated padding scheme according to IETF RFC 8017 ((PKCS#1).

If a label is used in the padding process of the scheme during encryption, the label parameter is required to be present in the decryption process and label is required to be the same in both cases. If label is not the same, the decrypt operation is very likely to fail.

§Returns

The decrypted output.

§Example
// label text needs to be the same as the on used when data was encrypted.
let message_out = context.rsa_decrypt(key_handle, cipher_text, scheme, label)
    .expect("Should be possible to call rsa_decrypt using valid arguments.");
let decrypted_bytes = message_out.as_bytes();
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().as_bytes(), z_point_gen.x().as_bytes());
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 certify_creation( &mut self, signing_key_handle: KeyHandle, created_object: ObjectHandle, qualifying_data: Data, creation_hash: Digest, signing_scheme: SignatureScheme, creation_ticket: CreationTicket, ) -> Result<(Attest, Signature)>

Prove the association between an object and its creation data

§Arguments
  • signing_key_handle - Handle of the key used to sign the attestation buffer
  • object_handle - Handle of the object to be certified
  • qualifying_data - Qualifying data
  • creation_hash - Digest of the creation data
  • signing_scheme - Signing scheme to use if the scheme for signing_key_handle is Null.
  • creation_ticket - CreationTicket returned at object creation time.

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),
            None,
            None,
        ),
        |ctx| {
            ctx.certify_creation(
              create_result.key_handle,
              create_result.key_handle.into(),
              qualifying_data.try_into()?,
              create_result.creation_hash,
              SignatureScheme::Null,
              create_result.creation_ticket,
            )
        },
    )
    .expect("Failed to certify creation");
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

§Arguments
  • signing_key_handle - Handle of key that will perform signature.
  • qualifying_data - Data supplied by the caller.
  • signing_scheme - Signing scheme to use if the scheme for signing_key_handle is the null scheme.
  • pcr_selection_list - The PCR set to quote.
§Errors
  • if the qualifying data provided is too long, a WrongParamSize wrapper error will be returned.
§Examples
use std::convert::TryFrom;
use tss_esapi::{
    interface_types::{
        algorithm::HashingAlgorithm,
        session_handles::AuthSession,
    },
    structures::{
        Data, PcrSelectionListBuilder, PcrSlot, SignatureScheme,
    },
};

let qualifying_data = Data::try_from(vec![0xff; 16])
    .expect("It should be possible to create qualifying data from bytes.");

// Quote PCR 0, 1, 2
let pcr_selection_list = PcrSelectionListBuilder::new()
    .with_selection(HashingAlgorithm::Sha256, &[PcrSlot::Slot0, PcrSlot::Slot1, PcrSlot::Slot2])
    .build()
    .expect("It should be possible to create PCR selection list with valid values.");

let (attest, signature) = context
    .execute_with_sessions(
        (
            Some(AuthSession::Password),
            None,
            None,
        ),
        |ctx| {
            ctx.quote(
                sign_key_handle,
                qualifying_data,
                SignatureScheme::Null,
                pcr_selection_list.clone(),
            )
        },
    )
    .expect("Failed to get quote");
Source

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

Get the current time and clock from the TPM

§Arguments
  • 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 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.get_time(
                sign_key_handle,
                Data::try_from(qualifying_data).unwrap(),
                SignatureScheme::Null,
            )
        },
    )
    .expect("Failed to get tpm time");
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<SavedTpmContext>

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: SavedTpmContext) -> 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::from_bytes(random_digest.as_slice()).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::{
        reserved_handles::Provision,
        data_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::{
        reserved_handles::Provision,
        data_handles::Persistent,
        session_handles::AuthSession,
    },
};
// Create interface type Persistent by using the persistent tpm handle.
let persistent = Persistent::Persistent(persistent_tpm_handle);
// Evict the persistent 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

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

Cause conditional gating of a policy based on an authorized policy stored in non-volatile memory.

§Arguments
  • policy_session - The policy session being extended.
  • auth_handle - Handle indicating the source of authorization value.
  • nv_index_handle - The NvIndexHandle associated with NV memory where the policy is stored.
§Example
let nv_index_handle = context
   .nv_define_space(Provision::Owner, None, owner_nv_public)
   .expect("Call to nv_define_space failed");

context.policy_authorize_nv(
    policy_session,
    NvAuth::Owner,
    nv_index_handle,
).expect("failed to extend policy with policy_authorize_nv");;
Source§

impl Context

Source

pub fn hmac_sequence_start( &mut self, handle: ObjectHandle, hashing_algorithm: HashingAlgorithm, auth: Option<Auth>, ) -> Result<ObjectHandle>

Starts HMAC sequence of large data (larger than MaxBuffer::MAX_SIZE) using the specified algorithm.

§Details

When the amount of data to be included in a digest cannot be sent to the TPM in one atomic HMAC command then a sequence of commands may be used to provide incremental updates to the digest.

Follow the pattern:

§Example
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(Default::default())
    .build()
    .expect("Failed to build public structure for key.");

let key = context
    .create_primary(Hierarchy::Owner, key_pub, None, None, None, None)
    .unwrap();

let data = [0xEE; 5000];

let handle = context
    .hmac_sequence_start(key.key_handle.into(), HashingAlgorithm::Sha256, None)
    .unwrap();

let chunks = data.chunks_exact(MaxBuffer::MAX_SIZE);
let last_chunk = chunks.remainder();
for chunk in chunks {
    context
        .sequence_update(handle, MaxBuffer::from_bytes(chunk).unwrap())
        .unwrap();
}
let (actual_hashed_data, ticket) = context
    .sequence_complete(
        handle,
        MaxBuffer::from_bytes(last_chunk).unwrap(),
        Hierarchy::Null,
    )
   .unwrap();
Source

pub fn hash_sequence_start( &mut self, hashing_algorithm: HashingAlgorithm, auth: Option<Auth>, ) -> Result<ObjectHandle>

Starts hash sequence of large data (larger than MaxBuffer::MAX_SIZE) using the specified algorithm.

§Details

When the amount of data to be included in a digest cannot be sent to the TPM in one atomic hash command then a sequence of commands may be used to provide incremental updates to the digest.

Follow the pattern:

§Example

let data = [0xEE; 2*1025];

let handle = context
    .hash_sequence_start(HashingAlgorithm::Sha256, None)
    .unwrap();

let chunks = data.chunks_exact(MaxBuffer::MAX_SIZE);
let last_chunk = chunks.remainder();
for chunk in chunks {
    context
        .sequence_update(handle, MaxBuffer::from_bytes(chunk).unwrap())
        .unwrap();
}
let (actual_hashed_data, ticket) = context
     .sequence_complete(
        handle,
        MaxBuffer::from_bytes(last_chunk).unwrap(),
        Hierarchy::Owner,
    )
    .unwrap();
Source

pub fn sequence_update( &mut self, sequence_handle: ObjectHandle, data: MaxBuffer, ) -> Result<()>

Continues hash or HMAC sequence.

See Context::hash_sequence_start, Context::hmac_sequence_start.

Source

pub fn sequence_complete( &mut self, sequence_handle: ObjectHandle, data: MaxBuffer, hierarchy: Hierarchy, ) -> Result<(Digest, Option<HashcheckTicket>)>

Finishes hash or HMAC sequence.

/// See Context::hash_sequence_start, Context::hmac_sequence_start.

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.

Please beware that this method requires an authorization session handle to be present.

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

A NvIndexHandle associated with the NV memory that was defined.

§Example
use tss_esapi::{
     handles::NvIndexTpmHandle, attributes::NvIndexAttributes, structures::NvPublic,
     interface_types::{algorithm::HashingAlgorithm, reserved_handles::Provision},
};
let nv_index = NvIndexTpmHandle::new(0x01500022)
    .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 owner_nv_index_handle = context
    .nv_define_space(Provision::Owner, None, owner_nv_public)
    .expect("Call to nv_define_space failed");
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.

Please beware that this method requires an authorization session handle to be present.

§Arguments
  • nv_auth - The Provision used for authorization.
  • nv_index_handle- The NvIndexHandle associated with the nv area that is to be removed.
§Example
use tss_esapi::interface_types::reserved_handles::Provision;
// Define the NV space.
let owner_nv_index_handle = context
    .nv_define_space(Provision::Owner, None, owner_nv_public)
    .expect("Call to nv_define_space failed");

context
   .nv_undefine_space(Provision::Owner, owner_nv_index_handle)
   .expect("Call to nv_undefine_space failed");
Source

pub fn nv_undefine_space_special( &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 that was defined with TPMA_NV_POLICY_DELETE.

Please beware that this method requires both a policy and authorization session handle to be present.

§Arguments
  • nv_auth - The Provision used for authorization.
  • nv_index_handle- The NvIndexHandle associated with the nv area that is to be removed.
§Example
use tss_esapi::interface_types::reserved_handles::Provision;
use tss_esapi::interface_types::session_handles::AuthSession;
// Define the NV space.
let index_handle = context.execute_with_session(Some(AuthSession::Password), |context| {
        context
            .nv_define_space(Provision::Platform, None, nv_public)
            .expect("Call to nv_define_space failed")
    });

// Undefine the NV space with a policy session and default auth session
context.execute_with_sessions((
        Some(session),
        Some(AuthSession::Password),
        None,
    ), |context| {
        context
            .nv_undefine_space_special(Provision::Platform, index_handle)
            .expect("Call to nv_undefine_space_special failed");
        }
    );
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.

§Arguments
  • nv_index_handle - The NvIndexHandle associated with NV memory for which the public part is to be read.
§Returns

A tuple containing the public area and the name of an nv index.

§Example
use tss_esapi::{
      interface_types::reserved_handles::Provision,
};

// 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");

let nv_index_handle = context
   .nv_define_space(Provision::Owner, None, owner_nv_public.clone())
   .expect("Call to nv_define_space failed");

// Holds the result in order to ensure that the
// NV space gets undefined.
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
let (read_nv_public, _name) = nv_read_public_result
    .expect("Call to nv_read_public failed");

assert_eq!(owner_nv_public, read_nv_public);
Source

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

Writes data to the NV memory associated with a nv index.

§Details

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

Please beware that this method requires an authorization session handle to be present.

§Arguments
  • auth_handle - Handle indicating the source of authorization value.
  • nv_index_handle - The NvIndexHandle associated with NV memory where data is to be written.
  • data - The data, in the form of a MaxNvBuffer, that is to be written.
  • offset - The octet offset into the NV area.
§Example
use tss_esapi::{
      interface_types::reserved_handles::{Provision, NvAuth}, structures::MaxNvBuffer,
};
use std::convert::TryFrom;


let data = MaxNvBuffer::try_from(vec![1, 2, 3, 4, 5, 6, 7])
   .expect("Failed to create MaxNvBuffer from vec");

let nv_index_handle = context
   .nv_define_space(Provision::Owner, None, owner_nv_public.clone())
   .expect("Call to nv_define_space failed");

// Use owner authorization
let nv_write_result = context.nv_write(NvAuth::Owner, nv_index_handle, data, 0);

context
    .nv_undefine_space(Provision::Owner, nv_index_handle)
    .expect("Call to nv_undefine_space failed");

// Process result
nv_write_result.expect("Call to nv_write failed");
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.

Please beware that this method requires an authorization session handle to be present.

§Arguments
  • auth_handle - Handle indicating the source of authorization value.
  • nv_index_handle - The NvIndexHandle associated with NV memory where data is to be written.
use tss_esapi::{
      interface_types::reserved_handles::{Provision, NvAuth}
};

let nv_index_handle = context
    .nv_define_space(Provision::Owner, None, owner_nv_public.clone())
    .expect("Call to nv_define_space failed");

let nv_increment_result = context.nv_increment(NvAuth::Owner, nv_index_handle);

context
    .nv_undefine_space(Provision::Owner, nv_index_handle)
    .expect("Call to nv_undefine_space failed");

// Process result
nv_increment_result.expect("Call to nv_increment failed");
Source

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

Extends data to the NV memory associated with a nv index.

§Details

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

Please beware that this method requires an authorization session handle to be present.

Any NV index (that is not already used) can be defined as an extend type. However various specifications define indexes that have specific purposes or are reserved, for example the TCG PC Client Platform Firmware Profile Specification Section 3.3.6 defines indexes within the 0x01c40200-0x01c402ff range for instance measurements. Section 2.2 of TCG Registry of Reserved TPM 2.0 Handles and Localities provides additional context for specific NV index ranges.

§Arguments
  • auth_handle - Handle indicating the source of authorization value.
  • nv_index_handle - The NvIndexHandle associated with NV memory which will be extended by data hashed with the previous data.
  • data - The data, in the form of a MaxNvBuffer, that is to be written.
§Example
use tss_esapi::{
      interface_types::reserved_handles::{Provision, NvAuth}, structures::MaxNvBuffer,
};

// Create NV index attributes
let owner_nv_index_attributes = NvIndexAttributes::builder()
    .with_owner_write(true)
    .with_owner_read(true)
    .with_orderly(true)
    .with_nv_index_type(NvIndexType::Extend)
    .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");

let nv_index_handle = context
    .nv_define_space(Provision::Owner, None, owner_nv_public.clone())
    .expect("Call to nv_define_space failed");

let data = MaxNvBuffer::try_from(vec![0x0]).unwrap();
let result = context.nv_extend(NvAuth::Owner, nv_index_handle, data);
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.

Please beware that this method requires an authorization session handle to be present.

§Arguments
  • auth_handle - Handle indicating the source of authorization value.
  • nv_index_handle - The NvIndexHandle associated with NV memory where data is to be written.
  • size - The number of octets to read.
  • offset- Octet offset into the NV area.
§Example
use tss_esapi::{
      interface_types::reserved_handles::{Provision, NvAuth}, structures::MaxNvBuffer,
};
use std::convert::TryFrom;

let data = MaxNvBuffer::try_from(vec![1, 2, 3, 4, 5, 6, 7])
   .expect("Failed to create MaxNvBuffer from vec");

let nv_index_handle = context
   .nv_define_space(Provision::Owner, None, owner_nv_public)
   .expect("Call to nv_define_space failed");

// Write data using owner authorization
let nv_write_result = context.nv_write(NvAuth::Owner, nv_index_handle, data.clone(), 0);

// Read data using owner authorization
let data_len = u16::try_from(data.len()).expect("Failed to retrieve length of data");
let nv_read_result = context
    .nv_read(NvAuth::Owner, nv_index_handle, data_len, 0);

context
    .nv_undefine_space(Provision::Owner, nv_index_handle)
    .expect("Call to nv_undefine_space failed");

// Process result
nv_write_result.expect("Call to nv_write failed");
let read_data = nv_read_result.expect("Call to nv_read failed");
assert_eq!(data, read_data);
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: impl Into<Option<Sensitive>>, public: Public, hierarchy: Hierarchy, ) -> Result<KeyHandle>

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

§Details

This command is used to load an object that is not a Protected Object into the TPM. The command allows loading of a public area or both a public and sensitive area.

§Arguments
  • private - The optional sensitive portion of the object.
  • public - The public portion of the object.
  • hierarchy - The hierarchy with which the object area is associated.
§Returns

The handle to the loaded key.

§Example
let object_attributes = ObjectAttributesBuilder::new()
    .with_user_with_auth(true)
    .with_decrypt(false)
    .with_sign_encrypt(true)
    .with_restricted(false)
    .build()
    .expect("Failed to build object attributes");

let public = PublicBuilder::new()
    .with_public_algorithm(PublicAlgorithm::Rsa)
    .with_name_hashing_algorithm(HashingAlgorithm::Sha256)
    .with_object_attributes(object_attributes)
    .with_rsa_parameters(
        PublicRsaParametersBuilder::new_unrestricted_signing_key(
            RsaScheme::create(RsaSchemeAlgorithm::RsaSsa, Some(HashingAlgorithm::Sha256))
                .expect("Failed to create rsa scheme"),
            RsaKeyBits::Rsa2048,
            Default::default(),
        )
        .build()
        .expect("Failed to create rsa parameters for public structure"),
    )
    .with_rsa_unique_identifier(
        PublicKeyRsa::from_bytes(&KEY[..256])
            .expect("Failed to create Public RSA key from buffer"),
    )
    .build()
    .expect("Failed to build Public structure");

// Load public key into Owner hierarchy.
let key_handle = context.load_external(None, public, Hierarchy::Owner)
    .expect("The load_external should have returned a valid key 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: impl Into<Option<HashcheckTicket>>, ) -> Result<Signature>

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

§Details

For signatures using a restricted key, a hashcheck must be provided. For unrestricted keys, this may be None.

§Parameters

key_handle - Handle to the key be used for signing. digest - The digest that is going to be signed. scheme - The scheme to use if the scheme for the key referenced by the key handle is null. validation - An optional HashcheckTicket that proof that the digest was created by the TPM. N.B. None will be treated as a “Null ticket”.

§Example
use tss_esapi::structures::SignatureScheme;
let signature = context.execute_with_nullauth_session(|ctx| {
    ctx.sign(
        unrestricted_signing_key_handle,
        digest,
        SignatureScheme::Null,
        None,
    )
})
.expect("Failed to sign digest");
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

§Details

The first parameter returned is a buffer with manufacturer-specific information.

The second parameter returned by the method is an indicator of how the test went in the form a Result.

If testing of all functions is complete without functional failures then Ok(()) or else a TssError (see Error) is returned.

See Part 3, Commands.

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

pub fn tr_sess_get_nonce_tpm(&mut self, session: AuthSession) -> Result<Nonce>

Get the TPM nonce from a session.

§Arguments
  • session - An AuthSession handle to the authentication session from which to retrieve the TPM nonce.
§Returns

The TPM nonce as a Nonce struct on success.

§Details

This function retrieves the nonceTPM value from an authentication session.

Extracted nonceTPM can be useful in some scenarios. For example, a TPM object protected by a PolicySigned policy requires the nonceTPM value to be extracted and included in the signed digest to satisfy the policy.

§Example

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::Policy,
        SymmetricDefinition::AES_256_CFB,
        HashingAlgorithm::Sha256,
    )
    .expect("Failed to create session")
    .expect("Received invalid handle");
let nonce_tpm = context.tr_sess_get_nonce_tpm(session).expect("Failed to get nonceTPM");
// Use the nonce_tpm value as needed
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.

§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.
use tss_esapi::{handles::ObjectHandle, structures::Auth};

// Sets auth for Owner to empty string.
context
    .tr_set_auth(ObjectHandle::Owner, Auth::default())
    .expect("Failed to call tr_set_auth");
Source

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

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

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

§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
use tss_esapi::{
    handles::NvIndexTpmHandle,
};
let nv_index = NvIndexTpmHandle::new(0x01500402)
    .expect("Failed to create NV index tpm handle");
// 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.");
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.

§Arguments
  • object_handle`- An ObjectHandle referring to an object for which all metadata and resources is going to be released.
§Example
let nv_index = NvIndexTpmHandle::new(0x01500403)
    .expect("Failed to create NV index tpm handle");
let tr_close_result = context
    .tr_close(&mut handle_to_be_closed);
// Process results.
tr_close_result.expect("Call to tr_close failed.");
Source

pub fn tr_serialize(&mut self, handle: ObjectHandle) -> Result<Vec<u8>>

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.
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();
Source

pub fn tr_deserialize(&mut self, buffer: &[u8]) -> Result<ObjectHandle>

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.
§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.
let key_handle = context
    .create_primary(
        Hierarchy::Owner,
        public,
        None,
        None,
        None,
        None,
    ).unwrap()
    .key_handle;
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());
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> 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> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

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>,

Source§

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.