### Install tpm2-pytss from PyPi Source: https://tpm2-pytss.readthedocs.io/en/latest/_sources/install Installs the tpm2-pytss Python package using pip. This command fetches and installs the package from the Python Package Index. Depending on the environment, '--user' or 'sudo' might be required for installation. ```console $ python3 -m pip install tpm2-pytss ``` -------------------------------- ### Install tpm2-pytss from Git Repository Source: https://tpm2-pytss.readthedocs.io/en/latest/install Clones the tpm2-pytss repository from GitHub and installs it in editable mode using pip. ```bash $ git clone --depth 1 https://github.com/tpm2-software/tpm2-pytss $ cd tpm2-pytss $ python3 -m pip install -e . ``` -------------------------------- ### Install tpm2-pytss from Git Repository Source: https://tpm2-pytss.readthedocs.io/en/latest/_sources/install Installs the tpm2-pytss Python package directly from its Git repository. This involves cloning the repository, navigating into the directory, and then performing an editable installation using pip. ```console $ git clone --depth 1 https://github.com/tpm2-software/tpm2-pytss $ cd tpm2-pytss $ python3 -m pip install -e . ``` -------------------------------- ### Install Dependencies on Ubuntu Source: https://tpm2-pytss.readthedocs.io/en/latest/install Installs the necessary development files for the tpm2-tss native library on Ubuntu 20.04 using apt-get. ```bash apt-get update apt-get install libtss2-dev ``` -------------------------------- ### Install tpm2-pytss from PyPI Source: https://tpm2-pytss.readthedocs.io/en/latest/install Installs the tpm2-pytss Python package from the Python Package Index (PyPI) using pip. ```bash $ python3 -m pip install tpm2-pytss ``` -------------------------------- ### Install Dependencies on Fedora Source: https://tpm2-pytss.readthedocs.io/en/latest/install Installs the necessary development files for the tpm2-tss native library on Fedora 32 using dnf. ```bash dnf update dnf install tpm2-tss-devel ``` -------------------------------- ### Install Dev Dependencies and Run Tests for tpm2-pytss Source: https://tpm2-pytss.readthedocs.io/en/latest/testing This snippet shows how to install the development dependencies for tpm2-pytss using pip and then execute the tests using pytest with parallel execution based on the number of available processors. ```bash pip install -e .[dev] pytest -n$(nproc) -v test ``` -------------------------------- ### Install tpm2-pytss Dependencies on Fedora Source: https://tpm2-pytss.readthedocs.io/en/latest/_sources/install Installs the necessary development files for the tpm2-tss native library suite on Fedora 32 using dnf. This command updates the package list and installs the 'tpm2-tss-devel' package, a prerequisite for tpm2-pytss. ```bash dnf update dnf install tpm2-tss-devel ``` -------------------------------- ### Invoke TPM2_StartAuthSession Source: https://tpm2-pytss.readthedocs.io/en/latest/esys Starts an authentication session with the TPM. This function configures the session type, symmetric encryption, and hash algorithm, along with optional parameters like caller nonce and sessions. It returns a handle to the started session. ```Python start_auth_session(tpm_key, bind, session_type, symmetric, auth_hash, nonce_caller=None, session1=4095, session2=4095, session3=4095) ``` -------------------------------- ### Install tpm2-pytss Dependencies on Ubuntu Source: https://tpm2-pytss.readthedocs.io/en/latest/_sources/install Installs the required development files for the tpm2-tss native library suite on Ubuntu 20.04 using apt-get. This command updates the package list and then installs the 'libtss2-dev' package, which is necessary for tpm2-pytss to function correctly. ```bash apt-get update apt-get install libtss2-dev ``` -------------------------------- ### Configure ldconfig for Local Libraries Source: https://tpm2-pytss.readthedocs.io/en/latest/install Configures ldconfig to recognize shared libraries installed in /usr/local/lib, preventing 'cannot open shared object file' errors. ```bash $ sudo mkdir -p /etc/ld.so.conf.d/ $ echo 'include /etc/ld.so.conf.d/*.conf' | sudo tee -a /etc/ld.so.conf $ echo '/usr/local/lib' | sudo tee -a /etc/ld.so.conf.d/libc.conf $ sudo ldconfig ``` -------------------------------- ### Configure ldconfig for Shared Libraries Source: https://tpm2-pytss.readthedocs.io/en/latest/_sources/install Configures the system's dynamic linker run-time bindings to include the /usr/local/lib directory, ensuring that newly installed shared libraries are discoverable. This is crucial for resolving 'ImportError: libtss2-esys.so.0: cannot open shared object file' errors. ```console sudo mkdir -p /etc/ld.so.conf.d/ echo 'include /etc/ld.so.conf.d/*.conf' | sudo tee -a /etc/ld.so.conf echo '/usr/local/lib' | sudo tee -a /etc/ld.so.conf.d/libc.conf sudo ldconfig ``` -------------------------------- ### TPM2B_PUBLIC Methods for PEM, Name, and Marshaling Source: https://tpm2-pytss.readthedocs.io/en/latest/api Details various methods for TPM2B_PUBLIC, including conversion to/from PEM format, getting the name, and marshaling/unmarshaling. ```Python TPM2B_PUBLIC.__str__() TPM2B_PUBLIC.from_pem() TPM2B_PUBLIC.get_name() TPM2B_PUBLIC.marshal() TPM2B_PUBLIC.parse() TPM2B_PUBLIC.to_der() TPM2B_PUBLIC.to_pem() TPM2B_PUBLIC.to_ssh() TPM2B_PUBLIC.unmarshal() ``` -------------------------------- ### TPMA_STARTUP Methods Source: https://tpm2-pytss.readthedocs.io/en/latest/constants Explains the methods for TPMA_STARTUP structures, including marshaling, parsing, and string conversion for TPM startup values. ```python TPMA_STARTUP.CLEAR_EHENABLE TPMA_STARTUP.CLEAR_ORDERLY TPMA_STARTUP.CLEAR_PHENABLE TPMA_STARTUP.CLEAR_PHENABLENV TPMA_STARTUP.CLEAR_RESERVED1_MASK TPMA_STARTUP.CLEAR_SHENABLE TPMA_STARTUP.__str__() TPMA_STARTUP.marshal() TPMA_STARTUP.parse() TPMA_STARTUP.to_string() TPMA_STARTUP.unmarshal() ``` -------------------------------- ### General Constant String Conversion (Example Usage) Source: https://tpm2-pytss.readthedocs.io/en/latest/constants Illustrates the `__str__` method for constants, showing how to get a lowercase string representation of a constant. ```python str(ESYS_TR.PCR2) -> ‘pcr2’ ``` -------------------------------- ### Get String Value of TPM2 Constant Source: https://tpm2-pytss.readthedocs.io/en/latest/constants Returns a string value of the constant normalized to lowercase. Example: str(ESYS_TR.PCR2) -> ‘pcr2’ ```python __str__() ``` -------------------------------- ### Using setuptools-scm for Versioning Source: https://tpm2-pytss.readthedocs.io/en/latest/_sources/release The project utilizes setuptools-scm to automatically manage version strings. This requires either a source-built package from PyPI or direct use of the git repository. GitHub-generated zip and tarballs are not compatible. ```python use_scm_version ``` -------------------------------- ### TPMA_STARTUP Methods Source: https://tpm2-pytss.readthedocs.io/en/latest/api Outlines the methods for TPMA_STARTUP attributes, covering serialization and string conversion. Essential methods are marshal(), parse(), to_string(), and unmarshal(). ```python TPMA_STARTUP.marshal() TPMA_STARTUP.parse() TPMA_STARTUP.to_string() TPMA_STARTUP.unmarshal() ``` -------------------------------- ### Get TPM Nonce from Session Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/ESAPI Fetches the TPM's nonce from a started session. This nonce is crucial for operations like PolicySigned, ensuring the integrity of the TPM's response during the session. ```Python def trsess_get_nonce_tpm(self, session: ESYS_TR) -> TPM2B_NONCE: """Retrieve the TPM nonce of an Esys_TR session object. Some operations (i.e. Esys_PolicySigned) require the nonce returned by the TPM during Esys_StartauthSession. This function provides this nonce to the caller. Args: session (ESYS_TR): The session handle. Returns: ``` -------------------------------- ### FAPI Provisioning Method Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/FAPI Details the `provision` method for initializing the Feature API. This method creates the keystore and necessary TPM objects. It accepts optional authentication values for endorsement, storage, and lockout hierarchies. ```Python def provision( self, auth_value_eh: Optional[Union[bytes, str]] = None, auth_value_sh: Optional[Union[bytes, str]] = None, auth_value_lockout: Optional[Union[bytes, str]] = None, is_provisioned_ok: bool = True, ) -> bool: """Provision the Feature API. Creates the keystore and creates some TPM objects. See also config file `/etc/tpm2-tss/fapi-config.json`. Args: auth_value_eh (bytes or str): Endorsement Hierarchy password. Defaults to None. ``` -------------------------------- ### Invoke TPM2_Startup Source: https://tpm2-pytss.readthedocs.io/en/latest/esys Invokes the TPM2_Startup command. This function initiates the TPM startup process. ```Python startup(_startup_type_) ``` -------------------------------- ### Python Versioning with Setuptools Source: https://tpm2-pytss.readthedocs.io/en/latest/release The project utilizes setuptools with `use_scm_version` for managing the package version. This means the version is automatically determined from source control, typically Git tags. It's crucial to build from a source distribution (like a git clone) rather than GitHub's auto-generated archives. ```Python # In setup.py or setup.cfg: from setuptools_scm import get_version setup( # ... other setup parameters ... use_scm_version=True, # or configure it: # use_scm_version={ # "write_to": "tpm2_pytss/_version.py", # "tag_regex": r"^(?P\d+).(?P\d+).(?P\d+)(?:-(?Pdev|pre|post|rc))?" # }, ) ``` -------------------------------- ### Create FAPIConfig with Temporary Directories Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/FAPI Demonstrates creating a FAPIConfig instance that sets up temporary directories for user, system, and log paths. This is useful for isolated FAPI operations. It shows how to initialize the configuration, potentially overriding default paths or using provided configuration dictionaries. ```Python from tpm2_pytss.fapi_config import FAPIConfig # Example usage with default temporary directories with FAPIConfig(temp_dirs=True) as fapi_config: # FAPI operations can be performed here using the temporary environment print("FAPI environment set up.") # The FAPI environment is automatically cleaned up upon exiting the 'with' block print("FAPI environment cleaned up.") # Example usage with a custom configuration dictionary custom_config = { "user_dir": "/path/to/custom/user", "system_dir": "/path/to/custom/system", "log_dir": "/path/to/custom/log" } with FAPIConfig(config=custom_config, temp_dirs=False) as fapi_config_custom: print("Custom FAPI environment set up.") # Example overriding specific settings with FAPIConfig(log_dir="/another/log/path", temp_dirs=True) as fapi_config_override: print("FAPI environment with overridden log directory set up.") ``` -------------------------------- ### ESYS_TR String Conversion Example Source: https://tpm2-pytss.readthedocs.io/en/latest/constants Provides an example of converting an integer value to its string name representation for ESYS_TR constants. ```python ESYS_TR.to_string(5) # -> ‘ESYS_TR.PCR5’ ``` -------------------------------- ### Git Tagging and Signing Source: https://tpm2-pytss.readthedocs.io/en/latest/release This section details the process of creating Git tags for releases and the importance of signing these tags using GPG for security and verification. It references external resources for detailed instructions on signing Git work. ```Git git tag -s -m "" # Example: git tag -s v1.2.0 -m "Release version 1.2.0" # To push tags to remote: git push origin --tags ``` ```Shell # To verify a signed tag: git tag -v # Example: git tag -v v1.2.0 ``` -------------------------------- ### TPML_Iterator: Iteration Example Source: https://tpm2-pytss.readthedocs.io/en/latest/types Provides an example of how to use the TPML_Iterator class for iterating over TPML data types, commonly used in for loops. ```python class TPML_Iterator: """Iterator class for iterating over TPML data types.""" # Example usage: # for alg in TPML_ALG: # do_something(alg) ``` -------------------------------- ### FAPI Initialization and Context Management Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/FAPI Demonstrates the initialization of the TPM2 Feature API (FAPI) using `Fapi_Initialize`. It shows how to manage the FAPI context, including entering and exiting a context using `__enter__` and `__exit__`, and finalizing the API with `Fapi_Finalize`. ```Python class FAPI: """The TPM2 Feature API. This class can be used as a python context or be closed manually via :meth:`~tpm2_pytss.FAPI.close`. """ def __init__(self, uri: Optional[Union[bytes, str]] = None): self.encoding = "utf-8" self._ctx_pp = ffi.new("FAPI_CONTEXT **") uri = _to_bytes_or_null(uri) ret = lib.Fapi_Initialize(self._ctx_pp, uri) _chkrc(ret) self._callback_metadata = {} @property def _ctx: """Get the Feature API C context used by the library to hold state. Returns: The Feature API C context. """ return self._ctx_pp[0] def __enter__(self): return self def __exit__(self, _type, value, traceback): self.close() def close(self) -> None: """Finalize the Feature API. This frees allocated memory and invalidates the FAPI object.""" lib.Fapi_Finalize(self._ctx_pp) ``` -------------------------------- ### HashSequenceStart: Initiate Hash Sequence Source: https://tpm2-pytss.readthedocs.io/en/latest/esys This function initiates a hash sequence using the TPM2_HashSequenceStart command. It requires authorization and a hash algorithm, and allows for session management. The function blocks until the TPM response is available. ```Python hash_sequence_start(_auth_ , _hash_alg_ , _session1 =4095_, _session2 =4095_, _session3 =4095_)[source]¶ Invoke the TPM2_HashSequenceStart command. This function invokes the TPM2_HashSequenceStart command in a one-call variant. This means the function will block until the TPM response is available. Parameters: * **auth** (_Union_ _[__TPM2B_AUTH_ _,__bytes_ _,__str_ _]_) – Authorization value for subsequent use of the sequence. * **hash_alg** (_TPM2_ALG_) – The hash algorithm to use for the hash sequence. * **session1** (_ESYS_TR_) – A session for securing the TPM command (optional). Defaults to ESYS_TR.PASSWORD. * **session2** (_ESYS_TR_) – A session for securing the TPM command (optional). Defaults to ESYS_TR.NONE. * **session3** (_ESYS_TR_) – A session for securing the TPM command (optional). Defaults to ESYS_TR.NONE. Raises: * **TypeError** – If a parameter is not of an expected type. * **ValueError** – If a parameter is not of an expected value. * **TSS2_Exception** – Any of the various TSS2_RC’s the lower layers can return. Returns: An ESYS_TR handle of ESYS resource for TPMI_DH_OBJECT. C Function: Esys_HashSequenceStart TPM Command: TPM2_HashSequenceStart ``` -------------------------------- ### TPMS_NV_PUBLIC Methods: Marshal, Unmarshal, Get Name, String Representation Source: https://tpm2-pytss.readthedocs.io/en/latest/api Explains the methods for TPMS_NV_PUBLIC, including marshaling, unmarshaling, getting the object's name, and generating a string representation. ```python from tpm2_pytss.tpm2_structures import TPMS_NV_PUBLIC # Example usage (assuming nv_public_bytes is a byte string) nv_public_bytes = b'...' nv_public_obj = TPMS_NV_PUBLIC() nv_public_obj.marshal(nv_public_bytes) print(nv_public_obj.get_name()) print(nv_public_obj.__str__()) nv_public_obj.unmarshal(nv_public_bytes) ``` -------------------------------- ### Get Calculated Policy Digest Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/policy Retrieves the digest of the calculated policy. This function interacts with the TPM to get the policy digest and returns it as a TPM2B_DIGEST structure. Raises TSS2_Exception if the digest retrieval fails. ```Python def get_calculated_digest(self) -> TPM2B_DIGEST: """Get the digest of the calculated policy Returns: The digest as a TPM2B_DIGEST. Raises: TSS2_Exception """ dig = ffi.new("TPM2B_DIGEST *") _chkrc(lib.Tss2_PolicyGetCalculatedDigest(self._ctx, dig)) ``` -------------------------------- ### FAPI: Provision TPM Source: https://tpm2-pytss.readthedocs.io/en/latest/fapi Provisions the TPM with initial configuration and security settings using the FAPI. This is a critical step for setting up a secure TPM environment. ```Python FAPI.provision() ``` -------------------------------- ### TPM Provisioning Source: https://tpm2-pytss.readthedocs.io/en/latest/fapi Function to provision the TPM Feature API (FAPI). This process involves creating the keystore and necessary TPM objects. It allows specifying authorization values for different hierarchies and controlling exception handling for already provisioned states. ```Python provision(_auth_value_eh =None_, _auth_value_sh =None_, _auth_value_lockout =None_, _is_provisioned_ok =True_) Provision the Feature API. Creates the keystore and creates some TPM objects. See also config file /etc/tpm2-tss/fapi_config.json. Parameters: auth_value_eh (_bytes_ _or_ _str_) – Endorsement Hierarchy password. Defaults to None. auth_value_sh (_bytes_ _or_ _str_) – Storage/Owner Hierarchy password. Defaults to None. auth_value_lockout (_bytes_ _or_ _str_) – Lockout Hierarchy password. Defaults to None. is_provisioned_ok (_bool_) – Do not throw a TSS2_Exception if Fapi is already provisioned. Defaults to True. Raises: TSS2_Exception – If Fapi returned an error code. Returns: True if Fapi was provisioned, False otherwise. Return type: bool ``` -------------------------------- ### Get RSA Key Size Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/cryptography Returns the size of the RSA key in bits. ```Python @property def key_size(self) -> int: """The RSA key size""" return self._public.parameters.rsaDetail.keyBits ``` -------------------------------- ### Get Policy JSON Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/policy Property to retrieve the JSON policy as bytes. ```Python @property def policy(self) -> bytes: """bytes: The JSON policy.""" return self._policy ``` -------------------------------- ### TPM2 Startup Command (Python) Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/ESAPI Invokes the TPM2_Startup command, which initializes the TPM. This function operates in a one-call variant, blocking until the TPM response is received. It accepts a startup type (TPM2_SU_CLEAR or TPM2_SU_STATE) and validates the input type. ```Python def startup(self, startup_type: TPM2_SU) -> None: """Invoke the TPM2_Startup command. This function invokes the TPM2_Startup command in a one-call variant. This means the function will block until the TPM response is available. Args: startup_type (TPM2_SU): TPM2_SU_CLEAR or TPM2_SU_STATE. Raises: TypeError: If a parameter is not of an expected type. ValueError: If a parameter is not of an expected value. TSS2_Exception: Any of the various TSS2_RC's the lower layers can return. C Function: Esys_Startup TPM Command: TPM2_Startup """ _check_friendly_int(startup_type, "startup_type", TPM2_SU) _chkrc(lib.Esys_Startup(self._ctx, startup_type)) ``` -------------------------------- ### Invoke TPM2_MAC_Start Command Source: https://tpm2-pytss.readthedocs.io/en/latest/esys This Python function invokes the TPM2_MAC_Start command in a one-call variant, blocking until the TPM response is available. It requires a handle for the MAC key, authorization, and hash algorithm, with optional sessions for security. ```Python mac_start(_handle_ , _auth_ , _hash_alg_ , _session1 =255_, _session2 =4095_, _session3 =4095_) ``` -------------------------------- ### Get TPM2_PT_FIRMWARE Constants Source: https://tpm2-pytss.readthedocs.io/en/latest/constants Represents constants related to TPM2_PT_FIRMWARE. Includes VERSION_1 and VERSION_2. ```python _class _tpm2_pytss.constants.TPM2_PT_FIRMWARE[source] VERSION_1 _ = 267_ VERSION_2 _ = 268_ ``` -------------------------------- ### TPM2B_ECC_POINT: Get String Representation Source: https://tpm2-pytss.readthedocs.io/en/latest/types The __str__ method for TPM2B_ECC_POINT returns its string representation. ```Python Return str(self). ``` -------------------------------- ### TPM2 MAC_Start Command Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/ESAPI Invokes the TPM2_MAC_Start command in a one-call variant, blocking until the TPM response is available. It requires a handle for an MAC key and authorization for sequence use. The function supports optional sessions for securing the command and returns an ESYS_TR handle for the ESYS resource. ```Python def mac_start( self, handle: ESYS_TR, auth: Union[TPM2B_AUTH, bytes, str], hash_alg: TPM2_ALG, session1: ESYS_TR = ESYS_TR.PASSWORD, session2: ESYS_TR = ESYS_TR.NONE, session3: ESYS_TR = ESYS_TR.NONE, ) -> ESYS_TR: """Invoke the TPM2_MAC_Start command. This function invokes the TPM2_MAC_Start command in a one-call variant. This means the function will block until the TPM response is available. Args: handle (ESYS_TR): Handle of an MAC key. auth (Union[TPM2B_AUTH, bytes, str]): Authorization value for subsequent use of the sequence. hash_alg (TPM2_ALG): The hash algorithm to use for the MAC. session1 (ESYS_TR): A session for securing the TPM command (optional). Defaults to ESYS_TR.PASSWORD. session2 (ESYS_TR): A session for securing the TPM command (optional). Defaults to ESYS_TR.NONE. session3 (ESYS_TR): A session for securing the TPM command (optional). Defaults to ESYS_TR.NONE. Raises: TypeError: If a parameter is not of an expected type. ValueError: If a parameter is not of an expected value. TSS2_Exception: Any of the various TSS2_RC's the lower layers can return. Returns: An ESYS_TR handle of ESYS resource for TPMI_DH_OBJECT. C Function: Esys_MAC_Start TPM Command: TPM2_MAC_Start """ if not _lib_version_atleast("tss2-esys", "4.0.0"): raise NotImplementedError("MAC api not supported below ESAPI v4") _check_handle_type(handle, "handle") _check_handle_type(session1, "session1") _check_handle_type(session2, "session2") _check_handle_type(session3, "session3") _check_friendly_int(hash_alg, "hash_alg", TPM2_ALG) if auth is None: auth = TPM2B_AUTH() auth_cdata = _get_cdata(auth, TPM2B_AUTH, "auth") sequence_handle = ffi.new("ESYS_TR *") _chkrc( lib.Esys_MAC_Start( self._ctx, handle, session1, session2, session3, auth_cdata, hash_alg, sequence_handle, ) ) return ESYS_TR(sequence_handle[0], ectx=self) ``` -------------------------------- ### TPM RSA Private Key Initialization Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/cryptography Initializes the `tpm_rsa_private_key` class, setting up the ESAPI instance, key handle, and session. It also reads the public part of the key and validates its type and attributes, ensuring it's an RSA key and not restricted. ```Python def __init__( self, ectx: ESAPI, handle: ESYS_TR, session: ESYS_TR = ESYS_TR.PASSWORD ): self._handle = handle self._session = session self._ectx = ectx public, _, _ = ectx.read_public(handle) self._public = public.publicArea if self._public.type != TPM2_ALG.RSA: raise ValueError( f"invalid key type, expected {TPM2_ALG.RSA}, got {self._public.type}" ) if self._public.objectAttributes & TPMA_OBJECT.RESTRICTED: raise ValueError( "TPM key does not allow generic signing and/or decryption (object attribute restricted is set)" ) ``` -------------------------------- ### Get TPM2_PT_CONTEXT Constants Source: https://tpm2-pytss.readthedocs.io/en/latest/constants Represents constants related to TPM2_PT_CONTEXT. Includes HASH, SYM, and SYM_SIZE. ```python _class _tpm2_pytss.constants.TPM2_PT_CONTEXT[source] HASH _ = 282_ SYM _ = 283_ SYM_SIZE _ = 284_ ``` -------------------------------- ### TPM2B_NV_PUBLIC Methods for Name and Marshaling Source: https://tpm2-pytss.readthedocs.io/en/latest/api Details methods for TPM2B_NV_PUBLIC, including getting the object name and marshaling/unmarshaling. ```Python TPM2B_NV_PUBLIC.__str__() TPM2B_NV_PUBLIC.get_name() TPM2B_NV_PUBLIC.marshal() TPM2B_NV_PUBLIC.unmarshal() ``` -------------------------------- ### TPMA_STARTUP Constants Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/constants Defines constants for TPM startup modes, including flags for enabling or disabling clear operations for platform, storage, and endorsement hierarchies, and a flag for orderly startup. ```Python class TPMA_STARTUP(TPMA_FRIENDLY_INTLIST): CLEAR_PHENABLE = 0x00000001 CLEAR_SHENABLE = 0x00000002 CLEAR_EHENABLE = 0x00000004 CLEAR_PHENABLENV = 0x00000008 CLEAR_RESERVED1_MASK = 0x7FFFFFF0 CLEAR_ORDERLY = 0x80000000 ``` -------------------------------- ### Get Policy Callback Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/policy Retrieves a registered callback function for a given policy callback type. ```Python def _get_callback(self, callback_type: policy_cb_types) -> Callable: return self._callbacks.get(callback_type) ``` -------------------------------- ### NVReadEK Callback for create_ek_template Source: https://tpm2-pytss.readthedocs.io/en/latest/utils Defines a callback function NVReadEK for use with create_ek_template. This callback is responsible for reading from NV areas and takes an ESAPI context and optional authorization handles and sessions as parameters. ```python class _tpm2_pytss.utils.NVReadEK(_ectx_ , _auth_handle =None_, _session1 =255_, _session2 =4095_, _session3 =4095_): """NV read callback to be used with create_ek_template""" pass ``` -------------------------------- ### Get Policy Hash Algorithm Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/policy Property to retrieve the hash algorithm used for policy calculations. ```Python @property def hash_alg(self) -> TPM2_ALG: """TPM2_ALG: The hash algorithm to be used during policy calculcation.""" return self._hash_alg ``` -------------------------------- ### Create EK Template for TPM Family 2.0 Source: https://tpm2-pytss.readthedocs.io/en/latest/utils Creates an Endorsement Key (EK) template that matches the EK certificate according to the TCG EK Credential Profile for TPM Family 2.0. It requires the EK type and a callback function for reading NV areas. The callback must raise NoSuchIndex if the NV index is undefined. Returns a tuple containing the certificate (or None) and the TPM2B_PUBLIC template. ```python def tpm2_pytss.utils.create_ek_template(_ektype_ , _nv_read_cb_): """Creates an Endorsenment Key template which when created matches the EK certificate The template is created according to TCG EK Credential Profile For TPM Family 2.0: - https://trustedcomputinggroup.org/resource/tcg-ek-credential-profile-for-tpm-family-2-0/ Parameters: * ektype (_str_) – The endoresment key type. * nv_read_cb (_Callable_ _[__int_ _,__TPM2_RH_ _]_) – The callback to use for reading NV areas. Note nv_read_cb MUST raise a NoSuchIndex exception if the NV index isn’t defined. Returns: A tuple of the certificate (can be None) and the template as a TPM2B_PUBLIC instance Raises: **ValueError** – If ektype is unknown or if a high range certificate is requested but not found.""" pass ``` -------------------------------- ### Get TPM2 TSS Library Version Source: https://tpm2-pytss.readthedocs.io/en/latest/fapi Retrieves the version of the tpm2-tss library. This is a property that returns the version as a string. ```python version ``` -------------------------------- ### Start TPM Authentication Session Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/ESAPI Invokes the TPM2_StartAuthSession command to establish a new session with the TPM. This is crucial for secure communication and command authorization. It requires parameters like a TPM key, binding entity, session type, symmetric encryption details, and a hash algorithm. ```Python pass # Placeholder for the actual implementation ``` -------------------------------- ### tpm2-pytss Modules Overview Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/index Lists all available modules within the tpm2-pytss library. These modules provide various functionalities for interacting with TPM 2.0 devices. ```Python tpm2_pytss.ESAPI tpm2_pytss.FAPI tpm2_pytss.TCTI tpm2_pytss.TCTILdr tpm2_pytss.TCTISPIHelper tpm2_pytss.TSS2_Exception tpm2_pytss.constants tpm2_pytss.cryptography tpm2_pytss.policy tpm2_pytss.tsskey tpm2_pytss.types tpm2_pytss.utils ``` -------------------------------- ### TPM2_SE Constants (Example Usage) Source: https://tpm2-pytss.readthedocs.io/en/latest/constants Demonstrates the usage of the `_to_string` method for TPM2_SE constants, converting an integer to its string representation. ```python ESYS_TR.to_string(5) -> ‘ESYS_TR.PCR5’ ``` -------------------------------- ### Invoke TPM2_FieldUpgradeStart Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/ESAPI Initiates the TPM field upgrade process by invoking the TPM2_FieldUpgradeStart command. This function requires a key handle, the digest of the firmware image, and a signature for authorization. It operates in a one-call variant, blocking until the TPM response is available. ```Python def field_upgrade_start( self, key_handle: ESYS_TR, fu_digest: Union[TPM2B_DIGEST, bytes, str], manifest_signature: TPMT_SIGNATURE, authorization: ESYS_TR = ESYS_TR.PLATFORM, session1: ESYS_TR = ESYS_TR.PASSWORD, session2: ESYS_TR = ESYS_TR.NONE, session3: ESYS_TR = ESYS_TR.NONE, ) -> None: """Invoke the TPM2_FieldUpgradeStart command. This function invokes the TPM2_FieldUpgradeStart command in a one-call variant. This means the function will block until the TPM response is available. Args: ``` -------------------------------- ### Unmarshal TPMU_HA Source: https://tpm2-pytss.readthedocs.io/en/latest/types Unmarshals bytes into a TPMU_HA type instance, guided by a selector. Returns the instance and the number of bytes consumed. ```python _classmethod _unmarshal(_selector_ , _buf_) ``` -------------------------------- ### TPM2 HashSequenceStart Command Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/ESAPI Invokes the TPM2_HashSequenceStart command in a one-call variant, blocking until the TPM response is available. It requires authorization for sequence use and specifies the hash algorithm. The function supports optional sessions for securing the command and returns an ESYS_TR handle for the ESYS resource. ```Python def hash_sequence_start( self, auth: Union[TPM2B_AUTH, bytes, str], hash_alg: TPM2_ALG, session1: ESYS_TR = ESYS_TR.NONE, session2: ESYS_TR = ESYS_TR.NONE, session3: ESYS_TR = ESYS_TR.NONE, ) -> ESYS_TR: """Invoke the TPM2_HashSequenceStart command. This function invokes the TPM2_HashSequenceStart command in a one-call variant. This means the function will block until the TPM response is available. Args: auth (Union[TPM2B_AUTH, bytes, str]): Authorization value for subsequent use of the sequence. hash_alg (TPM2_ALG): The hash algorithm to use for the hash sequence. session1 (ESYS_TR): A session for securing the TPM command (optional). Defaults to ESYS_TR.PASSWORD. session2 (ESYS_TR): A session for securing the TPM command (optional). Defaults to ESYS_TR.NONE. session3 (ESYS_TR): A session for securing the TPM command (optional). Defaults to ESYS_TR.NONE. Raises: TypeError: If a parameter is not of an expected type. ValueError: If a parameter is not of an expected value. TSS2_Exception: Any of the various TSS2_RC's the lower layers can return. Returns: An ESYS_TR handle of ESYS resource for TPMI_DH_OBJECT. C Function: Esys_HashSequenceStart TPM Command: TPM2_HashSequenceStart """ _check_handle_type(session1, "session1") _check_handle_type(session2, "session2") _check_handle_type(session3, "session3") _check_friendly_int(hash_alg, "hash_alg", TPM2_ALG) if auth is None: auth = TPM2B_AUTH() auth_cdata = _get_cdata(auth, TPM2B_AUTH, "auth") sequence_handle = ffi.new("ESYS_TR *") _chkrc( lib.Esys_HashSequenceStart( self._ctx, session1, session2, ``` -------------------------------- ### Get TPM2_PT_NV Constants Source: https://tpm2-pytss.readthedocs.io/en/latest/constants Represents constants related to TPM2_PT_NV (Non-Volatile). Includes buffer sizes, counters, and write recovery values. ```python _class _tpm2_pytss.constants.TPM2_PT_NV[source] BUFFER_MAX _ = 300_ COUNTERS _ = 522_ COUNTERS_AVAIL _ = 523_ COUNTERS_MAX _ = 278_ INDEX_MAX _ = 279_ WRITE_RECOVERY _ = 530_ ``` -------------------------------- ### TPM2 Constants: String Representation Source: https://tpm2-pytss.readthedocs.io/en/latest/constants Provides a method to get a lowercase string representation of a TPM2 constant. This is useful for debugging and logging. ```python str(ESYS_TR.PCR2) -> ‘pcr2’ ``` -------------------------------- ### Import Object into Keystore Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/FAPI Imports a policy, policy template, or key into the TPM2 keystore. It takes the desired path for the object and the JSON-encoded import data. The `exists_ok` parameter prevents errors if an object with the same path already exists. ```Python def import_object(self, path: Union[bytes, str], import_data: Union[bytes, str], exists_ok: bool = False) -> bool: """Import policy, policy template or key into the keystore. Args: path (bytes or str): Path of the future Fapi object. import_data (bytes or str): JSON-encoded data to import. exists_ok (bool): Do not throw a TSS2_Exception if an object with the given path already exists. Defaults to False. Raises: TSS2_Exception: If Fapi returned an error code. Returns: bool: True if the object was imported. False otherwise. """ _check_bug_fixed( fixed_in="3.2", details="FAPI Import will overwrite existing objects with same path silently. See https://github.com/tpm2-software/tpm2-tss/issues/2028", ) path = _to_bytes_or_null(path) import_data = _to_bytes_or_null(import_data) ret = lib.Fapi_Import(self._ctx, path, import_data) _chkrc( ret, acceptable=lib.TSS2_FAPI_RC_PATH_ALREADY_EXISTS if exists_ok else None ) return ret == lib.TPM2_RC_SUCCESS ``` -------------------------------- ### Get TCTI Context Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/ESAPI Retrieves the TCTI context used by the ESAPI. This is useful for performing a clean Tss2_Tcti_Finalize before the ESAPI context is finalized. ```Python return self._tcti ``` -------------------------------- ### TPMA_X509_KEY_USAGE Methods Source: https://tpm2-pytss.readthedocs.io/en/latest/constants Covers the methods for TPMA_X509_KEY_USAGE structures, detailing key usage attributes and their marshaling, parsing, and string conversion. ```python TPMA_X509_KEY_USAGE.CRLSIGN TPMA_X509_KEY_USAGE.DATAENCIPHERMENT TPMA_X509_KEY_USAGE.DECIPHER_ONLY TPMA_X509_KEY_USAGE.DIGITALSIGNATURE TPMA_X509_KEY_USAGE.ENCIPHER_ONLY TPMA_X509_KEY_USAGE.KEYAGREEMENT TPMA_X509_KEY_USAGE.KEYCERTSIGN TPMA_X509_KEY_USAGE.KEYENCIPHERMENT TPMA_X509_KEY_USAGE.NONREPUDIATION TPMA_X509_KEY_USAGE.__str__() TPMA_X509_KEY_USAGE.marshal() TPMA_X509_KEY_USAGE.parse() TPMA_X509_KEY_USAGE.to_string() TPMA_X509_KEY_USAGE.unmarshal() ``` -------------------------------- ### FAPI: Get TPM Information Source: https://tpm2-pytss.readthedocs.io/en/latest/fapi Retrieves general information about the TPM using the FAPI. This includes details like the TPM version and manufacturer. ```Python FAPI.get_info() ``` -------------------------------- ### FAPI Version and Configuration Retrieval Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/FAPI Provides methods to retrieve the tpm2-tss library version and FAPI configuration. It utilizes `get_info` to fetch FAPI information, parses it as JSON, and extracts the version and configuration details. ```Python # TODO flesh out info class @property def version: """ Get the tpm2-tss library version. Returns: str: The Feature API C context. """ info = json.loads(self.get_info()) return FapiInfo(info).version @property def config: """ # TODO doc, test info = json.loads(self.get_info()) return FapiInfo(info).fapi_config ``` -------------------------------- ### FAPI: Get Object Description Source: https://tpm2-pytss.readthedocs.io/en/latest/fapi Retrieves a descriptive string for a TPM object using the FAPI. This helps in identifying and managing TPM resources. ```Python FAPI.get_description() ``` -------------------------------- ### FAPI: Get Certificate Source: https://tpm2-pytss.readthedocs.io/en/latest/fapi Retrieves a certificate associated with a TPM object using the FAPI. This is often used for identity verification and secure communication. ```Python FAPI.get_certificate() ``` -------------------------------- ### Invoke TPM2_FieldUpgradeStart Command Source: https://tpm2-pytss.readthedocs.io/en/latest/esys This function invokes the TPM2_FieldUpgradeStart command in a one-call variant, blocking until the TPM response is available. It requires a key handle, field upgrade digest, manifest signature, authorization, and optional sessions. ```python field_upgrade_start(_key_handle_ , _fu_digest_ , _manifest_signature_ , _authorization =268_, _session1 =255_, _session2 =4095_, _session3 =4095_)[source]¶ ``` -------------------------------- ### Get TPM ECC Public Key Source: https://tpm2-pytss.readthedocs.io/en/latest/_modules/tpm2_pytss/cryptography Retrieves the public part of the ECC key. This method returns the public key formatted as a `cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey` object. ```Python def public_key(self) -> ec.EllipticCurvePublicKey: """Get the public key. Returns: the public part of the ECC key as a :py:class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey` """ return public_to_key(self._public) ``` -------------------------------- ### Get TPM2 Constant String Representation Source: https://tpm2-pytss.readthedocs.io/en/latest/constants Returns a string value of the constant normalized to lowercase. This method is available for various TPM2 constant classes. ```python str(ESYS_TR.PCR2) -> ‘pcr2’ ``` -------------------------------- ### Load TSSPrivKey Source: https://tpm2-pytss.readthedocs.io/en/latest/tsskey Loads the TSSPrivKey into the TPM. It requires an ESAPI instance and optionally a password for authorization. ```python load(_ectx_ , _password =None_) ``` -------------------------------- ### Get TPM2_PT_HR Constants Source: https://tpm2-pytss.readthedocs.io/en/latest/constants Represents constants related to TPM2_PT_HR (Handle Resource). Includes various availability and minimum values for different resource types. ```python _class _tpm2_pytss.constants.TPM2_PT_HR[source] ACTIVE _ = 517_ ACTIVE_AVAIL _ = 518_ LOADED _ = 515_ LOADED_AVAIL _ = 516_ LOADED_MIN _ = 272_ NV_INDEX _ = 514_ PERSISTENT _ = 520_ PERSISTENT_AVAIL _ = 521_ PERSISTENT_MIN _ = 271_ TRANSIENT_AVAIL _ = 519_ TRANSIENT_MIN _ = 270_ ```