Struct tss_esapi::Context [−][src]
pub struct Context { /* fields omitted */ }
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
pub fn rsa_encrypt(
&mut self,
key_handle: KeyHandle,
message: PublicKeyRsa,
in_scheme: RsaDecryptionScheme,
label: Data
) -> Result<PublicKeyRsa>
pub fn rsa_encrypt(
&mut self,
key_handle: KeyHandle,
message: PublicKeyRsa,
in_scheme: RsaDecryptionScheme,
label: Data
) -> Result<PublicKeyRsa>
Perform an asymmetric RSA encryption.
pub fn rsa_decrypt(
&mut self,
key_handle: KeyHandle,
cipher_text: PublicKeyRsa,
in_scheme: RsaDecryptionScheme,
label: Data
) -> Result<PublicKeyRsa>
pub fn rsa_decrypt(
&mut self,
key_handle: KeyHandle,
cipher_text: PublicKeyRsa,
in_scheme: RsaDecryptionScheme,
label: Data
) -> Result<PublicKeyRsa>
Perform an asymmetric RSA decryption.
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();
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 bykey_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());
pub fn quote(
&mut self,
signing_key_handle: KeyHandle,
qualifying_data: &Data,
signing_scheme: TPMT_SIG_SCHEME,
pcr_selection_list: PcrSelectionList
) -> Result<(TPM2B_ATTEST, Signature)>
pub fn quote(
&mut self,
signing_key_handle: KeyHandle,
qualifying_data: &Data,
signing_scheme: TPMT_SIG_SCHEME,
pcr_selection_list: PcrSelectionList
) -> Result<(TPM2B_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
pub fn get_capability(
&mut self,
capability: CapabilityType,
property: u32,
property_count: u32
) -> Result<(CapabilityData, bool)>
pub fn get_capability(
&mut self,
capability: CapabilityType,
property: u32,
property_count: u32
) -> Result<(CapabilityData, bool)>
Get current capability information about the TPM.
Test if the given parameters are supported by the TPM.
Errors
- if any of the public parameters is not compatible with the TPM,
an
Err
containing the specific unmarshalling error will be returned.
Save the context of an object from the TPM and return it.
Errors
- if conversion from
TPMS_CONTEXT
toTpmsContext
fails, aWrongParamSize
error will be returned
Load a previously saved context into the TPM and return the object handle.
Errors
- if conversion from
TpmsContext
to the nativeTPMS_CONTEXT
fails, aWrongParamSize
error will be returned
Flush the context of an object from the TPM.
Example
// Create session for a key
let session = context
.start_auth_session(
None,
None,
None,
SessionType::Hmac,
SymmetricDefinition::AES_256_CFB,
HashingAlgorithm::Sha256,
)
.expect("Failed to create session")
.expect("Recived invalid handle");
let (session_attributes, session_attributes_mask) = SessionAttributesBuilder::new()
.with_decrypt(true)
.with_encrypt(true)
.build();
context.tr_sess_set_attributes(session, session_attributes, session_attributes_mask)
.expect("Failed to set attributes on session");
// Create public area for a rsa key
let public_area = create_unrestricted_signing_rsa_public(
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 random_digest = ctx.get_random(16)
.expect("Call to get_random failed");
let key_auth = Auth::try_from(random_digest.value().to_vec())
.expect("Failed to create Auth");
let key_handle = ctx
.create_primary(
Hierarchy::Owner,
&public_area,
Some(&key_auth),
None,
None,
None,
)
.expect("Failed to create primary key")
.key_handle;
// Flush the context of the key.
ctx.flush_context(key_handle.into()).expect("Call to flush_context failed");
assert!(ctx.read_public(key_handle).is_err());
})
pub fn evict_control(
&mut self,
auth: Provision,
object_handle: ObjectHandle,
persistent: Persistent
) -> Result<ObjectHandle>
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 peristent.
Details
In order to be able to perform this action an authorization session is required.
Arguments
auth
- An a handle used for authorization that is limited to the ones specified in Provision.object_handle
- The handle of a loaded object.persistant
- If theobject_handle
is transient object then this then this will become the persistant handle of that object. If theobject_handle
refers to a persistant object then this shall be the persistant handle of that object.
Returns
If the input object_handle
was transient object then it will be made
persistent and the returned ObjectHandle will refer to the persistent
object.
If the input object_handle
refers to a presistent object the returned
value will be ObjectHandle::None and the input object_handle
will not
be valid after this call is made.
Example
Make transient object peristent:
use tss_esapi::{
interface_types::{
resource_handles::Provision,
dynamic_handles::Persistent,
session_handles::AuthSession,
},
};
// Create interface type Persistent by using the persistent tpm handle.
let persistent = Persistent::Persistent(persistent_tpm_handle);
// Make transient_object_handle persistent.
// An authorization session is required!
let mut persistent_object_handle = context.execute_with_session(Some(AuthSession::Password), |ctx| {
ctx
.evict_control(Provision::Owner, transient_object_handle.into(), persistent)
.expect("Failed to make the transient_object_handle handle persistent")
});
Make persistent object transient
use tss_esapi::{
interface_types::{
resource_handles::Provision,
dynamic_handles::Persistent,
session_handles::AuthSession,
},
};
// Create interface type Persistent by using the persistent tpm handle.
let persistent = Persistent::Persistent(persistent_tpm_handle);
// Evict the persitent handle from the tpm
// An authorization session is required!
let _ = context.execute_with_session(Some(AuthSession::Password), |ctx| {
ctx
.evict_control(Provision::Owner, retireved_persistant_handle, persistent)
.expect("Failed to evict persistent handle")
});
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)>
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
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)>
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
pub fn policy_or(
&mut self,
policy_session: PolicySession,
digest_list: DigestList
) -> Result<()>
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
hash_list
must be at least 2 and at most 8 elements long
Errors
- if the hash list provided is too short or too long, a
WrongParamSize
wrapper error will be returned
pub fn policy_pcr(
&mut self,
policy_session: PolicySession,
pcr_policy_digest: &Digest,
pcr_selection_list: PcrSelectionList
) -> Result<()>
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
pub fn policy_locality(
&mut self,
policy_session: PolicySession,
locality: TPMA_LOCALITY
) -> Result<()>
pub fn policy_locality(
&mut self,
policy_session: PolicySession,
locality: TPMA_LOCALITY
) -> 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).
pub fn policy_command_code(
&mut self,
policy_session: PolicySession,
code: TPM2_CC
) -> Result<()>
pub fn policy_command_code(
&mut self,
policy_session: PolicySession,
code: TPM2_CC
) -> 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.
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.
pub fn policy_cp_hash(
&mut self,
policy_session: PolicySession,
cp_hash_a: &Digest
) -> Result<()>
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.
pub fn policy_name_hash(
&mut self,
policy_session: PolicySession,
name_hash: &Digest
) -> Result<()>
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.
Cause conditional gating of a policy based on an authorized policy
The TPM will ensure that the current policy digest is correctly signed by the ticket in check_ticket and that check_ticket is signed by the key named in key_sign. If this is the case, the policyDigest of the policy session is replaced by the value of the key_sign and policy_ref values.
Cause conditional gating of a policy based on authValue.
The TPM will ensure that the current policy requires the user to know the authValue used when creating the object.
Cause conditional gating of a policy based on password.
The TPM will ensure that the current policy requires the user to know the password used when creating the object.
Function for retriving the current policy digest for the session.
pub fn policy_nv_written(
&mut self,
policy_session: PolicySession,
written_set: bool
) -> Result<()>
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.
pub fn policy_template(
&mut self,
policy_session: PolicySession,
template_hash: &Digest
) -> Result<()>
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.
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>
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
Clear all TPM context associated with a specific Owner
Disable or enable the TPM2_CLEAR command
pub fn hierarchy_change_auth(
&mut self,
auth_handle: AuthHandle,
new_auth: Auth
) -> Result<()>
pub fn hierarchy_change_auth(
&mut self,
auth_handle: AuthHandle,
new_auth: Auth
) -> Result<()>
Change authorization for a hierarchy root
Extends a PCR with the specified digests.
Arguments
pcr_handle
- A PcrHandle to the PCR slot that is to be extended.digests
- The DigestValues with which the slot shall be extended.
Details
This method is used to cause an update to the indicated PCR. The digests param contains the digests for specific algorithms that are to be used.
Example
use std::convert::TryFrom;
use tss_esapi::{
structures::{DigestValues},
interface_types::algorithm::HashingAlgorithm,
};
// Extend both sha256 and sha1
let mut vals = DigestValues::new();
vals.set(
HashingAlgorithm::Sha1,
digest_sha1,
);
vals.set(
HashingAlgorithm::Sha256,
digest_sha256,
);
// Use pcr_session for authorization when extending
// PCR 16 with the values for the banks specified in
// vals.
context.execute_with_session(Some(pcr_session), |ctx| {
ctx.pcr_extend(PcrHandle::Pcr16, vals).expect("Call to pcr_extend failed");
});
pub fn pcr_read(
&mut self,
pcr_selection_list: &PcrSelectionList
) -> Result<(u32, PcrSelectionList, PcrData)>
pub fn pcr_read(
&mut self,
pcr_selection_list: &PcrSelectionList
) -> Result<(u32, PcrSelectionList, PcrData)>
Reads the values of a PCR.
Arguments
pcr_selection_list
- A PcrSelectionList that contains pcr slots in different banks that is going to be read.
Details
The provided PcrSelectionList contains the pcr slots in the different banks that is going to be read. It is possible to select more pcr slots then what will fit in the returned result so the method returns a PcrSelectionList that indicates what values that was read. The values that was read are returned in the PcrData.
Errors
- Several different errors can occur if conversion of return data fails.
Example
use tss_esapi::{
interface_types::algorithm::HashingAlgorithm,
structures::{PcrSelectionListBuilder, PcrSlot},
};
// Create PCR selection list with slots in a bank
// that is going to be read.
let pcr_selection_list = PcrSelectionListBuilder::new()
.with_selection(HashingAlgorithm::Sha256, &[PcrSlot::Slot0, PcrSlot::Slot1])
.build();
let (update_counter, read_pcr_list, pcr_data) = context.pcr_read(&pcr_selection_list)
.expect("Call to pcr_read failed");
Resets the value in a PCR.
Arguments
pcr_handle
- A PcrHandle to the PCR slot that is to be resetted.
Details
If the attributes of the PCR indicates that it is allowed to reset them and the proper authorization is provided then this method can be used to set the the specified PCR in all banks to 0.
Example
use tss_esapi::{
handles::PcrHandle
};
context.execute_with_session(Some(pcr_session), |ctx| {
ctx.pcr_reset(PcrHandle::Pcr16).expect("Call to pcr_reset failed");
});
pub fn nv_define_space(
&mut self,
nv_auth: Provision,
auth: Option<&Auth>,
public_info: &NvPublic
) -> Result<NvIndexHandle>
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.
pub fn nv_undefine_space(
&mut self,
nv_auth: Provision,
nv_index_handle: NvIndexHandle
) -> Result<()>
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.
Reads the public part of an nv index.
Details
This method is used to read the public area and name of a nv index.
pub fn nv_write(
&mut self,
auth_handle: NvAuth,
nv_index_handle: NvIndexHandle,
data: &MaxNvBuffer,
offset: u16
) -> Result<()>
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.
pub fn nv_read(
&mut self,
auth_handle: NvAuth,
nv_index_handle: NvIndexHandle,
size: u16,
offset: u16
) -> Result<MaxNvBuffer>
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.
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>
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
Load a previously generated key back into the TPM and return its new handle.
pub fn load_external(
&mut self,
private: &TPM2B_SENSITIVE,
public: &Public,
hierarchy: Hierarchy
) -> Result<KeyHandle>
pub fn load_external(
&mut self,
private: &TPM2B_SENSITIVE,
public: &Public,
hierarchy: Hierarchy
) -> Result<KeyHandle>
Load an external key into the TPM and return its new handle.
Load the public part of an external key and return its new handle.
Read the public part of a key currently in the TPM and return it.
pub fn activate_credential(
&mut self,
activate_handle: KeyHandle,
key_handle: KeyHandle,
credential_blob: IDObject,
secret: EncryptedSecret
) -> Result<Digest>
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.
pub fn make_credential(
&mut self,
key_handle: KeyHandle,
credential: Digest,
object_name: Name
) -> Result<(IDObject, EncryptedSecret)>
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.
Unseal and return data from a Sealed Data Object
pub fn object_change_auth(
&mut self,
object_handle: ObjectHandle,
parent_handle: ObjectHandle,
new_auth: Auth
) -> Result<Private>
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.
Get a number of random bytes from the TPM and return them.
Errors
- if converting
num_bytes
tou16
fails, aWrongParamSize
will be returned
Add additional information into the TPM RNG state
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>>
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("Recived invalid handle");
Restart the TPM Policy
pub fn verify_signature(
&mut self,
key_handle: KeyHandle,
digest: &Digest,
signature: Signature
) -> Result<VerifiedTicket>
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.
pub fn sign(
&mut self,
key_handle: KeyHandle,
digest: &Digest,
scheme: TPMT_SIG_SCHEME,
validation: HashcheckTicket
) -> Result<Signature>
pub fn sign(
&mut self,
key_handle: KeyHandle,
digest: &Digest,
scheme: TPMT_SIG_SCHEME,
validation: HashcheckTicket
) -> Result<Signature>
Sign a digest with a key present in the TPM and return the signature.
Send a TPM2_STARTUP command to the TPM
Send a TPM2_SHUTDOWN command to the TPM
pub fn encrypt_decrypt_2(
&mut self,
key_handle: KeyHandle,
decrypt: bool,
mode: SymmetricMode,
in_data: &MaxBuffer,
initial_value_in: &InitialValue
) -> Result<(MaxBuffer, InitialValue)>
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, // The data that is to be encrypted.
&initial_value, // Initial value needed by the algorithmen.
)
.expect("Call to encrypt_decrypt_2 failed when encrypting data")
});
assert_ne!(data, encrypted_data);
pub fn hash(
&mut self,
data: &MaxBuffer,
hashing_algorithm: HashingAlgorithm,
hierarchy: Hierarchy
) -> Result<(Digest, HashcheckTicket)>
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);
pub fn hmac(
&mut self,
handle: ObjectHandle,
buffer: &MaxBuffer,
alg_hash: HashingAlgorithm
) -> Result<Digest>
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.
pub fn tr_sess_set_attributes(
&mut self,
session: AuthSession,
attributes: SessionAttributes,
mask: SessionAttributesMask
) -> Result<()>
pub fn tr_sess_set_attributes(
&mut self,
session: AuthSession,
attributes: SessionAttributes,
mask: SessionAttributesMask
) -> Result<()>
Set the given attributes on a given session.
Get session attribute flags.
Set the authentication value for a given object handle in the ESYS context.
Retrieve the name of an object from the object handle
Used to construct an esys object from the resources inside the TPM.
Instructs the ESAPI to release the metadata and resources allocated for a specific ObjectHandle.
This is useful for cleaning up handles for which the context cannot be flushed.
Create a new ESYS context based on the desired TCTI
Warning
The client is responsible for ensuring that the context can be initialized safely, threading-wise. Some TCTI are not safe to execute with multiple commands in parallel. If the sequence of commands to the TPM is interrupted by another application, commands might fail unexpectedly. If multiple applications are using the TPM in parallel, make sure to use the TABRMD TCTI which will offer multi-user support to a single TPM device. See the specification for more information.
Errors
- if either
Tss2_TctiLdr_Initiialize
orEsys_Initialize
fail, a corresponding Tss2ResponseCode will be returned
Create a new ESYS context based on the TAB Ressource Manager Daemon. The TABRMD will make sure that multiple users can use the TPM safely.
Errors
- if either
Tss2_TctiLdr_Initiialize
orEsys_Initialize
fail, a corresponding Tss2ResponseCode will be returned
pub fn set_sessions(
&mut self,
session_handles: (Option<AuthSession>, Option<AuthSession>, Option<AuthSession>)
)
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));
Clears any sessions that have been set
This will result in the None handle being used in all calls to ESAPI.
Example
// Use password session for auth
context.set_sessions((Some(AuthSession::Password), None, None));
// Clear auth sessions
context.clear_sessions();
Returns the sessions that are currently set.
Example
// Use password session for auth
context.set_sessions((Some(AuthSession::Password), None, None));
// Retreive sessions in use
let (session_1, session_2, session_3) = context.sessions();
assert_eq!(Some(AuthSession::Password), session_1);
assert_eq!(None, session_2);
assert_eq!(None, session_3);
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,
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
pub fn execute_with_session<F, T>(
&mut self,
session_handle: Option<AuthSession>,
f: F
) -> T where
F: FnOnce(&mut Context) -> T,
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
Executes the closure without any sessions,
Executes the closure with a newly generated empty session
Details
The session attributes for the generated empty session that is used to execute closure will have the attributes decrypt and encrypt set.
pub fn execute_with_temporary_object<F, T>(
&mut self,
object: ObjectHandle,
f: F
) -> Result<T> where
F: FnOnce(&mut Context, ObjectHandle) -> Result<T>,
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
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");