├── .clippy.toml
├── .codespellrc
├── .devcontainer
├── Dockerfile
├── devcontainer.json
└── docker-compose.yml
├── .dockerignore
├── .github
└── workflows
│ ├── ci.yml
│ └── nightly.yml
├── .gitignore
├── CHANGELOG.md
├── Cargo.toml
├── LICENSE
├── MAINTAINERS.toml
├── README.md
├── SECURITY.md
├── tss-esapi-sys
├── Cargo.toml
├── LICENSE
├── README.md
├── build.rs
├── regenerate-bindings.sh
└── src
│ ├── bindings
│ ├── aarch64-unknown-linux-gnu.rs
│ ├── arm-unknown-linux-gnueabi.rs
│ ├── x86_64-unknown-darwin.rs
│ └── x86_64-unknown-linux-gnu.rs
│ └── lib.rs
└── tss-esapi
├── Cargo.toml
├── LICENSE
├── README.md
├── build.rs
├── examples
├── certify.rs
├── duplication.rs
├── duplication_secret.rs
├── hmac.rs
├── rsa_oaep.rs
├── sealed_data_object.rs
├── symmetric_file_encrypt_decrypt.rs
└── symmetric_file_encrypt_decrypt_example.txt
├── src
├── abstraction
│ ├── ak.rs
│ ├── cipher.rs
│ ├── ek.rs
│ ├── hashing.rs
│ ├── mod.rs
│ ├── no_tpm
│ │ ├── mod.rs
│ │ └── quote.rs
│ ├── nv.rs
│ ├── pcr.rs
│ ├── pcr
│ │ ├── bank.rs
│ │ └── data.rs
│ ├── public.rs
│ ├── signatures.rs
│ ├── signer.rs
│ └── transient
│ │ ├── key_attestation.rs
│ │ └── mod.rs
├── attributes
│ ├── algorithm.rs
│ ├── command_code.rs
│ ├── locality.rs
│ ├── mod.rs
│ ├── nv_index.rs
│ ├── object.rs
│ └── session.rs
├── constants
│ ├── algorithm.rs
│ ├── capabilities.rs
│ ├── command_code.rs
│ ├── command_code
│ │ └── structure.rs
│ ├── ecc.rs
│ ├── mod.rs
│ ├── nv_index_type.rs
│ ├── pcr_property_tag.rs
│ ├── property_tag.rs
│ ├── return_code.rs
│ ├── return_code
│ │ ├── base_error.rs
│ │ ├── layer.rs
│ │ ├── tpm.rs
│ │ └── tpm
│ │ │ ├── format_one.rs
│ │ │ ├── format_zero.rs
│ │ │ └── format_zero
│ │ │ ├── error.rs
│ │ │ └── warning.rs
│ ├── session_type.rs
│ ├── startup_type.rs
│ ├── structure_tags.rs
│ ├── tss.rs
│ └── types.rs
├── context.rs
├── context
│ ├── general_esys_tr.rs
│ ├── handle_manager.rs
│ ├── session_administration.rs
│ └── tpm_commands
│ │ ├── asymmetric_primitives.rs
│ │ ├── attached_components.rs
│ │ ├── attestation_commands.rs
│ │ ├── authenticated_countdown_timer.rs
│ │ ├── capability_commands.rs
│ │ ├── clocks_and_timers.rs
│ │ ├── command_audit.rs
│ │ ├── context_management.rs
│ │ ├── dictionary_attack_functions.rs
│ │ ├── duplication_commands.rs
│ │ ├── enhanced_authorization_ea_commands.rs
│ │ ├── ephemeral_ec_keys.rs
│ │ ├── field_upgrade.rs
│ │ ├── hash_hmac_event_sequences.rs
│ │ ├── hierarchy_commands.rs
│ │ ├── integrity_collection_pcr.rs
│ │ ├── miscellaneous_management_functions.rs
│ │ ├── mod.rs
│ │ ├── non_volatile_storage.rs
│ │ ├── object_commands.rs
│ │ ├── object_commands
│ │ ├── create_command_input.rs
│ │ └── create_command_output.rs
│ │ ├── random_number_generator.rs
│ │ ├── session_commands.rs
│ │ ├── signing_and_signature_verification.rs
│ │ ├── startup.rs
│ │ ├── symmetric_primitives.rs
│ │ ├── testing.rs
│ │ └── vendor_specific.rs
├── error.rs
├── error
│ ├── return_code.rs
│ ├── return_code
│ │ ├── base.rs
│ │ ├── esapi.rs
│ │ ├── fapi.rs
│ │ ├── muapi.rs
│ │ ├── sapi.rs
│ │ ├── tcti.rs
│ │ ├── tpm.rs
│ │ └── tpm
│ │ │ ├── format_one.rs
│ │ │ ├── format_one
│ │ │ └── argument_number.rs
│ │ │ ├── format_zero.rs
│ │ │ └── format_zero
│ │ │ ├── error.rs
│ │ │ └── warning.rs
│ └── wrapper.rs
├── ffi.rs
├── ffi
│ └── data_zeroize.rs
├── handles
│ ├── handle.rs
│ ├── mod.rs
│ └── tpm.rs
├── interface_types
│ ├── algorithm.rs
│ ├── data_handles.rs
│ ├── ecc.rs
│ ├── key_bits.rs
│ ├── mod.rs
│ ├── reserved_handles.rs
│ ├── session_handles.rs
│ ├── structure_tags.rs
│ └── yes_no.rs
├── lib.rs
├── structures
│ ├── algorithm.rs
│ ├── algorithm
│ │ ├── symmetric.rs
│ │ └── symmetric
│ │ │ └── sensitive_create.rs
│ ├── attestation
│ │ ├── attest.rs
│ │ ├── attest_info.rs
│ │ ├── certify_info.rs
│ │ ├── command_audit_info.rs
│ │ ├── creation_info.rs
│ │ ├── mod.rs
│ │ ├── nv_certify_info.rs
│ │ ├── nv_digest_certify_info.rs
│ │ ├── quote_info.rs
│ │ ├── session_audit_info.rs
│ │ └── time_attest_info.rs
│ ├── buffers.rs
│ ├── buffers
│ │ ├── attest.rs
│ │ ├── private.rs
│ │ ├── public.rs
│ │ ├── sensitive.rs
│ │ └── sensitive_create.rs
│ ├── capability_data.rs
│ ├── clock
│ │ ├── clock_info.rs
│ │ ├── mod.rs
│ │ └── time_info.rs
│ ├── creation.rs
│ ├── ecc
│ │ ├── mod.rs
│ │ └── point.rs
│ ├── hash
│ │ ├── agile.rs
│ │ └── mod.rs
│ ├── lists
│ │ ├── algorithm_property.rs
│ │ ├── command_code.rs
│ │ ├── command_code_attributes.rs
│ │ ├── digest.rs
│ │ ├── digest_values.rs
│ │ ├── ecc_curves.rs
│ │ ├── handles.rs
│ │ ├── mod.rs
│ │ ├── pcr_selection.rs
│ │ ├── tagged_pcr_property.rs
│ │ └── tagged_tpm_property.rs
│ ├── mod.rs
│ ├── names
│ │ ├── mod.rs
│ │ └── name.rs
│ ├── nv
│ │ ├── mod.rs
│ │ └── storage
│ │ │ ├── mod.rs
│ │ │ └── public.rs
│ ├── parameters.rs
│ ├── pcr
│ │ ├── mod.rs
│ │ ├── select.rs
│ │ ├── select_size.rs
│ │ ├── selection.rs
│ │ ├── slot.rs
│ │ └── slot_collection.rs
│ ├── property
│ │ ├── algorithm_property.rs
│ │ ├── mod.rs
│ │ ├── tagged_pcr_select.rs
│ │ └── tagged_property.rs
│ ├── result.rs
│ ├── schemes.rs
│ ├── signatures.rs
│ ├── tagged
│ │ ├── mod.rs
│ │ ├── parameters.rs
│ │ ├── public.rs
│ │ ├── public
│ │ │ ├── ecc.rs
│ │ │ ├── keyed_hash.rs
│ │ │ └── rsa.rs
│ │ ├── schemes.rs
│ │ ├── sensitive.rs
│ │ ├── signature.rs
│ │ └── symmetric.rs
│ ├── tickets.rs
│ └── tpm_context.rs
├── tcti_ldr.rs
├── traits.rs
└── utils
│ └── mod.rs
└── tests
├── Cargo.lock.frozen
├── Dockerfile-fedora
├── Dockerfile-fedora-rawhide
├── Dockerfile-opensuse-tw
├── Dockerfile-ubuntu
├── all-fedora.sh
├── all-opensuse.sh
├── all-ubuntu.sh
├── coverage.sh
├── create_frozen_cargo_lock
├── cross-compile.sh
├── integration_tests
├── abstraction_tests
│ ├── ak_tests.rs
│ ├── ek_tests.rs
│ ├── mod.rs
│ ├── no_tpm
│ │ ├── mod.rs
│ │ └── quote_test.rs
│ ├── nv_tests.rs
│ ├── pcr_data_tests.rs
│ ├── pcr_tests.rs
│ ├── public_tests.rs
│ └── transient_key_context_tests.rs
├── attributes_tests
│ ├── algorithm_attributes_tests.rs
│ ├── command_code_attributes_tests.rs
│ ├── locality_attributes_tests.rs
│ ├── mod.rs
│ ├── nv_index_attributes_tests.rs
│ └── session_attributes_tests.rs
├── common
│ ├── marshall.rs
│ ├── mod.rs
│ ├── serde.rs
│ ├── tpm2b_types_equality_checks.rs
│ ├── tpma_types_equality_checks.rs
│ ├── tpml_types_equality_checks.rs
│ ├── tpms_types_equality_checks.rs
│ └── tpmt_types_equality_checks.rs
├── constants_tests
│ ├── algorithm_tests.rs
│ ├── capabilities_tests.rs
│ ├── command_code_tests.rs
│ ├── mod.rs
│ ├── nv_index_type_tests.rs
│ ├── pcr_property_tag_tests.rs
│ └── return_code_tests
│ │ ├── base_return_code_tests.rs
│ │ ├── mod.rs
│ │ ├── return_code_layer_tests.rs
│ │ ├── tpm_format_one_error_tests.rs
│ │ ├── tpm_format_zero_error_tests.rs
│ │ └── tpm_format_zero_warning_tests.rs
├── context_tests
│ ├── general_esys_tr_tests.rs
│ ├── mod.rs
│ └── tpm_commands
│ │ ├── asymmetric_primitives_tests.rs
│ │ ├── attached_components_tests.rs
│ │ ├── attestation_commands_tests.rs
│ │ ├── authenticated_countdown_timer_tests.rs
│ │ ├── capability_commands_tests.rs
│ │ ├── clocks_and_timers_tests.rs
│ │ ├── command_audit_tests.rs
│ │ ├── context_management_tests.rs
│ │ ├── dictionary_attack_functions_tests.rs
│ │ ├── duplication_commands_tests.rs
│ │ ├── enhanced_authorization_ea_commands_tests.rs
│ │ ├── ephemeral_ec_keys_tests.rs
│ │ ├── field_upgrade_tests.rs
│ │ ├── hash_hmac_event_sequences_tests.rs
│ │ ├── hierarchy_commands_tests.rs
│ │ ├── integrity_collection_pcr_tests.rs
│ │ ├── miscellaneous_management_functions_tests.rs
│ │ ├── mod.rs
│ │ ├── non_volatile_storage_tests.rs
│ │ ├── object_commands_tests.rs
│ │ ├── random_number_generator_tests.rs
│ │ ├── session_commands_tests.rs
│ │ ├── signing_and_signature_verification_tests.rs
│ │ ├── startup_tests.rs
│ │ ├── symmetric_primitives_tests.rs
│ │ ├── testing_tests.rs
│ │ └── vendor_specific_tests.rs
├── error_tests.rs
├── error_tests
│ ├── return_code_tests.rs
│ ├── return_code_tests
│ │ ├── base_tests.rs
│ │ ├── esapi_tests.rs
│ │ ├── fapi_tests.rs
│ │ ├── muapi_tests.rs
│ │ ├── resource_manager_tests.rs
│ │ ├── resource_manager_tpm_tests.rs
│ │ ├── sapi_tests.rs
│ │ ├── tcti_tests.rs
│ │ ├── tpm_tests.rs
│ │ └── tpm_tests
│ │ │ ├── tpm_format_one_argument_number_tests.rs
│ │ │ ├── tpm_format_one_error_tests.rs
│ │ │ ├── tpm_format_zero_tests.rs
│ │ │ └── tpm_format_zero_tests
│ │ │ ├── tpm_format_zero_error_tests.rs
│ │ │ └── tpm_format_zero_warning_tests.rs
│ └── wrapper_error_kind_tests.rs
├── handles_tests
│ ├── auth_handle_tests.rs
│ ├── mod.rs
│ ├── object_handle_tests.rs
│ ├── pcr_handle_tests.rs
│ ├── session_handle_tests.rs
│ └── tpm_handles_tests.rs
├── interface_types_tests
│ ├── algorithms_tests.rs
│ ├── data_handles_tests.rs
│ ├── key_bits_tests.rs
│ ├── mod.rs
│ ├── reserved_handles_tests.rs
│ ├── structure_tags_tests.rs
│ └── yes_no_tests.rs
├── main.rs
├── structures_tests
│ ├── algorithm_property_tests.rs
│ ├── algorithm_tests
│ │ ├── mod.rs
│ │ └── symmetric_tests
│ │ │ ├── mod.rs
│ │ │ └── sensitive_create_tests.rs
│ ├── attest_info_test.rs
│ ├── attest_tests.rs
│ ├── buffers_tests
│ │ ├── attest_buffer_tests.rs
│ │ ├── auth_tests.rs
│ │ ├── data_tests.rs
│ │ ├── digest_tests.rs
│ │ ├── ecc_parameters_tests.rs
│ │ ├── encrypted_secret_test.rs
│ │ ├── id_object_tests.rs
│ │ ├── max_buffer_tests.rs
│ │ ├── mod.rs
│ │ ├── nonce_tests.rs
│ │ ├── private.rs
│ │ ├── public.rs
│ │ ├── sensitive.rs
│ │ └── sensitive_create_buffer_tests.rs
│ ├── capability_data_tests.rs
│ ├── certify_info_tests.rs
│ ├── clock_info_tests.rs
│ ├── command_audit_info_tests.rs
│ ├── creation_info_tests.rs
│ ├── lists_tests
│ │ ├── algorithm_property_list_tests.rs
│ │ ├── command_code_attributes_list_tests.rs
│ │ ├── command_code_list_tests.rs
│ │ ├── digest_list_tests.rs
│ │ ├── ecc_curve_list_tests.rs
│ │ ├── handle_list_tests.rs
│ │ ├── mod.rs
│ │ ├── pcr_selection_list_builder_tests.rs
│ │ ├── pcr_selection_list_tests.rs
│ │ ├── tagged_pcr_property_list_tests.rs
│ │ └── tagged_tpm_property_list_tests.rs
│ ├── mod.rs
│ ├── nv_certify_info_tests.rs
│ ├── pcr_tests
│ │ ├── mod.rs
│ │ ├── pcr_select_size_tests.rs
│ │ ├── pcr_select_tests.rs
│ │ ├── pcr_selection_tests.rs
│ │ └── pcr_slot_tests.rs
│ ├── quote_info_tests.rs
│ ├── session_audit_info_tests.rs
│ ├── tagged_pcr_select_tests.rs
│ ├── tagged_property_tests.rs
│ ├── tagged_tests
│ │ ├── mod.rs
│ │ ├── parameters_tests.rs
│ │ ├── public.rs
│ │ ├── public_ecc_parameters_tests.rs
│ │ ├── public_rsa_exponent_tests.rs
│ │ ├── public_rsa_parameters_tests.rs
│ │ ├── sensitive.rs
│ │ ├── signature.rs
│ │ ├── symmetric_definition_object_tests.rs
│ │ ├── symmetric_definition_tests.rs
│ │ ├── tagged_ecc_scheme_tests.rs
│ │ ├── tagged_key_derivation_function_scheme_tests.rs
│ │ ├── tagged_keyed_hash_scheme_tests.rs
│ │ ├── tagged_rsa_decryption_scheme_tests.rs
│ │ ├── tagged_rsa_scheme_tests.rs
│ │ └── tagged_signature_scheme_tests.rs
│ ├── time_attest_info_tests.rs
│ ├── time_info_tests.rs
│ └── tpm_context_tests.rs
├── tcti_ldr_tests
│ ├── mod.rs
│ ├── tcti_context_tests.rs
│ └── tcti_info_tests.rs
├── traits.rs
└── utils_tests
│ ├── get_tpm_vendor_test.rs
│ └── mod.rs
├── lint-checks.sh
├── pkg-config
└── valgrind.sh
/.clippy.toml:
--------------------------------------------------------------------------------
1 | msrv = "1.74.0"
2 |
--------------------------------------------------------------------------------
/.codespellrc:
--------------------------------------------------------------------------------
1 | [codespell]
2 | skip = .git,target,Cargo.lock
3 | ignore-words-list = acsend,crate,keypair,daa,de,ser
4 |
--------------------------------------------------------------------------------
/.devcontainer/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM rust:latest
2 |
3 | RUN apt -y update && apt -y install \
4 | autoconf-archive \
5 | libcmocka0 \
6 | libcmocka-dev \
7 | procps \
8 | iproute2 \
9 | build-essential \
10 | git \
11 | pkg-config \
12 | gcc \
13 | libtool \
14 | automake \
15 | libssl-dev \
16 | uthash-dev \
17 | autoconf \
18 | doxygen \
19 | libjson-c-dev \
20 | libini-config-dev \
21 | libcurl4-openssl-dev \
22 | uuid-dev \
23 | libltdl-dev \
24 | libusb-1.0-0-dev \
25 | libftdi-dev \
26 | clang
27 |
28 | WORKDIR /build
29 | ADD . /build
30 |
31 | # TPM Lib
32 | RUN git clone --depth 1 --branch 4.1.3 https://github.com/tpm2-software/tpm2-tss.git && \
33 | cd tpm2-tss && \
34 | ./bootstrap && \
35 | ./configure --prefix=/usr && \
36 | make -j5 && \
37 | make install
--------------------------------------------------------------------------------
/.devcontainer/devcontainer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Development environment",
3 | "dockerComposeFile": "docker-compose.yml",
4 | "service": "app",
5 | "workspaceFolder": "/workspaces/${localWorkspaceFolderBasename}",
6 | "customizations": {
7 | "vscode": {
8 | "extensions": [
9 | "1YiB.rust-bundle",
10 | "fill-labs.dependi"
11 | ],
12 | "settings": {
13 | "remote.autoForwardPorts": false,
14 | "editor.formatOnSave": true
15 | }
16 | }
17 | }
18 | }
--------------------------------------------------------------------------------
/.devcontainer/docker-compose.yml:
--------------------------------------------------------------------------------
1 | services:
2 | app:
3 | hostname: app
4 | build:
5 | context: .
6 | dockerfile: Dockerfile
7 | volumes:
8 | - ../..:/workspaces:cached
9 | command: sleep infinity
10 | network_mode: host
11 | environment:
12 | TPM2TOOLS_TCTI: mssim:host=localhost,port=2321
13 | deploy:
14 | resources:
15 | limits:
16 | cpus: '4.0'
17 | memory: 16G
18 |
19 | tpm:
20 | image: tpmdev/tpm2-runtime
21 | network_mode: host
22 | restart: unless-stopped
23 | environment:
24 | TPM2TOOLS_TCTI: mssim:host=localhost,port=2321
25 | command: /bin/bash -c "tpm_server >/dev/null & sleep 1; tpm2_startup -c; sleep infinity"
26 |
27 |
--------------------------------------------------------------------------------
/.dockerignore:
--------------------------------------------------------------------------------
1 | .git
2 | .github
3 | .gitignore
4 | .mypy_cache
5 | .vscode
6 | *.md
7 | **/__pycache__/**
8 | docs
9 | Makefile
10 | target
11 | test.db
12 | vendor
13 |
--------------------------------------------------------------------------------
/.github/workflows/nightly.yml:
--------------------------------------------------------------------------------
1 | name: Nightly Checks
2 |
3 | on:
4 | schedule:
5 | # Every night at midnight
6 | - cron: "0 0 * * *"
7 | workflow_dispatch:
8 |
9 | jobs:
10 | # This won't build on GA environment because of missing TSS
11 | # libraries. To be reactivated later or to pass using Docker.
12 | dependencies:
13 | name: Check for unused dependencies
14 | if: false
15 | runs-on: ubuntu-latest
16 | steps:
17 | - uses: actions/checkout@v2
18 | - name: Install latest Rust
19 | uses: actions-rs/toolchain@v1
20 | with:
21 | toolchain: nightly
22 | - name: Fetch submodules
23 | run: git submodule update --init
24 | - name: Install cargo udeps
25 | run: cargo install cargo-udeps --locked
26 | - name: Execute cargo udeps
27 | run: cargo udeps
28 |
29 | audit:
30 | name: Check for crates with security vulnerabilities
31 | runs-on: ubuntu-latest
32 | steps:
33 | - uses: actions/checkout@v2
34 | - name: Install latest Rust
35 | uses: actions-rs/toolchain@v1
36 | with:
37 | toolchain: nightly
38 | - name: Install cargo audit
39 | run: cargo install cargo-audit
40 | - name: Execute cargo audit
41 | run: cargo audit
42 |
43 | coverage:
44 | name: Calculate code coverage and cross compile
45 | runs-on: ubuntu-latest
46 | steps:
47 | - uses: actions/checkout@v2
48 | - name: Build the container
49 | run: docker build -t ubuntucontainer tss-esapi/tests/ --file tss-esapi/tests/Dockerfile-ubuntu
50 | - name: Run the code coverage script
51 | run: docker run -v $(pwd):/tmp/rust-tss-esapi -w /tmp/rust-tss-esapi/tss-esapi --security-opt seccomp=unconfined ubuntucontainer /tmp/rust-tss-esapi/tss-esapi/tests/coverage.sh
52 | - name: Collect coverage results
53 | run: bash <(curl -s https://codecov.io/bash)
54 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *target
2 | **/*.rs.bk
3 | *Cargo.lock
4 | *.swp
5 | *DS_Store
6 | *.patch
7 | *NVChip
8 | .vscode
9 | .cargo/
10 | vendor/
11 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [workspace]
2 | resolver = "2"
3 | members = ["tss-esapi", "tss-esapi-sys"]
4 |
--------------------------------------------------------------------------------
/MAINTAINERS.toml:
--------------------------------------------------------------------------------
1 | # tss-esapi crate maintainers file
2 | #
3 | # This file lists the maintainers of the parallaxsecond/rust-tss-esapi project.
4 | #
5 | # Its structure is inspired from the maintainers files in the Docker Github
6 | # repositories. Please see the MAINTAINERS file in docker/opensource for more
7 | # information.
8 |
9 | [maintainers]
10 |
11 | # Core maintainers of the project.
12 |
13 | [maintainers.core]
14 | people = [
15 | "hug-dev",
16 | "ionut-arm",
17 | "paulhowardarm",
18 | ]
19 |
20 | [people]
21 |
22 | # A reference list of all people associated with the project.
23 |
24 | [people.hug-dev]
25 | Name = "Hugues de Valon"
26 | Email = "hugues.devalon@arm.com"
27 | GitHub = "hug-dev"
28 |
29 | [people.ionut-arm]
30 | Name = "Ionut Mihalcea"
31 | Email = "ionut.mihalcea@arm.com"
32 | GitHub = "ionut-arm"
33 |
34 | [people.paulhowardarm]
35 | Name = "Paul Howard"
36 | Email = "paul.howard@arm.com"
37 | GitHub = "paulhowardarm"
38 |
39 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 | # TSS 2.0 Enhanced System API Rust Wrapper
3 |
4 | The `tss-esapi` Rust crate provides an idiomatic interface to the TCG TSS 2.0 Enhanced System API. We expose both direct FFI bindings (under the `tss-esapi-sys` crate) and abstracted versions, aimed at improved convenience of using the API.
5 |
6 | ## Minimum Supported Rust Version (MSRV)
7 |
8 | At the moment we test (via CI) and support the following Rust compiler versions:
9 |
10 | * On Ubuntu we test with:
11 | - The latest stable compiler version, as accessible through `rustup`.
12 | - The 1.74.0 compiler version.
13 | * On Fedora we test with the compiler version included with the Fedora 38 release.
14 | * On Fedora rawhide we test with the compiler version included.
15 |
16 | If you need support for other versions of the compiler, get in touch with us to see what we can do!
17 |
18 | ## Community channel
19 |
20 | Come and talk to us in [our Slack channel](https://github.com/parallaxsecond/community#community-channel)!
21 |
22 | ## Contributing
23 |
24 | We would be happy for you to contribute to the `tss-esapi` crate!
25 | Please check the [**Contribution Guidelines**](https://parallaxsecond.github.io/parsec-book/contributing/index.html)
26 | to know more about the contribution process.
27 |
28 | ## License
29 |
30 | The software is provided under Apache-2.0. Contributions to this project are accepted under the same license.
31 |
32 | *Copyright 2019 Contributors to the Parsec project.*
33 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security policy
2 |
3 | Security is of paramount importance to the tss-esapi project. We do all we can to identify and fix
4 | issues, however some problems might slip through the cracks. Any efforts towards responsible
5 | disclosure of security problems are greatly appreciated and your contributions will be acknowledged.
6 |
7 | ## Our disclosure policy
8 |
9 | All security vulnerabilities affecting the tss-esapi project - including those reported using the
10 | steps highlighted below, those discovered during routine testing, and those found in our dependency
11 | tree either through `cargo-audit` or otherwise - will receive
12 | [security advisories](https://github.com/parallaxsecond/rust-tss-esapi/security) in a timely
13 | manner. The advisories should include sufficient information about the cause, effect, and possible
14 | mitigations for the vulnerability. If any information is missing, or you would like to raise a
15 | question about the advisories, please open an issue in
16 | [our repo](https://github.com/parallaxsecond/rust-tss-esapi).
17 |
18 | Efforts to mitigate for the reported vulnerabilities will be tracked using GitHub issues linked to
19 | the corresponding advisories.
20 |
21 | ## Reporting a vulnerability
22 |
23 | To report a vulnerability, please send an email to
24 | [cncf-parsec-maintainers@lists.cncf.io](mailto:cncf-parsec-maintainers@lists.cncf.io). We will
25 | promptly reply to your report and we will strive to keep you in the loop as we try to reach a
26 | resolution.
27 |
28 | # Security considerations for the use of the software
29 |
30 | The authvalue provided to the TPM to perform certain operations like creating Primary Keys is
31 | currently randomly generated by [getrandom](https://crates.io/crates/getrandom), which assumes
32 | "that the system always provides high-quality cryptographically secure random data, ideally backed
33 | by hardware entropy sources."
34 |
35 | The user of this software should take this into consideration when setting up their system and using
36 | this software.
37 |
--------------------------------------------------------------------------------
/tss-esapi-sys/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "tss-esapi-sys"
3 | version = "0.5.0"
4 | authors = ["Parsec Project Contributors"]
5 | edition = "2021"
6 | description = "FFI wrapper around TSS 2.0 Enhanced System API"
7 | readme = "README.md"
8 | keywords = ["tpm", "tss", "esys", "esapi"]
9 | categories = ["api-bindings", "external-ffi-bindings", "cryptography"]
10 | license = "Apache-2.0"
11 | repository = "https://github.com/parallaxsecond/rust-tss-esapi"
12 | documentation = "https://docs.rs/crate/tss-esapi-sys"
13 | links = "tss2-esys"
14 | rust-version = "1.74.0"
15 |
16 | [build-dependencies]
17 | bindgen = { version = "0.70.1", optional = true }
18 | pkg-config = "0.3.18"
19 | target-lexicon = "0.12.0"
20 | cfg-if = "1.0.0"
21 | semver = "1.0.7"
22 |
23 | [features]
24 | generate-bindings = ["bindgen"]
25 |
--------------------------------------------------------------------------------
/tss-esapi-sys/src/lib.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | #![allow(
4 | non_snake_case,
5 | non_camel_case_types,
6 | non_upper_case_globals,
7 | clippy::unseparated_literal_suffix,
8 | improper_ctypes,
9 | missing_debug_implementations,
10 | trivial_casts,
11 | clippy::all,
12 | unused
13 | )]
14 | // Suppress warnings from bindgen-generated code
15 | // Remove on resolution of
16 | // https://github.com/rust-lang/rust-bindgen/issues/1651
17 | #![allow(deref_nullptr)]
18 | ///! This crate provides a basic interface for accessing the TSS Enhanced
19 | ///! System API from Rust. No abstraction is provided beyond what is
20 | ///! automatically generated by `bindgen` - the `tss-esapi` crate is the
21 | ///! one exposing an idiomatic Rust interface built on top of this FFI.
22 |
23 | // For supported targets: use the generated and committed bindings.
24 | #[cfg(all(
25 | not(feature = "generate-bindings"),
26 | target_arch = "x86_64",
27 | target_os = "linux"
28 | ))]
29 | include!(concat!(
30 | env!("CARGO_MANIFEST_DIR"),
31 | "/src/bindings/x86_64-unknown-linux-gnu.rs"
32 | ));
33 |
34 | #[cfg(all(
35 | not(feature = "generate-bindings"),
36 | target_arch = "aarch64",
37 | target_os = "linux"
38 | ))]
39 | include!(concat!(
40 | env!("CARGO_MANIFEST_DIR"),
41 | "/src/bindings/aarch64-unknown-linux-gnu.rs"
42 | ));
43 |
44 | #[cfg(all(
45 | not(feature = "generate-bindings"),
46 | target_arch = "arm",
47 | target_os = "linux"
48 | ))]
49 | include!(concat!(
50 | env!("CARGO_MANIFEST_DIR"),
51 | "/src/bindings/arm-unknown-linux-gnueabi.rs"
52 | ));
53 |
54 | #[cfg(all(
55 | not(feature = "generate-bindings"),
56 | target_arch = "x86_64",
57 | target_os = "macos"
58 | ))]
59 | include!(concat!(
60 | env!("CARGO_MANIFEST_DIR"),
61 | "/src/bindings/x86_64-unknown-darwin.rs"
62 | ));
63 |
64 | // If the "generate-bindings" feature is on, use the generated bindings.
65 | #[cfg(feature = "generate-bindings")]
66 | include!(concat!(env!("OUT_DIR"), "/tss_esapi_bindings.rs"));
67 |
--------------------------------------------------------------------------------
/tss-esapi/README.md:
--------------------------------------------------------------------------------
1 | # TPM2 Software Stack Rust Wrapper
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | This is the high-level, Rust idiomatic wrapper crate that exposes an interface
10 | to [TSS](https://github.com/tpm2-software/tpm2-tss).
11 |
12 | This crate depends on the [`tss-esapi-sys`](../tss-esapi-sys/) crate for its
13 | FFI interface. By default, pre-generated bindings are used. If you'd like the
14 | bindings to be generated at build time, please enable either the
15 | `generate-bindings` feature - the FFI bindings will then be generated at build
16 | time using the headers identified on the system.
17 |
18 | Our end-goal is to achieve a fully Rust-native interface that offers strong safety and security guarantees. Check out our [documentation](https://docs.rs/tss-esapi/*/tss_esapi/#notes-on-code-safety) for an overview of our code safety approach.
19 |
20 | ## Cargo Features
21 |
22 | The crate currently offers the following features:
23 |
24 | * `generate-bindings` - forces the underlying `tss-esapi-sys`
25 | crate to regenerate the FFI bindings on each build, using the TSS
26 | libraries available on the build machine.
27 | * `abstraction` (enabled by default) - provides a set of abstracted primitives
28 | on top of the basic Rust-native ESAPI API provided by the crate. This feature
29 | can be turned off to reduce the number of dependencies built.
30 | * `serde` - enable serde `Serialize`/`Deserialize` traits for types.
31 | * `rustcrypto-full` (disabled by default) - provides conversion from all
32 | supported elliptic curves, rsa or hashes.
33 | Support for individual hash, rsa or curves can be pulled individually.
34 |
35 | ## Cross compiling
36 |
37 | For more information on cross-compiling the `tss-esapi` crate, please see the README of the `tss-esapi-sys` crate.
38 |
39 | *Copyright 2021 Contributors to the Parsec project.*
40 |
--------------------------------------------------------------------------------
/tss-esapi/build.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use semver::{Version, VersionReq};
4 |
5 | fn main() {
6 | println!("cargo:rustc-check-cfg=cfg(hierarchy_is_esys_tr)");
7 | println!("cargo:rustc-check-cfg=cfg(has_tss_base_rc_values_28_to_51)");
8 | println!("cargo:rustc-check-cfg=cfg(has_tss_base_rc_values_52_to_53)");
9 | println!("cargo:rustc-check-cfg=cfg(has_tpmu_sensitive_create)");
10 | println!("cargo:rustc-check-cfg=cfg(has_esys_tr_get_tpm_handle)");
11 |
12 | let tss_version_string = std::env::var("DEP_TSS2_ESYS_VERSION")
13 | .expect("Failed to parse ENV variable DEP_TSS2_ESYS_VERSION as string");
14 |
15 | let tss_version = Version::parse(&tss_version_string)
16 | .expect("Failed to parse the DEP_TSS2_ESYS_VERSION variable as a semver version");
17 |
18 | let supported_tss_version =
19 | VersionReq::parse("<5.0.0, >=2.3.3").expect("Failed to parse supported TSS version");
20 |
21 | assert!(
22 | supported_tss_version.matches(&tss_version),
23 | "Unsupported TSS version {}",
24 | tss_version
25 | );
26 |
27 | let hierarchy_is_esys_tr_req = VersionReq::parse(">=3.0.0").unwrap();
28 | if hierarchy_is_esys_tr_req.matches(&tss_version) {
29 | println!("cargo:rustc-cfg=hierarchy_is_esys_tr")
30 | }
31 |
32 | let has_tss_base_rc_values_28_to_51_req = VersionReq::parse(">=2.4.0").unwrap();
33 | if has_tss_base_rc_values_28_to_51_req.matches(&tss_version) {
34 | println!("cargo:rustc-cfg=has_tss_base_rc_values_28_to_51")
35 | }
36 |
37 | let has_tss_base_rc_values_52_to_53_req = VersionReq::parse(">=3.0.0").unwrap();
38 | if has_tss_base_rc_values_52_to_53_req.matches(&tss_version) {
39 | println!("cargo:rustc-cfg=has_tss_base_rc_values_52_to_53")
40 | }
41 |
42 | let has_tpmu_sensitive_create_req = VersionReq::parse(">=4.0.0").unwrap();
43 | if has_tpmu_sensitive_create_req.matches(&tss_version) {
44 | println!("cargo:rustc-cfg=has_tpmu_sensitive_create")
45 | }
46 |
47 | #[cfg(feature = "generate-bindings")]
48 | {
49 | let has_esys_tr_get_tpm_handle_req = VersionReq::parse(">=2.4.0").unwrap();
50 | if has_esys_tr_get_tpm_handle_req.matches(&tss_version) {
51 | println!("cargo:rustc-cfg=has_esys_tr_get_tpm_handle")
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/tss-esapi/src/abstraction/hashing.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2024 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::interface_types::algorithm::HashingAlgorithm;
5 |
6 | /// Provides the value of the digest used in this crate for the digest.
7 | pub trait AssociatedHashingAlgorithm {
8 | /// Value of the digest when interacting with the TPM.
9 | const TPM_DIGEST: HashingAlgorithm;
10 | }
11 |
12 | #[cfg(feature = "sha1")]
13 | impl AssociatedHashingAlgorithm for sha1::Sha1 {
14 | const TPM_DIGEST: HashingAlgorithm = HashingAlgorithm::Sha1;
15 | }
16 |
17 | #[cfg(feature = "sha2")]
18 | impl AssociatedHashingAlgorithm for sha2::Sha256 {
19 | const TPM_DIGEST: HashingAlgorithm = HashingAlgorithm::Sha256;
20 | }
21 |
22 | #[cfg(feature = "sha2")]
23 | impl AssociatedHashingAlgorithm for sha2::Sha384 {
24 | const TPM_DIGEST: HashingAlgorithm = HashingAlgorithm::Sha384;
25 | }
26 |
27 | #[cfg(feature = "sha2")]
28 | impl AssociatedHashingAlgorithm for sha2::Sha512 {
29 | const TPM_DIGEST: HashingAlgorithm = HashingAlgorithm::Sha512;
30 | }
31 |
32 | #[cfg(feature = "sm3")]
33 | impl AssociatedHashingAlgorithm for sm3::Sm3 {
34 | const TPM_DIGEST: HashingAlgorithm = HashingAlgorithm::Sm3_256;
35 | }
36 |
37 | #[cfg(feature = "sha3")]
38 | impl AssociatedHashingAlgorithm for sha3::Sha3_256 {
39 | const TPM_DIGEST: HashingAlgorithm = HashingAlgorithm::Sha3_256;
40 | }
41 |
42 | #[cfg(feature = "sha3")]
43 | impl AssociatedHashingAlgorithm for sha3::Sha3_384 {
44 | const TPM_DIGEST: HashingAlgorithm = HashingAlgorithm::Sha3_384;
45 | }
46 |
47 | #[cfg(feature = "sha3")]
48 | impl AssociatedHashingAlgorithm for sha3::Sha3_512 {
49 | const TPM_DIGEST: HashingAlgorithm = HashingAlgorithm::Sha3_512;
50 | }
51 |
--------------------------------------------------------------------------------
/tss-esapi/src/abstraction/no_tpm/mod.rs:
--------------------------------------------------------------------------------
1 | #[cfg(all(
2 | any(feature = "p224", feature = "p256", feature = "p384", feature = "rsa"),
3 | any(feature = "sha1", feature = "sha2",)
4 | ))]
5 | mod quote;
6 | #[cfg(all(
7 | any(feature = "p224", feature = "p256", feature = "p384", feature = "rsa"),
8 | any(feature = "sha1", feature = "sha2",)
9 | ))]
10 | pub use quote::checkquote;
11 |
--------------------------------------------------------------------------------
/tss-esapi/src/abstraction/pcr.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod bank;
4 | mod data;
5 |
6 | use crate::{structures::PcrSelectionList, Context, Result};
7 |
8 | pub use bank::PcrBank;
9 | pub use data::PcrData;
10 |
11 | /// Function that reads all the PCRs in a selection list and returns
12 | /// the result as PCR data.
13 | ///
14 | /// # Example
15 | ///
16 | /// ```rust
17 | /// # use tss_esapi::{Context, TctiNameConf};
18 | /// # // Create context
19 | /// # let mut context =
20 | /// # Context::new(
21 | /// # TctiNameConf::from_environment_variable().expect("Failed to get TCTI"),
22 | /// # ).expect("Failed to create Context");
23 | /// #
24 | /// use tss_esapi::{
25 | /// interface_types::algorithm::HashingAlgorithm,
26 | /// structures::{PcrSelectionListBuilder, PcrSlot},
27 | /// };
28 | /// // Create PCR selection list with slots in a bank
29 | /// // that is going to be read.
30 | /// let pcr_selection_list = PcrSelectionListBuilder::new()
31 | /// .with_selection(HashingAlgorithm::Sha256,
32 | /// &[
33 | /// PcrSlot::Slot0,
34 | /// PcrSlot::Slot1,
35 | /// PcrSlot::Slot2,
36 | /// PcrSlot::Slot3,
37 | /// PcrSlot::Slot4,
38 | /// PcrSlot::Slot5,
39 | /// PcrSlot::Slot6,
40 | /// PcrSlot::Slot7,
41 | /// PcrSlot::Slot8,
42 | /// PcrSlot::Slot9,
43 | /// PcrSlot::Slot10,
44 | /// PcrSlot::Slot11,
45 | /// PcrSlot::Slot12,
46 | /// PcrSlot::Slot13,
47 | /// PcrSlot::Slot14,
48 | /// PcrSlot::Slot15,
49 | /// PcrSlot::Slot16,
50 | /// PcrSlot::Slot17,
51 | /// PcrSlot::Slot18,
52 | /// PcrSlot::Slot19,
53 | /// PcrSlot::Slot20,
54 | /// PcrSlot::Slot21,
55 | /// ])
56 | /// .build()
57 | /// .expect("Failed to build PcrSelectionList");
58 | /// let _pcr_data = tss_esapi::abstraction::pcr::read_all(&mut context, pcr_selection_list)
59 | /// .expect("pcr::read_all failed");
60 | /// ```
61 | pub fn read_all(
62 | context: &mut Context,
63 | mut pcr_selection_list: PcrSelectionList,
64 | ) -> Result {
65 | let mut pcr_data = PcrData::new();
66 | while !pcr_selection_list.is_empty() {
67 | let (_, pcrs_read, pcr_digests) = context.pcr_read(pcr_selection_list.clone())?;
68 | pcr_data.add(&pcrs_read, &pcr_digests)?;
69 | pcr_selection_list.subtract(&pcrs_read)?;
70 | }
71 | Ok(pcr_data)
72 | }
73 |
--------------------------------------------------------------------------------
/tss-esapi/src/attributes/algorithm.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::tss2_esys::TPMA_ALGORITHM;
5 | use bitfield::bitfield;
6 |
7 | bitfield! {
8 | /// Bitfield representing the algorithm attributes.
9 | #[derive(Copy, Clone, Eq, PartialEq)]
10 | pub struct AlgorithmAttributes(TPMA_ALGORITHM);
11 | impl Debug;
12 |
13 | pub asymmetric, _: 0;
14 | pub symmetric, _: 1;
15 | pub hash, _: 2;
16 | pub object, _: 3;
17 | // 7:4 Reserved
18 | pub signing, _: 8;
19 | pub encrypting, _: 9;
20 | pub method, _: 10;
21 | // 31:11 Reserved
22 | }
23 |
24 | impl From for AlgorithmAttributes {
25 | fn from(tpma_algorithm: TPMA_ALGORITHM) -> Self {
26 | AlgorithmAttributes(tpma_algorithm)
27 | }
28 | }
29 |
30 | impl From for TPMA_ALGORITHM {
31 | fn from(algorithm_attributes: AlgorithmAttributes) -> Self {
32 | algorithm_attributes.0
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/tss-esapi/src/attributes/mod.rs:
--------------------------------------------------------------------------------
1 | //! Module for representation of attributes
2 |
3 | /// Representation of the attributes defined in the
4 | /// Attribute structures -> TPMA_OBJECT section of
5 | /// the specification
6 | pub mod object;
7 |
8 | /// Representation of the attributes defined in the
9 | /// Attribute structures -> TPMA_OBJECT section of
10 | /// the specification.
11 | pub mod session;
12 |
13 | /// Representation of the attributes defined in the
14 | /// NV Storage -> TPMA_NV section of
15 | /// the specification.
16 | pub mod nv_index;
17 |
18 | pub mod locality;
19 |
20 | pub mod algorithm;
21 |
22 | pub mod command_code;
23 |
24 | pub use algorithm::AlgorithmAttributes;
25 | pub use command_code::CommandCodeAttributes;
26 | pub use locality::{LocalityAttributes, LocalityAttributesBuilder};
27 | pub use nv_index::{NvIndexAttributes, NvIndexAttributesBuilder};
28 | pub use object::{ObjectAttributes, ObjectAttributesBuilder};
29 | pub use session::{SessionAttributes, SessionAttributesBuilder, SessionAttributesMask};
30 |
--------------------------------------------------------------------------------
/tss-esapi/src/constants/capabilities.rs:
--------------------------------------------------------------------------------
1 | use crate::{Error, Result, WrapperErrorKind};
2 | use log::error;
3 | use num_derive::{FromPrimitive, ToPrimitive};
4 | use num_traits::{FromPrimitive, ToPrimitive};
5 | use std::convert::{From, TryFrom};
6 |
7 | use crate::{
8 | constants::tss::{
9 | TPM2_CAP_ACT, TPM2_CAP_ALGS, TPM2_CAP_AUDIT_COMMANDS, TPM2_CAP_AUTH_POLICIES,
10 | TPM2_CAP_COMMANDS, TPM2_CAP_ECC_CURVES, TPM2_CAP_HANDLES, TPM2_CAP_PCRS,
11 | TPM2_CAP_PCR_PROPERTIES, TPM2_CAP_PP_COMMANDS, TPM2_CAP_TPM_PROPERTIES,
12 | },
13 | tss2_esys::TPM2_CAP,
14 | };
15 |
16 | // Enum representing the different TPM Capability Type values.
17 | #[derive(FromPrimitive, ToPrimitive, Debug, Copy, Clone, PartialEq, Eq)]
18 | #[repr(u32)]
19 | pub enum CapabilityType {
20 | Algorithms = TPM2_CAP_ALGS,
21 | Handles = TPM2_CAP_HANDLES,
22 | Command = TPM2_CAP_COMMANDS,
23 | PpCommands = TPM2_CAP_PP_COMMANDS,
24 | AuditCommands = TPM2_CAP_AUDIT_COMMANDS,
25 | AssignedPcr = TPM2_CAP_PCRS,
26 | TpmProperties = TPM2_CAP_TPM_PROPERTIES,
27 | PcrProperties = TPM2_CAP_PCR_PROPERTIES,
28 | EccCurves = TPM2_CAP_ECC_CURVES,
29 | AuthPolicies = TPM2_CAP_AUTH_POLICIES,
30 | Act = TPM2_CAP_ACT,
31 | }
32 |
33 | impl From for TPM2_CAP {
34 | fn from(capability_type: CapabilityType) -> TPM2_CAP {
35 | // The values are well defined so this cannot fail.
36 | capability_type.to_u32().unwrap()
37 | }
38 | }
39 |
40 | impl TryFrom for CapabilityType {
41 | type Error = Error;
42 | fn try_from(tpm_capability_type: TPM2_CAP) -> Result {
43 | CapabilityType::from_u32(tpm_capability_type).ok_or_else(|| {
44 | error!(
45 | "value = {} did not match any CapabilityType.",
46 | tpm_capability_type
47 | );
48 | Error::local_error(WrapperErrorKind::InvalidParam)
49 | })
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/tss-esapi/src/constants/ecc.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::{
4 | constants::tss::{
5 | TPM2_ECC_BN_P256, TPM2_ECC_BN_P638, TPM2_ECC_NIST_P192, TPM2_ECC_NIST_P224,
6 | TPM2_ECC_NIST_P256, TPM2_ECC_NIST_P384, TPM2_ECC_NIST_P521, TPM2_ECC_SM2_P256,
7 | },
8 | tss2_esys::TPM2_ECC_CURVE,
9 | Error, Result, WrapperErrorKind,
10 | };
11 | use log::error;
12 | use num_derive::{FromPrimitive, ToPrimitive};
13 | use num_traits::{FromPrimitive, ToPrimitive};
14 | use std::convert::TryFrom;
15 | /// Enum that contains the constants for the
16 | /// implemented elliptic curves.
17 | ///
18 | /// # Details
19 | /// This corresponds to `TPM2_ECC_CURVE`
20 | #[derive(FromPrimitive, ToPrimitive, Debug, Copy, Clone, PartialEq, Eq, Hash)]
21 | #[repr(u16)]
22 | pub enum EccCurveIdentifier {
23 | NistP192 = TPM2_ECC_NIST_P192,
24 | NistP224 = TPM2_ECC_NIST_P224,
25 | NistP256 = TPM2_ECC_NIST_P256,
26 | NistP384 = TPM2_ECC_NIST_P384,
27 | NistP521 = TPM2_ECC_NIST_P521,
28 | BnP256 = TPM2_ECC_BN_P256,
29 | BnP638 = TPM2_ECC_BN_P638,
30 | Sm2P256 = TPM2_ECC_SM2_P256,
31 | }
32 |
33 | impl From for TPM2_ECC_CURVE {
34 | fn from(curve: EccCurveIdentifier) -> Self {
35 | // The values are well defined so this cannot fail.
36 | curve.to_u16().unwrap()
37 | }
38 | }
39 |
40 | impl TryFrom for EccCurveIdentifier {
41 | type Error = Error;
42 |
43 | fn try_from(tpm2_ecc_curve: TPM2_ECC_CURVE) -> Result {
44 | EccCurveIdentifier::from_u16(tpm2_ecc_curve).ok_or_else(|| {
45 | error!("Value = {} did not match any ecc curve.", tpm2_ecc_curve);
46 | Error::local_error(WrapperErrorKind::InvalidParam)
47 | })
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/tss-esapi/src/constants/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | //! This module contains both the constants defined in the TSS specification (tss module)
5 | //! but also the internal representation of the TSS constants.
6 |
7 | /// Representation of the constants defined in the
8 | /// Constants -> TPM_ALG_ID section of the specification
9 | mod algorithm;
10 | pub use algorithm::AlgorithmIdentifier;
11 |
12 | /// The constants defined in the TSS specification.
13 | #[allow(
14 | non_snake_case,
15 | non_camel_case_types,
16 | non_upper_case_globals,
17 | dead_code,
18 | clippy::all
19 | )]
20 | /// Exposes the constants form the TSS header.
21 | pub mod tss;
22 |
23 | /// Representation of the constants defined in the
24 | /// Constants -> TPM_ST section of the specification
25 | pub mod structure_tags;
26 |
27 | /// Representation of the constants defined in the
28 | /// Constants -> TPM_PT section of the specification
29 | pub mod property_tag;
30 |
31 | /// Representation of the constants defined in the
32 | /// Constants -> TPM_SU section of the specification
33 | pub mod startup_type;
34 |
35 | /// Representation of the constants defined in the
36 | /// Constants -> TPM_SE section of the specification
37 | pub mod session_type;
38 |
39 | /// Representation of the constants defined in the
40 | /// Constants -> TPM_CAP section of the specification
41 | pub mod capabilities;
42 |
43 | /// Representation of the return code TSS2_RC (TPM_RC)
44 | pub mod return_code;
45 |
46 | /// Representation of the constants defined in the
47 | /// NV Storage -> TPM_NT section of the specification
48 | pub mod nv_index_type;
49 |
50 | /// Representation of the constants defined in
51 | /// Constants -> TPM_ECC_CURVE section of the specification.
52 | pub mod ecc;
53 |
54 | /// Representation of the constants defined in
55 | /// Constants -> TPM_CC section of the specification.
56 | pub mod command_code;
57 |
58 | /// Representation of the constants defined in
59 | /// Constants -> TPM_PT_PCR section of the specification.
60 | pub mod pcr_property_tag;
61 |
62 | pub use capabilities::CapabilityType;
63 | pub use command_code::CommandCode;
64 | pub use ecc::EccCurveIdentifier;
65 | pub use nv_index_type::NvIndexType;
66 | pub use pcr_property_tag::PcrPropertyTag;
67 | pub use property_tag::PropertyTag;
68 | pub use return_code::{
69 | BaseError, ReturnCodeLayer, TpmFormatOneError, TpmFormatZeroError, TpmFormatZeroWarning,
70 | };
71 | pub use session_type::SessionType;
72 | pub use startup_type::StartupType;
73 | pub use structure_tags::StructureTag;
74 |
--------------------------------------------------------------------------------
/tss-esapi/src/constants/nv_index_type.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::{
4 | constants::tss::{
5 | TPM2_NT_BITS, TPM2_NT_COUNTER, TPM2_NT_EXTEND, TPM2_NT_ORDINARY, TPM2_NT_PIN_FAIL,
6 | TPM2_NT_PIN_PASS,
7 | },
8 | tss2_esys::TPM2_NT,
9 | Error, Result, WrapperErrorKind,
10 | };
11 | use log::error;
12 | use std::convert::TryFrom;
13 |
14 | /// Enum with values representing the NV index type.
15 | #[derive(Debug, Copy, Clone, PartialEq, Eq)]
16 | pub enum NvIndexType {
17 | Ordinary,
18 | Counter,
19 | Bits,
20 | Extend,
21 | PinFail,
22 | PinPass,
23 | }
24 |
25 | impl From for TPM2_NT {
26 | fn from(nv_index_type: NvIndexType) -> TPM2_NT {
27 | match nv_index_type {
28 | NvIndexType::Ordinary => TPM2_NT_ORDINARY,
29 | NvIndexType::Counter => TPM2_NT_COUNTER,
30 | NvIndexType::Bits => TPM2_NT_BITS,
31 | NvIndexType::Extend => TPM2_NT_EXTEND,
32 | NvIndexType::PinFail => TPM2_NT_PIN_FAIL,
33 | NvIndexType::PinPass => TPM2_NT_PIN_PASS,
34 | }
35 | }
36 | }
37 |
38 | impl TryFrom for NvIndexType {
39 | type Error = Error;
40 | fn try_from(tss_nv_index_type: TPM2_NT) -> Result {
41 | match tss_nv_index_type {
42 | TPM2_NT_ORDINARY => Ok(NvIndexType::Ordinary),
43 | TPM2_NT_COUNTER => Ok(NvIndexType::Counter),
44 | TPM2_NT_BITS => Ok(NvIndexType::Bits),
45 | TPM2_NT_EXTEND => Ok(NvIndexType::Extend),
46 | TPM2_NT_PIN_FAIL => Ok(NvIndexType::PinFail),
47 | TPM2_NT_PIN_PASS => Ok(NvIndexType::PinPass),
48 | _ => {
49 | error!("Found invalid value when trying to parse Nv Index Type");
50 | Err(Error::local_error(WrapperErrorKind::InvalidParam))
51 | }
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/tss-esapi/src/constants/pcr_property_tag.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::{
5 | constants::tss::{
6 | TPM2_PT_PCR_AUTH, TPM2_PT_PCR_DRTM_RESET, TPM2_PT_PCR_EXTEND_L0, TPM2_PT_PCR_EXTEND_L1,
7 | TPM2_PT_PCR_EXTEND_L2, TPM2_PT_PCR_EXTEND_L3, TPM2_PT_PCR_EXTEND_L4,
8 | TPM2_PT_PCR_NO_INCREMENT, TPM2_PT_PCR_POLICY, TPM2_PT_PCR_RESET_L0, TPM2_PT_PCR_RESET_L1,
9 | TPM2_PT_PCR_RESET_L2, TPM2_PT_PCR_RESET_L3, TPM2_PT_PCR_RESET_L4, TPM2_PT_PCR_SAVE,
10 | },
11 | tss2_esys::TPM2_PT_PCR,
12 | Error, Result, WrapperErrorKind,
13 | };
14 | use log::error;
15 | use num_derive::{FromPrimitive, ToPrimitive};
16 | use num_traits::{FromPrimitive, ToPrimitive};
17 | use std::convert::TryFrom;
18 |
19 | #[derive(FromPrimitive, ToPrimitive, Debug, Clone, Copy, PartialEq, Eq, Hash)]
20 | #[repr(u32)]
21 | pub enum PcrPropertyTag {
22 | Save = TPM2_PT_PCR_SAVE,
23 | ExtendL0 = TPM2_PT_PCR_EXTEND_L0,
24 | ResetL0 = TPM2_PT_PCR_RESET_L0,
25 | ExtendL1 = TPM2_PT_PCR_EXTEND_L1,
26 | ResetL1 = TPM2_PT_PCR_RESET_L1,
27 | ExtendL2 = TPM2_PT_PCR_EXTEND_L2,
28 | ResetL2 = TPM2_PT_PCR_RESET_L2,
29 | ExtendL3 = TPM2_PT_PCR_EXTEND_L3,
30 | ResetL3 = TPM2_PT_PCR_RESET_L3,
31 | ExtendL4 = TPM2_PT_PCR_EXTEND_L4,
32 | ResetL4 = TPM2_PT_PCR_RESET_L4,
33 | // Reserved 0x0000000B – 0x00000010
34 | NoIncrement = TPM2_PT_PCR_NO_INCREMENT,
35 | DrtmReset = TPM2_PT_PCR_DRTM_RESET,
36 | Policy = TPM2_PT_PCR_POLICY,
37 | Auth = TPM2_PT_PCR_AUTH,
38 | }
39 |
40 | impl From for TPM2_PT_PCR {
41 | fn from(pcr_property_tag: PcrPropertyTag) -> Self {
42 | // The values are well defined so this cannot fail.
43 | pcr_property_tag.to_u32().unwrap()
44 | }
45 | }
46 |
47 | impl TryFrom for PcrPropertyTag {
48 | type Error = Error;
49 |
50 | fn try_from(tpm_pt_pcr: TPM2_PT_PCR) -> Result {
51 | PcrPropertyTag::from_u32(tpm_pt_pcr).ok_or_else(|| {
52 | error!("value = {} did not match any PcrPropertyTag.", tpm_pt_pcr);
53 | Error::local_error(WrapperErrorKind::InvalidParam)
54 | })
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/tss-esapi/src/constants/return_code.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod base_error;
4 | mod layer;
5 | mod tpm;
6 |
7 | pub use base_error::BaseError;
8 | pub use layer::ReturnCodeLayer;
9 | pub use tpm::{TpmFormatOneError, TpmFormatZeroError, TpmFormatZeroWarning};
10 |
--------------------------------------------------------------------------------
/tss-esapi/src/constants/return_code/layer.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::{
4 | constants::tss::{
5 | TSS2_ESYS_RC_LAYER, TSS2_FEATURE_RC_LAYER, TSS2_MU_RC_LAYER, TSS2_RESMGR_RC_LAYER,
6 | TSS2_RESMGR_TPM_RC_LAYER, TSS2_SYS_RC_LAYER, TSS2_TCTI_RC_LAYER, TSS2_TPM_RC_LAYER,
7 | },
8 | Error, Result, WrapperErrorKind,
9 | };
10 |
11 | use log::error;
12 | use num_derive::{FromPrimitive, ToPrimitive};
13 | use num_traits::{FromPrimitive, ToPrimitive};
14 | use std::convert::TryFrom;
15 |
16 | /// Enum representing the TSS layer of a
17 | /// return code.
18 | #[derive(FromPrimitive, ToPrimitive, Copy, Clone, Debug, PartialEq, Eq, Hash)]
19 | #[repr(u8)]
20 | pub enum ReturnCodeLayer {
21 | Tpm = u32::to_le_bytes(TSS2_TPM_RC_LAYER)[2],
22 | Feature = u32::to_le_bytes(TSS2_FEATURE_RC_LAYER)[2],
23 | Esys = u32::to_le_bytes(TSS2_ESYS_RC_LAYER)[2],
24 | Sys = u32::to_le_bytes(TSS2_SYS_RC_LAYER)[2],
25 | Mu = u32::to_le_bytes(TSS2_MU_RC_LAYER)[2],
26 | Tcti = u32::to_le_bytes(TSS2_TCTI_RC_LAYER)[2],
27 | ResMgr = u32::to_le_bytes(TSS2_RESMGR_RC_LAYER)[2],
28 | ResMgrTpm = u32::to_le_bytes(TSS2_RESMGR_TPM_RC_LAYER)[2],
29 | }
30 |
31 | impl TryFrom for ReturnCodeLayer {
32 | type Error = Error;
33 |
34 | fn try_from(value: u8) -> Result {
35 | ReturnCodeLayer::from_u8(value).ok_or_else(|| {
36 | error!("{:#02X} is not valid ReturnCodeLayer", value);
37 | Error::local_error(WrapperErrorKind::InvalidParam)
38 | })
39 | }
40 | }
41 |
42 | impl From for u8 {
43 | fn from(return_code_layer: ReturnCodeLayer) -> u8 {
44 | // The values are well defined so unwrap cannot panic.
45 | return_code_layer.to_u8().unwrap()
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/tss-esapi/src/constants/return_code/tpm.rs:
--------------------------------------------------------------------------------
1 | // // Copyright 2022 Contributors to the Parsec project.
2 | // // SPDX-License-Identifier: Apache-2.0
3 | mod format_one;
4 | mod format_zero;
5 | pub use format_one::TpmFormatOneError;
6 | pub use format_zero::{TpmFormatZeroError, TpmFormatZeroWarning};
7 |
--------------------------------------------------------------------------------
/tss-esapi/src/constants/return_code/tpm/format_zero.rs:
--------------------------------------------------------------------------------
1 | // // Copyright 2022 Contributors to the Parsec project.
2 | // // SPDX-License-Identifier: Apache-2.0
3 | mod error;
4 | mod warning;
5 |
6 | pub use error::TpmFormatZeroError;
7 | pub use warning::TpmFormatZeroWarning;
8 |
--------------------------------------------------------------------------------
/tss-esapi/src/constants/session_type.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::{
4 | constants::tss::{TPM2_SE_HMAC, TPM2_SE_POLICY, TPM2_SE_TRIAL},
5 | tss2_esys::TPM2_SE,
6 | Error, Result, WrapperErrorKind,
7 | };
8 | use log::error;
9 | use num_derive::{FromPrimitive, ToPrimitive};
10 | use num_traits::{FromPrimitive, ToPrimitive};
11 | use std::convert::TryFrom;
12 |
13 | /// Enum representing the different TPM session types.
14 | #[derive(FromPrimitive, ToPrimitive, Debug, Copy, Clone, PartialEq, Eq)]
15 | #[repr(u8)]
16 | pub enum SessionType {
17 | Hmac = TPM2_SE_HMAC,
18 | Policy = TPM2_SE_POLICY,
19 | Trial = TPM2_SE_TRIAL,
20 | }
21 |
22 | impl From for TPM2_SE {
23 | fn from(session_type: SessionType) -> TPM2_SE {
24 | // The values are well defined so this cannot fail.
25 | session_type.to_u8().unwrap()
26 | }
27 | }
28 |
29 | impl TryFrom for SessionType {
30 | type Error = Error;
31 | fn try_from(tpm_session_type: TPM2_SE) -> Result {
32 | SessionType::from_u8(tpm_session_type).ok_or_else(|| {
33 | error!(
34 | "value = {} did not match any SessionType.",
35 | tpm_session_type
36 | );
37 | Error::local_error(WrapperErrorKind::InvalidParam)
38 | })
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/tss-esapi/src/constants/startup_type.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::{
4 | constants::tss::{TPM2_SU_CLEAR, TPM2_SU_STATE},
5 | tss2_esys::TPM2_SU,
6 | Error, Result, WrapperErrorKind,
7 | };
8 | use log::error;
9 | use num_derive::{FromPrimitive, ToPrimitive};
10 | use num_traits::{FromPrimitive, ToPrimitive};
11 | use std::convert::TryFrom;
12 | /// Enum repsenting the different TPM Startup Type values.
13 | #[derive(FromPrimitive, ToPrimitive, Debug, Copy, Clone, PartialEq, Eq)]
14 | #[repr(u16)]
15 | pub enum StartupType {
16 | Clear = TPM2_SU_CLEAR,
17 | State = TPM2_SU_STATE,
18 | }
19 |
20 | impl From for TPM2_SU {
21 | fn from(startup_type: StartupType) -> TPM2_SU {
22 | // The values are well defined so this cannot fail.
23 | startup_type.to_u16().unwrap()
24 | }
25 | }
26 |
27 | impl TryFrom for StartupType {
28 | type Error = Error;
29 | fn try_from(tpm_startup_type: TPM2_SU) -> Result {
30 | StartupType::from_u16(tpm_startup_type).ok_or_else(|| {
31 | error!(
32 | "value = {} did not match any StartupType.",
33 | tpm_startup_type
34 | );
35 | Error::local_error(WrapperErrorKind::InvalidParam)
36 | })
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/tss-esapi/src/constants/structure_tags.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::constants::tss::{
4 | TPM2_ST_ATTEST_CERTIFY, TPM2_ST_ATTEST_COMMAND_AUDIT, TPM2_ST_ATTEST_CREATION,
5 | TPM2_ST_ATTEST_NV, TPM2_ST_ATTEST_NV_DIGEST, TPM2_ST_ATTEST_QUOTE,
6 | TPM2_ST_ATTEST_SESSION_AUDIT, TPM2_ST_ATTEST_TIME, TPM2_ST_AUTH_SECRET, TPM2_ST_AUTH_SIGNED,
7 | TPM2_ST_CREATION, TPM2_ST_FU_MANIFEST, TPM2_ST_HASHCHECK, TPM2_ST_NO_SESSIONS, TPM2_ST_NULL,
8 | TPM2_ST_RSP_COMMAND, TPM2_ST_SESSIONS, TPM2_ST_VERIFIED,
9 | };
10 | use crate::{tss2_esys::TPM2_ST, Error, Result, WrapperErrorKind};
11 | use log::error;
12 | use num_derive::{FromPrimitive, ToPrimitive};
13 | use num_traits::{FromPrimitive, ToPrimitive};
14 | use std::convert::TryFrom;
15 |
16 | /// This enum represents the TPM_ST (Structure Tags)
17 | #[derive(FromPrimitive, ToPrimitive, Copy, Clone, Debug, PartialEq, Eq, Hash)]
18 | #[repr(u16)]
19 | pub enum StructureTag {
20 | RspCommand = TPM2_ST_RSP_COMMAND,
21 | Null = TPM2_ST_NULL,
22 | NoSessions = TPM2_ST_NO_SESSIONS,
23 | Sessions = TPM2_ST_SESSIONS,
24 | // Reserved1 = TPM2_ST_RESERVED1,
25 | // Reserved2 = TPM2_ST_RESERVED2,
26 | AttestNv = TPM2_ST_ATTEST_NV,
27 | AttestCommandAudit = TPM2_ST_ATTEST_COMMAND_AUDIT,
28 | AttestSessionAudit = TPM2_ST_ATTEST_SESSION_AUDIT,
29 | AttestCertify = TPM2_ST_ATTEST_CERTIFY,
30 | AttestQuote = TPM2_ST_ATTEST_QUOTE,
31 | AttestTime = TPM2_ST_ATTEST_TIME,
32 | AttestCreation = TPM2_ST_ATTEST_CREATION,
33 | // Reserved3 = TPM2_ST_RESERVED3,
34 | AttestNvDigest = TPM2_ST_ATTEST_NV_DIGEST,
35 | Creation = TPM2_ST_CREATION,
36 | Verified = TPM2_ST_VERIFIED,
37 | AuthSecret = TPM2_ST_AUTH_SECRET,
38 | Hashcheck = TPM2_ST_HASHCHECK,
39 | AuthSigned = TPM2_ST_AUTH_SIGNED,
40 | FuManifest = TPM2_ST_FU_MANIFEST,
41 | }
42 |
43 | impl TryFrom for StructureTag {
44 | type Error = Error;
45 | fn try_from(tpm_structure_tag: TPM2_ST) -> Result {
46 | StructureTag::from_u16(tpm_structure_tag).ok_or_else(|| {
47 | error!(
48 | "value = {} did not match any StructureTag.",
49 | tpm_structure_tag
50 | );
51 | Error::local_error(WrapperErrorKind::InvalidParam)
52 | })
53 | }
54 | }
55 |
56 | impl From for TPM2_ST {
57 | fn from(structure_tag: StructureTag) -> Self {
58 | // The values are well defined so this cannot fail.
59 | structure_tag.to_u16().unwrap()
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/tss-esapi/src/context/session_administration.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::{
4 | attributes::{SessionAttributes, SessionAttributesMask},
5 | handles::SessionHandle,
6 | interface_types::session_handles::AuthSession,
7 | tss2_esys::{Esys_TRSess_GetAttributes, Esys_TRSess_SetAttributes},
8 | Context, Result, ReturnCode,
9 | };
10 | use log::error;
11 | use std::convert::TryInto;
12 |
13 | impl Context {
14 | /// Set the given attributes on a given session.
15 | pub fn tr_sess_set_attributes(
16 | &mut self,
17 | session: AuthSession,
18 | attributes: SessionAttributes,
19 | mask: SessionAttributesMask,
20 | ) -> Result<()> {
21 | ReturnCode::ensure_success(
22 | unsafe {
23 | Esys_TRSess_SetAttributes(
24 | self.mut_context(),
25 | SessionHandle::from(session).into(),
26 | attributes.try_into()?,
27 | mask.try_into()?,
28 | )
29 | },
30 | |ret| {
31 | error!("Error when setting session attributes: {:#010X}", ret);
32 | },
33 | )
34 | }
35 |
36 | /// Get session attribute flags.
37 | pub fn tr_sess_get_attributes(&mut self, session: AuthSession) -> Result {
38 | let mut flags = 0;
39 | ReturnCode::ensure_success(
40 | unsafe {
41 | Esys_TRSess_GetAttributes(
42 | self.mut_context(),
43 | SessionHandle::from(session).into(),
44 | &mut flags,
45 | )
46 | },
47 | |ret| {
48 | error!("Error when getting session attributes: {:#010X}", ret);
49 | },
50 | )?;
51 | Ok(SessionAttributes(flags))
52 | }
53 |
54 | // Missing function: Esys_TRSess_GetNonceTPM
55 | }
56 |
--------------------------------------------------------------------------------
/tss-esapi/src/context/tpm_commands/attached_components.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::Context;
4 |
5 | impl Context {
6 | // Missing function: AC_GetCapability
7 | // Missing function: AC_Send
8 | // Missing function: Policy_AC_SendSelect
9 | }
10 |
--------------------------------------------------------------------------------
/tss-esapi/src/context/tpm_commands/authenticated_countdown_timer.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::Context;
4 |
5 | impl Context {
6 | // Missing function: ACT_SetTimeout
7 | }
8 |
--------------------------------------------------------------------------------
/tss-esapi/src/context/tpm_commands/clocks_and_timers.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::Context;
4 |
5 | impl Context {
6 | // Missing function: ReadClock
7 | // Missing function: ClockSet
8 | // Missing function: ClockRateAdjust
9 | }
10 |
--------------------------------------------------------------------------------
/tss-esapi/src/context/tpm_commands/command_audit.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::Context;
4 |
5 | impl Context {
6 | // Missing function: SetCommandCodeAuditStatus
7 | }
8 |
--------------------------------------------------------------------------------
/tss-esapi/src/context/tpm_commands/dictionary_attack_functions.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::Context;
4 |
5 | impl Context {
6 | // Missing function: DictionaryAttackLockReset
7 | // Missing function: DictionaryAttackParameters
8 | }
9 |
--------------------------------------------------------------------------------
/tss-esapi/src/context/tpm_commands/ephemeral_ec_keys.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::Context;
4 |
5 | impl Context {
6 | // Missing function: Commit
7 | // Missing function: EC_Ephemeral
8 | }
9 |
--------------------------------------------------------------------------------
/tss-esapi/src/context/tpm_commands/field_upgrade.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::Context;
4 |
5 | impl Context {
6 | // Missing function: FieldUpgradeStart
7 | // Missing function: FieldUpgradeData
8 | // Missing function: FirmwareRead
9 | }
10 |
--------------------------------------------------------------------------------
/tss-esapi/src/context/tpm_commands/hash_hmac_event_sequences.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::Context;
4 |
5 | impl Context {
6 | // Missing function: HMAC_Start
7 | // Missing function: MAC_Start
8 | // Missing function: HashSequenceStart
9 | // Missing function: SequenceUpdate
10 | // Missing function: SequenceComplete
11 | // Missing function: EventSequenceComplete
12 | }
13 |
--------------------------------------------------------------------------------
/tss-esapi/src/context/tpm_commands/miscellaneous_management_functions.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::Context;
4 |
5 | impl Context {
6 | // Missing function: PP_Commands
7 | // Missing function: SetAlgorithmSet
8 | }
9 |
--------------------------------------------------------------------------------
/tss-esapi/src/context/tpm_commands/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod asymmetric_primitives;
4 | mod attached_components;
5 | mod attestation_commands;
6 | mod authenticated_countdown_timer;
7 | mod capability_commands;
8 | mod clocks_and_timers;
9 | mod command_audit;
10 | mod context_management;
11 | mod dictionary_attack_functions;
12 | mod duplication_commands;
13 | mod enhanced_authorization_ea_commands;
14 | mod ephemeral_ec_keys;
15 | mod field_upgrade;
16 | mod hash_hmac_event_sequences;
17 | mod hierarchy_commands;
18 | mod integrity_collection_pcr;
19 | mod miscellaneous_management_functions;
20 | mod non_volatile_storage;
21 | mod object_commands;
22 | mod random_number_generator;
23 | mod session_commands;
24 | mod signing_and_signature_verification;
25 | mod startup;
26 | mod symmetric_primitives;
27 | mod testing;
28 | mod vendor_specific;
29 |
--------------------------------------------------------------------------------
/tss-esapi/src/context/tpm_commands/random_number_generator.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::{
4 | structures::{Digest, SensitiveData},
5 | tss2_esys::{Esys_GetRandom, Esys_StirRandom},
6 | Context, Error, Result, ReturnCode, WrapperErrorKind as ErrorKind,
7 | };
8 | use log::error;
9 | use std::convert::{TryFrom, TryInto};
10 | use std::ptr::null_mut;
11 |
12 | impl Context {
13 | /// Get a number of random bytes from the TPM and return them.
14 | ///
15 | /// # Errors
16 | /// * if converting `num_bytes` to `u16` fails, a `WrongParamSize` will be returned
17 | pub fn get_random(&mut self, num_bytes: usize) -> Result {
18 | let mut random_bytes_ptr = null_mut();
19 | ReturnCode::ensure_success(
20 | unsafe {
21 | Esys_GetRandom(
22 | self.mut_context(),
23 | self.optional_session_1(),
24 | self.optional_session_2(),
25 | self.optional_session_3(),
26 | num_bytes
27 | .try_into()
28 | .map_err(|_| Error::local_error(ErrorKind::WrongParamSize))?,
29 | &mut random_bytes_ptr,
30 | )
31 | },
32 | |ret| {
33 | error!("Error in getting random bytes: {:#010X}", ret);
34 | },
35 | )?;
36 | Digest::try_from(Context::ffi_data_to_owned(random_bytes_ptr))
37 | }
38 |
39 | /// Add additional information into the TPM RNG state
40 | pub fn stir_random(&mut self, in_data: SensitiveData) -> Result<()> {
41 | ReturnCode::ensure_success(
42 | unsafe {
43 | Esys_StirRandom(
44 | self.mut_context(),
45 | self.optional_session_1(),
46 | self.optional_session_2(),
47 | self.optional_session_3(),
48 | &in_data.into(),
49 | )
50 | },
51 | |ret| {
52 | error!("Error stirring random: {:#010X}", ret);
53 | },
54 | )
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/tss-esapi/src/context/tpm_commands/startup.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::{
4 | constants::StartupType,
5 | tss2_esys::{Esys_Shutdown, Esys_Startup},
6 | Context, Result, ReturnCode,
7 | };
8 | use log::error;
9 |
10 | impl Context {
11 | /// Send a TPM2_STARTUP command to the TPM
12 | pub fn startup(&mut self, startup_type: StartupType) -> Result<()> {
13 | ReturnCode::ensure_success(
14 | unsafe { Esys_Startup(self.mut_context(), startup_type.into()) },
15 | |ret| {
16 | error!("Error while starting up TPM: {:#010X}", ret);
17 | },
18 | )
19 | }
20 |
21 | /// Send a TPM2_SHUTDOWN command to the TPM
22 | pub fn shutdown(&mut self, shutdown_type: StartupType) -> Result<()> {
23 | ReturnCode::ensure_success(
24 | unsafe {
25 | Esys_Shutdown(
26 | self.mut_context(),
27 | self.optional_session_1(),
28 | self.optional_session_2(),
29 | self.optional_session_3(),
30 | shutdown_type.into(),
31 | )
32 | },
33 | |ret| {
34 | error!("Error while shutting down TPM: {:#010X}", ret);
35 | },
36 | )
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/tss-esapi/src/context/tpm_commands/vendor_specific.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::Context;
4 |
5 | impl Context {
6 | // Missing function: Vendor_TCG_Test
7 | }
8 |
--------------------------------------------------------------------------------
/tss-esapi/src/error.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod return_code;
4 | mod wrapper;
5 |
6 | pub use return_code::{
7 | ArgumentNumber, BaseReturnCode, EsapiReturnCode, FapiReturnCode, MuapiReturnCode, ReturnCode,
8 | SapiReturnCode, TctiReturnCode, TpmFormatOneResponseCode, TpmFormatZeroErrorResponseCode,
9 | TpmFormatZeroResponseCode, TpmFormatZeroWarningResponseCode, TpmResponseCode,
10 | };
11 | pub use wrapper::WrapperErrorKind;
12 |
13 | pub type Result = std::result::Result;
14 |
15 | /// Main error type used by the crate to return issues with a method call. The value can either be
16 | /// a TSS-generated response code or a wrapper error - marking an issue caught within the wrapping
17 | /// layer.
18 | #[derive(Debug, Copy, Clone, PartialEq, Eq)]
19 | pub enum Error {
20 | WrapperError(WrapperErrorKind),
21 | TssError(ReturnCode),
22 | }
23 |
24 | impl Error {
25 | /// Creates a wrapper error.
26 | pub(crate) const fn local_error(kind: WrapperErrorKind) -> Self {
27 | Error::WrapperError(kind)
28 | }
29 |
30 | /// Creates a TSS error.
31 | pub(crate) const fn tss_error(return_code: ReturnCode) -> Self {
32 | Error::TssError(return_code)
33 | }
34 | }
35 |
36 | impl std::fmt::Display for Error {
37 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38 | match self {
39 | Error::WrapperError(e) => e.fmt(f),
40 | Error::TssError(e) => e.fmt(f),
41 | }
42 | }
43 | }
44 |
45 | impl std::error::Error for Error {
46 | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
47 | match self {
48 | Error::WrapperError(wrapper_error) => Some(wrapper_error),
49 | Error::TssError(response_code) => Some(response_code),
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/tss-esapi/src/error/return_code/muapi.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::{constants::BaseError, error::BaseReturnCode, Error, Result, WrapperErrorKind};
4 | use log::error;
5 | use std::convert::TryFrom;
6 |
7 | /// Enum representing the error return codes generated by the MUAPI layer
8 | /// in TSS.
9 | #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
10 | pub struct MuapiReturnCode {
11 | base_error: BaseError,
12 | }
13 |
14 | impl MuapiReturnCode {
15 | /// Returns the BaseError associated with the MUAPI return code.
16 | pub const fn base_error(&self) -> BaseError {
17 | self.base_error
18 | }
19 | }
20 |
21 | impl From for BaseReturnCode {
22 | fn from(muapi_return_code: MuapiReturnCode) -> Self {
23 | muapi_return_code.base_error.into()
24 | }
25 | }
26 |
27 | impl TryFrom for MuapiReturnCode {
28 | type Error = Error;
29 |
30 | fn try_from(base_return_code: BaseReturnCode) -> Result {
31 | MuapiReturnCode::try_from(BaseError::from(base_return_code))
32 | }
33 | }
34 |
35 | impl TryFrom for MuapiReturnCode {
36 | type Error = Error;
37 |
38 | fn try_from(value: u16) -> Result {
39 | MuapiReturnCode::try_from(BaseError::try_from(value)?)
40 | }
41 | }
42 |
43 | impl From for u16 {
44 | fn from(muapi_error_code: MuapiReturnCode) -> Self {
45 | BaseReturnCode::from(muapi_error_code).into()
46 | }
47 | }
48 |
49 | impl TryFrom for MuapiReturnCode {
50 | type Error = Error;
51 |
52 | fn try_from(base_error: BaseError) -> Result {
53 | match base_error {
54 | BaseError::GeneralFailure
55 | | BaseError::BadReference
56 | | BaseError::BadSize
57 | | BaseError::BadValue
58 | | BaseError::InsufficientBuffer => Ok(MuapiReturnCode { base_error }),
59 | _ => {
60 | error!(
61 | "{} is not a valid MuapiReturnCode base error",
62 | u16::from(base_error)
63 | );
64 | Err(Error::local_error(WrapperErrorKind::InvalidParam))
65 | }
66 | }
67 | }
68 | }
69 |
70 | impl From for BaseError {
71 | fn from(muapi_return_code: MuapiReturnCode) -> Self {
72 | muapi_return_code.base_error
73 | }
74 | }
75 |
76 | impl std::error::Error for MuapiReturnCode {}
77 |
78 | impl std::fmt::Display for MuapiReturnCode {
79 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 | write!(f, "{}", BaseReturnCode::from(*self))
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/tss-esapi/src/error/return_code/tpm.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod format_one;
4 | mod format_zero;
5 |
6 | use crate::{Error, Result};
7 | use bitfield::bitfield;
8 | pub use format_one::{ArgumentNumber, TpmFormatOneResponseCode};
9 | pub use format_zero::{
10 | TpmFormatZeroErrorResponseCode, TpmFormatZeroResponseCode, TpmFormatZeroWarningResponseCode,
11 | };
12 | use std::convert::TryFrom;
13 |
14 | /// Enum representing an TPM response code.
15 | #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
16 | pub enum TpmResponseCode {
17 | FormatZero(TpmFormatZeroResponseCode),
18 | FormatOne(TpmFormatOneResponseCode),
19 | }
20 |
21 | impl TryFrom for TpmResponseCode {
22 | type Error = Error;
23 | fn try_from(value: u16) -> Result {
24 | if FormatSelector(value).is_format_one() {
25 | TpmFormatOneResponseCode::try_from(value).map(TpmResponseCode::FormatOne)
26 | } else {
27 | TpmFormatZeroResponseCode::try_from(value).map(TpmResponseCode::FormatZero)
28 | }
29 | }
30 | }
31 |
32 | impl From for u16 {
33 | fn from(tpm_response_code: TpmResponseCode) -> u16 {
34 | match tpm_response_code {
35 | TpmResponseCode::FormatOne(rc) => {
36 | let mut format_selector = FormatSelector(rc.into());
37 | format_selector.set_format_one(true);
38 | format_selector.0
39 | }
40 | TpmResponseCode::FormatZero(rc) => {
41 | let mut format_selector = FormatSelector(rc.into());
42 | format_selector.set_format_one(false);
43 | format_selector.0
44 | }
45 | }
46 | }
47 | }
48 |
49 | impl std::error::Error for TpmResponseCode {
50 | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
51 | match self {
52 | TpmResponseCode::FormatOne(rc) => Some(rc),
53 | TpmResponseCode::FormatZero(rc) => Some(rc),
54 | }
55 | }
56 | }
57 |
58 | impl std::fmt::Display for TpmResponseCode {
59 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 | match self {
61 | TpmResponseCode::FormatOne(e) => e.fmt(f),
62 | TpmResponseCode::FormatZero(e) => e.fmt(f),
63 | }
64 | }
65 | }
66 |
67 | bitfield! {
68 | struct FormatSelector(u16);
69 | impl Debug;
70 | is_format_one, set_format_one: 7;
71 | }
72 |
--------------------------------------------------------------------------------
/tss-esapi/src/handles/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | /// Module that contains the different types of handles
5 | /// that the ESAPI and the TPM uses in order to provide
6 | /// access to objects that was or has been created.
7 | // ///////////////////////////////////////////////////////
8 | // ESYS Handles
9 | // //////////////////////////////////////////////////////
10 | pub use handle::auth::AuthHandle;
11 | pub use handle::key::KeyHandle;
12 | pub use handle::nv_index::NvIndexHandle;
13 | pub use handle::object::ObjectHandle;
14 | pub use handle::pcr::PcrHandle;
15 | pub use handle::session::SessionHandle;
16 | pub(crate) mod handle_conversion {
17 | pub(crate) use super::handle::conversions::*;
18 | }
19 | mod handle;
20 | /////////////////////////////////////////////////////////
21 | /// TPM Handles
22 | /////////////////////////////////////////////////////////
23 | pub use tpm::attached_component::AttachedComponentTpmHandle;
24 | pub use tpm::hmac_session::HmacSessionTpmHandle;
25 | pub use tpm::loaded_session::LoadedSessionTpmHandle;
26 | pub use tpm::nv_index::NvIndexTpmHandle;
27 | pub use tpm::pcr::PcrTpmHandle;
28 | pub use tpm::permanent::PermanentTpmHandle;
29 | pub use tpm::persistent::PersistentTpmHandle;
30 | pub use tpm::policy_session::PolicySessionTpmHandle;
31 | pub use tpm::saved_session::SavedSessionTpmHandle;
32 | pub use tpm::transient::TransientTpmHandle;
33 | pub use tpm::TpmHandle;
34 | mod tpm;
35 |
--------------------------------------------------------------------------------
/tss-esapi/src/interface_types/ecc.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::{constants::EccCurveIdentifier, tss2_esys::TPMI_ECC_CURVE, Error, Result};
4 | use std::convert::TryFrom;
5 | /// Enum containing the implemented ECC curves
6 | ///
7 | /// # Details
8 | /// This corresponds to TPMI_ECC_CURVE
9 | #[derive(Debug, Copy, Clone, PartialEq, Eq)]
10 | pub enum EccCurve {
11 | NistP192,
12 | NistP224,
13 | NistP256,
14 | NistP384,
15 | NistP521,
16 | BnP256,
17 | BnP638,
18 | Sm2P256,
19 | }
20 |
21 | impl From for EccCurveIdentifier {
22 | fn from(ecc_curve: EccCurve) -> Self {
23 | match ecc_curve {
24 | EccCurve::NistP192 => EccCurveIdentifier::NistP192,
25 | EccCurve::NistP224 => EccCurveIdentifier::NistP224,
26 | EccCurve::NistP256 => EccCurveIdentifier::NistP256,
27 | EccCurve::NistP384 => EccCurveIdentifier::NistP384,
28 | EccCurve::NistP521 => EccCurveIdentifier::NistP521,
29 | EccCurve::BnP256 => EccCurveIdentifier::BnP256,
30 | EccCurve::BnP638 => EccCurveIdentifier::BnP638,
31 | EccCurve::Sm2P256 => EccCurveIdentifier::Sm2P256,
32 | }
33 | }
34 | }
35 |
36 | impl From for EccCurve {
37 | fn from(ecc_curve_identifier: EccCurveIdentifier) -> Self {
38 | match ecc_curve_identifier {
39 | EccCurveIdentifier::NistP192 => EccCurve::NistP192,
40 | EccCurveIdentifier::NistP224 => EccCurve::NistP224,
41 | EccCurveIdentifier::NistP256 => EccCurve::NistP256,
42 | EccCurveIdentifier::NistP384 => EccCurve::NistP384,
43 | EccCurveIdentifier::NistP521 => EccCurve::NistP521,
44 | EccCurveIdentifier::BnP256 => EccCurve::BnP256,
45 | EccCurveIdentifier::BnP638 => EccCurve::BnP638,
46 | EccCurveIdentifier::Sm2P256 => EccCurve::Sm2P256,
47 | }
48 | }
49 | }
50 |
51 | impl From for TPMI_ECC_CURVE {
52 | fn from(curve: EccCurve) -> Self {
53 | EccCurveIdentifier::from(curve).into()
54 | }
55 | }
56 |
57 | impl TryFrom for EccCurve {
58 | type Error = Error;
59 |
60 | fn try_from(tpmi_ecc_curve: TPMI_ECC_CURVE) -> Result {
61 | Ok(EccCurve::from(EccCurveIdentifier::try_from(
62 | tpmi_ecc_curve,
63 | )?))
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/tss-esapi/src/interface_types/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | //! This module contains the different interface types defined in
5 | //! the TPM 2.0 specification.
6 | mod yes_no;
7 |
8 | pub mod algorithm;
9 | pub mod data_handles;
10 | pub mod ecc;
11 | pub mod key_bits;
12 | pub mod reserved_handles;
13 | pub mod session_handles;
14 | pub mod structure_tags;
15 |
16 | pub use yes_no::YesNo;
17 |
--------------------------------------------------------------------------------
/tss-esapi/src/interface_types/yes_no.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::{tss2_esys::TPMI_YES_NO, Error, Result, WrapperErrorKind};
4 | use std::convert::TryFrom;
5 |
6 | /// Enum representing a yes or no.
7 | ///
8 | /// # Details
9 | /// This corresponds to the TPMI_YES_NO interface type.
10 | #[derive(Debug, Clone, Copy, PartialEq, Eq)]
11 | pub enum YesNo {
12 | Yes,
13 | No,
14 | }
15 |
16 | impl From for YesNo {
17 | fn from(value: bool) -> Self {
18 | if value {
19 | YesNo::Yes
20 | } else {
21 | YesNo::No
22 | }
23 | }
24 | }
25 |
26 | impl From for bool {
27 | fn from(yes_no: YesNo) -> Self {
28 | match yes_no {
29 | YesNo::Yes => true,
30 | YesNo::No => false,
31 | }
32 | }
33 | }
34 |
35 | impl From for TPMI_YES_NO {
36 | fn from(yes_no: YesNo) -> Self {
37 | match yes_no {
38 | YesNo::Yes => 1,
39 | YesNo::No => 0,
40 | }
41 | }
42 | }
43 |
44 | impl TryFrom for YesNo {
45 | type Error = Error;
46 |
47 | fn try_from(tpmi_yes_no: TPMI_YES_NO) -> Result {
48 | match tpmi_yes_no {
49 | 0 => Ok(YesNo::No),
50 | 1 => Ok(YesNo::Yes),
51 | _ => Err(Error::local_error(WrapperErrorKind::InvalidParam)),
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/algorithm.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | pub mod symmetric;
4 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/algorithm/symmetric.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | pub mod sensitive_create;
4 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/attestation/attest_info.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::{
5 | structures::{
6 | CertifyInfo, CommandAuditInfo, CreationInfo, NvCertifyInfo, QuoteInfo, SessionAuditInfo,
7 | TimeAttestInfo,
8 | },
9 | tss2_esys::TPMU_ATTEST,
10 | };
11 |
12 | /// Enum that holds the different types of
13 | /// attest info.
14 | ///
15 | /// # Details
16 | /// This type does to some degree corresponds to the
17 | /// TPMU_ATTEST but with the TPM_ST_ATTEST selectore
18 | /// included.
19 | #[derive(Debug, Clone)]
20 | pub enum AttestInfo {
21 | Certify { info: CertifyInfo },
22 | Quote { info: QuoteInfo },
23 | SessionAudit { info: SessionAuditInfo },
24 | CommandAudit { info: CommandAuditInfo },
25 | Time { info: TimeAttestInfo },
26 | Creation { info: CreationInfo },
27 | Nv { info: NvCertifyInfo },
28 | // NvDigest, the TPMS_NV_DIGEST_CERTIFY_INFO,
29 | // was first added in the 3.1.0 version of the tpm2-tss
30 | }
31 |
32 | impl From for TPMU_ATTEST {
33 | fn from(attest_info: AttestInfo) -> Self {
34 | match attest_info {
35 | AttestInfo::Certify { info } => TPMU_ATTEST {
36 | certify: info.into(),
37 | },
38 | AttestInfo::Quote { info } => TPMU_ATTEST { quote: info.into() },
39 | AttestInfo::SessionAudit { info } => TPMU_ATTEST {
40 | sessionAudit: info.into(),
41 | },
42 | AttestInfo::CommandAudit { info } => TPMU_ATTEST {
43 | commandAudit: info.into(),
44 | },
45 | AttestInfo::Time { info } => TPMU_ATTEST { time: info.into() },
46 | AttestInfo::Creation { info } => TPMU_ATTEST {
47 | creation: info.into(),
48 | },
49 | AttestInfo::Nv { info } => TPMU_ATTEST { nv: info.into() },
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/attestation/certify_info.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::{structures::Name, tss2_esys::TPMS_CERTIFY_INFO, Error, Result};
5 | use std::convert::{TryFrom, TryInto};
6 | /// This a struct holding the attested data for the command TPM2_Certify
7 | ///
8 | /// # Details
9 | /// This corresponds to the TPMS_CERTIFY_INFO.
10 | #[derive(Debug, Clone)]
11 | pub struct CertifyInfo {
12 | name: Name,
13 | qualified_name: Name,
14 | }
15 |
16 | impl CertifyInfo {
17 | /// Returns a reference to the name
18 | pub const fn name(&self) -> &Name {
19 | &self.name
20 | }
21 |
22 | /// Returns a reference to the qualified name
23 | pub const fn qualified_name(&self) -> &Name {
24 | &self.qualified_name
25 | }
26 | }
27 |
28 | impl From for TPMS_CERTIFY_INFO {
29 | fn from(certify_info: CertifyInfo) -> Self {
30 | TPMS_CERTIFY_INFO {
31 | name: certify_info.name.into(),
32 | qualifiedName: certify_info.qualified_name.into(),
33 | }
34 | }
35 | }
36 |
37 | impl TryFrom for CertifyInfo {
38 | type Error = Error;
39 |
40 | fn try_from(tpms_certify_info: TPMS_CERTIFY_INFO) -> Result {
41 | Ok(CertifyInfo {
42 | name: tpms_certify_info.name.try_into()?,
43 | qualified_name: tpms_certify_info.qualifiedName.try_into()?,
44 | })
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/attestation/command_audit_info.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::{
5 | constants::AlgorithmIdentifier, interface_types::algorithm::HashingAlgorithm,
6 | structures::Digest, tss2_esys::TPMS_COMMAND_AUDIT_INFO, Error, Result,
7 | };
8 |
9 | use std::convert::{TryFrom, TryInto};
10 |
11 | /// Structure holding the attested data for
12 | /// TPM2_GetCommandAuditDigest().
13 | ///
14 | /// # Details
15 | /// This corresponds to the TPMS_COMMAND_AUDIT_INFO
16 | #[derive(Debug, Clone)]
17 | pub struct CommandAuditInfo {
18 | audit_counter: u64,
19 | hashing_algorithm: HashingAlgorithm,
20 | audit_digest: Digest,
21 | command_digest: Digest,
22 | }
23 |
24 | impl CommandAuditInfo {
25 | /// Returns the audit counter
26 | pub const fn audit_counter(&self) -> u64 {
27 | self.audit_counter
28 | }
29 |
30 | /// Returns the hash algorithm used for the command audit
31 | pub const fn hashing_algorithm(&self) -> HashingAlgorithm {
32 | self.hashing_algorithm
33 | }
34 |
35 | /// Returns the audit digest
36 | pub const fn audit_digest(&self) -> &Digest {
37 | &self.audit_digest
38 | }
39 |
40 | /// Returns the command digest
41 | pub const fn command_digest(&self) -> &Digest {
42 | &self.command_digest
43 | }
44 | }
45 |
46 | impl From for TPMS_COMMAND_AUDIT_INFO {
47 | fn from(command_audit_info: CommandAuditInfo) -> Self {
48 | TPMS_COMMAND_AUDIT_INFO {
49 | auditCounter: command_audit_info.audit_counter,
50 | digestAlg: AlgorithmIdentifier::from(command_audit_info.hashing_algorithm).into(),
51 | auditDigest: command_audit_info.audit_digest.into(),
52 | commandDigest: command_audit_info.command_digest.into(),
53 | }
54 | }
55 | }
56 |
57 | impl TryFrom for CommandAuditInfo {
58 | type Error = Error;
59 |
60 | fn try_from(tpms_command_audit_info: TPMS_COMMAND_AUDIT_INFO) -> Result {
61 | Ok(CommandAuditInfo {
62 | audit_counter: tpms_command_audit_info.auditCounter,
63 | hashing_algorithm: AlgorithmIdentifier::try_from(tpms_command_audit_info.digestAlg)?
64 | .try_into()?,
65 | audit_digest: tpms_command_audit_info.auditDigest.try_into()?,
66 | command_digest: tpms_command_audit_info.commandDigest.try_into()?,
67 | })
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/attestation/creation_info.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::{
5 | structures::{Digest, Name},
6 | tss2_esys::TPMS_CREATION_INFO,
7 | Error, Result,
8 | };
9 | use std::convert::{TryFrom, TryInto};
10 | /// Structure holding the attested data for TPM2_CertifyCreation()
11 | ///
12 | /// # Details
13 | /// This corresponds to the TPMS_CREATION_INFO
14 | #[derive(Debug, Clone)]
15 | pub struct CreationInfo {
16 | object_name: Name,
17 | creation_hash: Digest,
18 | }
19 |
20 | impl CreationInfo {
21 | /// Returns the name of the object
22 | pub const fn object_name(&self) -> &Name {
23 | &self.object_name
24 | }
25 |
26 | /// Returns the creation hash
27 | pub const fn creation_hash(&self) -> &Digest {
28 | &self.creation_hash
29 | }
30 | }
31 |
32 | impl From for TPMS_CREATION_INFO {
33 | fn from(creation_info: CreationInfo) -> Self {
34 | TPMS_CREATION_INFO {
35 | objectName: creation_info.object_name.into(),
36 | creationHash: creation_info.creation_hash.into(),
37 | }
38 | }
39 | }
40 |
41 | impl TryFrom for CreationInfo {
42 | type Error = Error;
43 |
44 | fn try_from(tpms_creation_info: TPMS_CREATION_INFO) -> Result {
45 | Ok(CreationInfo {
46 | object_name: tpms_creation_info.objectName.try_into()?,
47 | creation_hash: tpms_creation_info.creationHash.try_into()?,
48 | })
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/attestation/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | pub mod attest;
4 | pub mod attest_info;
5 | pub mod certify_info;
6 | pub mod command_audit_info;
7 | pub mod creation_info;
8 | pub mod nv_certify_info;
9 | pub mod nv_digest_certify_info;
10 | pub mod quote_info;
11 | pub mod session_audit_info;
12 | pub mod time_attest_info;
13 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/attestation/nv_certify_info.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::{
5 | structures::{MaxNvBuffer, Name},
6 | tss2_esys::TPMS_NV_CERTIFY_INFO,
7 | Error, Result,
8 | };
9 | use std::convert::{TryFrom, TryInto};
10 | /// This structure contains the Name and contents of the
11 | /// selected NV Index that is certified by TPM2_NV_Certify()
12 | ///
13 | /// # Details
14 | /// This corresponds to the TPMS_NV_CERTIFY_INFO.
15 | #[derive(Debug, Clone)]
16 | pub struct NvCertifyInfo {
17 | index_name: Name,
18 | offset: u16,
19 | nv_contents: MaxNvBuffer,
20 | }
21 |
22 | impl NvCertifyInfo {
23 | /// Returns index name
24 | pub const fn index_name(&self) -> &Name {
25 | &self.index_name
26 | }
27 |
28 | /// Returns offset
29 | pub const fn offset(&self) -> u16 {
30 | self.offset
31 | }
32 |
33 | /// Returns nv contents
34 | pub const fn nv_contents(&self) -> &MaxNvBuffer {
35 | &self.nv_contents
36 | }
37 | }
38 |
39 | impl From for TPMS_NV_CERTIFY_INFO {
40 | fn from(nv_certify_info: NvCertifyInfo) -> Self {
41 | TPMS_NV_CERTIFY_INFO {
42 | indexName: nv_certify_info.index_name.into(),
43 | offset: nv_certify_info.offset,
44 | nvContents: nv_certify_info.nv_contents.into(),
45 | }
46 | }
47 | }
48 |
49 | impl TryFrom for NvCertifyInfo {
50 | type Error = Error;
51 |
52 | fn try_from(tpms_nv_certify_info: TPMS_NV_CERTIFY_INFO) -> Result {
53 | Ok(NvCertifyInfo {
54 | index_name: tpms_nv_certify_info.indexName.try_into()?,
55 | offset: tpms_nv_certify_info.offset,
56 | nv_contents: tpms_nv_certify_info.nvContents.try_into()?,
57 | })
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/attestation/nv_digest_certify_info.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::structures::{Digest, Name};
5 |
6 | /// This structure contains the Name and hash of the
7 | /// contents of the selected NV Index that is certified by
8 | /// TPM2_NV_Certify()
9 | ///
10 | /// # Details
11 | /// This corresponds to TPMS_NV_DIGEST_CERTIFY_INFO.
12 | #[derive(Debug, Clone)]
13 | pub struct NvDigestCertifyInfo {
14 | index_name: Name,
15 | nv_digest: Digest,
16 | }
17 |
18 | impl NvDigestCertifyInfo {
19 | /// Returns the index name
20 | pub const fn index_name(&self) -> &Name {
21 | &self.index_name
22 | }
23 |
24 | /// Returns the NV digest.
25 | pub const fn nv_digest(&self) -> &Digest {
26 | &self.nv_digest
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/attestation/quote_info.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::{
5 | structures::{Digest, PcrSelectionList},
6 | tss2_esys::TPMS_QUOTE_INFO,
7 | Error, Result,
8 | };
9 | use std::convert::{TryFrom, TryInto};
10 | /// Structure holding the attested data for TPM2_Quote()
11 | ///
12 | /// # Details
13 | /// This corresponds to the TPMS_QUOTE_INFO
14 | #[derive(Debug, Clone)]
15 | pub struct QuoteInfo {
16 | pcr_selection: PcrSelectionList,
17 | pcr_digest: Digest,
18 | }
19 |
20 | impl QuoteInfo {
21 | /// Returns the pcr selections list representing the selected PCRs.
22 | pub const fn pcr_selection(&self) -> &PcrSelectionList {
23 | &self.pcr_selection
24 | }
25 |
26 | /// Returns the digest selected PCRs hash of the signing key.
27 | pub const fn pcr_digest(&self) -> &Digest {
28 | &self.pcr_digest
29 | }
30 | }
31 |
32 | impl From for TPMS_QUOTE_INFO {
33 | fn from(quote_info: QuoteInfo) -> Self {
34 | TPMS_QUOTE_INFO {
35 | pcrSelect: quote_info.pcr_selection.into(),
36 | pcrDigest: quote_info.pcr_digest.into(),
37 | }
38 | }
39 | }
40 |
41 | impl TryFrom for QuoteInfo {
42 | type Error = Error;
43 |
44 | fn try_from(tpms_quote_info: TPMS_QUOTE_INFO) -> Result {
45 | Ok(QuoteInfo {
46 | pcr_selection: tpms_quote_info.pcrSelect.try_into()?,
47 | pcr_digest: tpms_quote_info.pcrDigest.try_into()?,
48 | })
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/attestation/session_audit_info.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::{
5 | interface_types::YesNo, structures::Digest, tss2_esys::TPMS_SESSION_AUDIT_INFO, Error, Result,
6 | };
7 | use std::convert::{TryFrom, TryInto};
8 |
9 | /// This type holds the attested data for
10 | /// TPM2_GetSessionAuditDigest()
11 | ///
12 | /// # Details
13 | /// This corresponds to the TPMS_SESSION_AUDIT_INFO.
14 | #[derive(Debug, Clone)]
15 | pub struct SessionAuditInfo {
16 | exclusive_session: YesNo,
17 | session_digest: Digest,
18 | }
19 |
20 | impl SessionAuditInfo {
21 | /// Returns true if if all of the commands recorded in the sessionDigest were
22 | /// executed without any intervening TPM command that did not use
23 | /// this audit session
24 | pub fn exlusive_session(&self) -> bool {
25 | self.exclusive_session.into()
26 | }
27 |
28 | /// Returns the current value of the session audit diges
29 | pub const fn session_digest(&self) -> &Digest {
30 | &self.session_digest
31 | }
32 | }
33 |
34 | impl From for TPMS_SESSION_AUDIT_INFO {
35 | fn from(session_audit_info: SessionAuditInfo) -> Self {
36 | TPMS_SESSION_AUDIT_INFO {
37 | exclusiveSession: session_audit_info.exclusive_session.into(),
38 | sessionDigest: session_audit_info.session_digest.into(),
39 | }
40 | }
41 | }
42 |
43 | impl TryFrom for SessionAuditInfo {
44 | type Error = Error;
45 |
46 | fn try_from(tpms_session_audit_info: TPMS_SESSION_AUDIT_INFO) -> Result {
47 | Ok(SessionAuditInfo {
48 | exclusive_session: tpms_session_audit_info.exclusiveSession.try_into()?,
49 | session_digest: tpms_session_audit_info.sessionDigest.try_into()?,
50 | })
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/attestation/time_attest_info.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::{structures::TimeInfo, tss2_esys::TPMS_TIME_ATTEST_INFO, Error, Result};
5 | use std::convert::{TryFrom, TryInto};
6 |
7 | /// This type is holding attested data for the command TPM2_GetTime
8 | ///
9 | /// # Details
10 | /// This corresponds to the TPMS_TIME_ATTEST_INFO.
11 | #[derive(Debug, Clone, Copy, PartialEq, Eq)]
12 | pub struct TimeAttestInfo {
13 | time_info: TimeInfo,
14 | firmware_version: u64,
15 | }
16 |
17 | impl TimeAttestInfo {
18 | /// Returns the time info
19 | pub const fn time_info(&self) -> &TimeInfo {
20 | &self.time_info
21 | }
22 |
23 | /// Returns the firmware version
24 | pub const fn firmware_version(&self) -> u64 {
25 | self.firmware_version
26 | }
27 | }
28 |
29 | impl From for TPMS_TIME_ATTEST_INFO {
30 | fn from(time_attest_info: TimeAttestInfo) -> Self {
31 | TPMS_TIME_ATTEST_INFO {
32 | time: time_attest_info.time_info.into(),
33 | firmwareVersion: time_attest_info.firmware_version,
34 | }
35 | }
36 | }
37 |
38 | impl TryFrom for TimeAttestInfo {
39 | type Error = Error;
40 |
41 | fn try_from(tpms_time_attest_info: TPMS_TIME_ATTEST_INFO) -> Result {
42 | Ok(TimeAttestInfo {
43 | time_info: tpms_time_attest_info.time.try_into()?,
44 | firmware_version: tpms_time_attest_info.firmwareVersion,
45 | })
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/buffers/private.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2023 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::traits::impl_mu_standard;
5 | use std::mem::size_of;
6 | use tss_esapi_sys::_PRIVATE;
7 |
8 | const TPM2B_PRIVATE_BUFFER_SIZE: usize = size_of::<_PRIVATE>();
9 |
10 | buffer_type!(Private, TPM2B_PRIVATE_BUFFER_SIZE, TPM2B_PRIVATE);
11 |
12 | impl_mu_standard!(Private, TPM2B_PRIVATE);
13 |
14 | cfg_if::cfg_if! {
15 | if #[cfg(feature = "serde")] {
16 | use crate::traits::{Marshall, UnMarshall};
17 | impl serde::Serialize for Private {
18 | /// Serialize the [Private] data into it's bytes representation of the TCG
19 | /// TPM2B_PRIVATE structure.
20 | fn serialize(&self, serializer: S) -> std::result::Result
21 | where
22 | S: serde::Serializer,
23 | {
24 | let bytes = self.marshall().map_err(serde::ser::Error::custom)?;
25 | serializer.serialize_bytes(&bytes)
26 | }
27 | }
28 |
29 | impl<'de> serde::Deserialize<'de> for Private {
30 | /// Deserialize the [Private] data from it's bytes representation of the TCG
31 | /// TPM2B_PRIVATE structure.
32 | fn deserialize(deserializer: D) -> std::result::Result
33 | where
34 | D: serde::Deserializer<'de>,
35 | {
36 | let bytes = >::deserialize(deserializer)?;
37 | Self::unmarshall(&bytes).map_err(serde::de::Error::custom)
38 | }
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/clock/clock_info.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::{interface_types::YesNo, tss2_esys::TPMS_CLOCK_INFO, Error, Result};
5 | use std::convert::TryFrom;
6 |
7 | /// Information related to the internal temporal
8 | /// state of the TPM.
9 | ///
10 | /// # Details
11 | /// Corresponds to `TPMS_CLOCK_INFO`
12 | #[derive(Debug, Clone, Copy, PartialEq, Eq)]
13 | pub struct ClockInfo {
14 | clock: u64,
15 | reset_count: u32,
16 | restart_count: u32,
17 | safe: YesNo,
18 | }
19 |
20 | impl ClockInfo {
21 | /// Returns the clock value
22 | pub const fn clock(&self) -> u64 {
23 | self.clock
24 | }
25 |
26 | /// Returns the reset count value
27 | pub const fn reset_count(&self) -> u32 {
28 | self.reset_count
29 | }
30 |
31 | /// Returns the restart count value
32 | pub const fn restart_count(&self) -> u32 {
33 | self.restart_count
34 | }
35 |
36 | /// Returns safe
37 | pub fn safe(&self) -> bool {
38 | self.safe.into()
39 | }
40 | }
41 |
42 | impl TryFrom for ClockInfo {
43 | type Error = Error;
44 |
45 | fn try_from(tss: TPMS_CLOCK_INFO) -> Result {
46 | Ok(ClockInfo {
47 | clock: tss.clock,
48 | reset_count: tss.resetCount,
49 | restart_count: tss.restartCount,
50 | safe: YesNo::try_from(tss.safe)?,
51 | })
52 | }
53 | }
54 |
55 | impl From for TPMS_CLOCK_INFO {
56 | fn from(native: ClockInfo) -> Self {
57 | TPMS_CLOCK_INFO {
58 | clock: native.clock,
59 | resetCount: native.reset_count,
60 | restartCount: native.restart_count,
61 | safe: native.safe.into(),
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/clock/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | pub mod clock_info;
4 | pub mod time_info;
5 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/clock/time_info.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::{structures::ClockInfo, tss2_esys::TPMS_TIME_INFO, Error, Result};
5 | use std::convert::{TryFrom, TryInto};
6 |
7 | /// Structure holding the attestation for
8 | /// TPM2_GetTime() and TPM2_ReadClock().
9 | ///
10 | /// # Details
11 | /// This corresponds to the TPMS_TIME_INFO
12 | #[derive(Debug, Clone, Copy, PartialEq, Eq)]
13 | pub struct TimeInfo {
14 | time: u64,
15 | clock_info: ClockInfo,
16 | }
17 |
18 | impl TimeInfo {
19 | /// Returns the time
20 | pub const fn time(&self) -> u64 {
21 | self.time
22 | }
23 |
24 | /// Restursn the clock info.
25 | pub const fn clock_info(&self) -> &ClockInfo {
26 | &self.clock_info
27 | }
28 | }
29 |
30 | impl From for TPMS_TIME_INFO {
31 | fn from(time_info: TimeInfo) -> Self {
32 | TPMS_TIME_INFO {
33 | time: time_info.time,
34 | clockInfo: time_info.clock_info.into(),
35 | }
36 | }
37 | }
38 |
39 | impl TryFrom for TimeInfo {
40 | type Error = Error;
41 |
42 | fn try_from(tpms_time_info: TPMS_TIME_INFO) -> Result {
43 | Ok(TimeInfo {
44 | time: tpms_time_info.time,
45 | clock_info: tpms_time_info.clockInfo.try_into()?,
46 | })
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/creation.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::{
5 | attributes::LocalityAttributes,
6 | constants::AlgorithmIdentifier,
7 | interface_types::algorithm::HashingAlgorithm,
8 | structures::{Data, Digest, Name, PcrSelectionList},
9 | tss2_esys::{TPM2B_CREATION_DATA, TPMS_CREATION_DATA},
10 | Error, Result,
11 | };
12 | use std::convert::{TryFrom, TryInto};
13 |
14 | #[derive(Debug, Clone)]
15 | pub struct CreationData {
16 | pcr_select: PcrSelectionList,
17 | pcr_digest: Digest,
18 | locality: LocalityAttributes,
19 | parent_name_alg: Option,
20 | parent_name: Name,
21 | parent_qualified_name: Name,
22 | outside_info: Data,
23 | }
24 |
25 | impl TryFrom for CreationData {
26 | type Error = Error;
27 | fn try_from(tss_creation_data: TPMS_CREATION_DATA) -> Result {
28 | Ok(CreationData {
29 | pcr_select: tss_creation_data.pcrSelect.try_into()?,
30 | pcr_digest: tss_creation_data.pcrDigest.try_into()?,
31 | locality: tss_creation_data.locality.into(),
32 | parent_name_alg: match AlgorithmIdentifier::try_from(tss_creation_data.parentNameAlg)? {
33 | AlgorithmIdentifier::Null => None,
34 | alg => Some(HashingAlgorithm::try_from(alg)?),
35 | },
36 | parent_name: tss_creation_data.parentName.try_into()?,
37 | parent_qualified_name: tss_creation_data.parentQualifiedName.try_into()?,
38 | outside_info: tss_creation_data.outsideInfo.try_into()?,
39 | })
40 | }
41 | }
42 |
43 | impl TryFrom for CreationData {
44 | type Error = Error;
45 | fn try_from(tss_creation_data_buffer: TPM2B_CREATION_DATA) -> Result {
46 | CreationData::try_from(tss_creation_data_buffer.creationData)
47 | }
48 | }
49 |
50 | impl From for TPMS_CREATION_DATA {
51 | fn from(creation_data: CreationData) -> Self {
52 | TPMS_CREATION_DATA {
53 | pcrSelect: creation_data.pcr_select.into(),
54 | pcrDigest: creation_data.pcr_digest.into(),
55 | locality: creation_data.locality.into(),
56 | parentNameAlg: match creation_data.parent_name_alg {
57 | None => AlgorithmIdentifier::Null.into(),
58 | Some(alg) => alg.into(),
59 | },
60 | parentName: creation_data.parent_name.into(),
61 | parentQualifiedName: creation_data.parent_qualified_name.into(),
62 | outsideInfo: creation_data.outside_info.into(),
63 | }
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/ecc/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | pub mod point;
4 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/ecc/point.rs:
--------------------------------------------------------------------------------
1 | use tss_esapi_sys::TPM2B_ECC_POINT;
2 |
3 | // Copyright 2021 Contributors to the Parsec project.
4 | // SPDX-License-Identifier: Apache-2.0
5 | use crate::{structures::EccParameter, tss2_esys::TPMS_ECC_POINT, Error, Result};
6 | use std::{
7 | convert::{TryFrom, TryInto},
8 | mem::size_of,
9 | };
10 |
11 | /// Structure holding ecc point information
12 | ///
13 | /// # Details
14 | /// This corresponds to TPMS_ECC_POINT
15 | #[derive(Debug, Clone, PartialEq, Eq)]
16 | pub struct EccPoint {
17 | x: EccParameter,
18 | y: EccParameter,
19 | }
20 |
21 | impl EccPoint {
22 | /// Creates a new ecc point
23 | pub const fn new(x: EccParameter, y: EccParameter) -> Self {
24 | EccPoint { x, y }
25 | }
26 |
27 | /// Returns x value as an [EccParameter] reference.
28 | pub const fn x(&self) -> &EccParameter {
29 | &self.x
30 | }
31 |
32 | /// Returns y value as an [EccParameter] reference.
33 | pub const fn y(&self) -> &EccParameter {
34 | &self.y
35 | }
36 | }
37 |
38 | impl Default for EccPoint {
39 | fn default() -> Self {
40 | EccPoint::new(EccParameter::default(), EccParameter::default())
41 | }
42 | }
43 |
44 | impl From for TPMS_ECC_POINT {
45 | fn from(ecc_point: EccPoint) -> Self {
46 | TPMS_ECC_POINT {
47 | x: ecc_point.x.into(),
48 | y: ecc_point.y.into(),
49 | }
50 | }
51 | }
52 |
53 | impl From for TPM2B_ECC_POINT {
54 | fn from(ecc_point: EccPoint) -> Self {
55 | let size = size_of::() + ecc_point.x().len() + size_of::() + ecc_point.y().len();
56 | TPM2B_ECC_POINT {
57 | size: size as u16,
58 | point: ecc_point.into(),
59 | }
60 | }
61 | }
62 |
63 | impl TryFrom for EccPoint {
64 | type Error = Error;
65 |
66 | fn try_from(tpms_ecc_point: TPMS_ECC_POINT) -> Result {
67 | Ok(EccPoint {
68 | x: tpms_ecc_point.x.try_into()?,
69 | y: tpms_ecc_point.y.try_into()?,
70 | })
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/hash/agile.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::interface_types::algorithm::HashingAlgorithm;
4 | use crate::structures::Digest;
5 | use crate::tss2_esys::{TPMT_HA, TPMU_HA};
6 | use crate::{Error, Result, WrapperErrorKind};
7 | use std::convert::{TryFrom, TryInto};
8 |
9 | #[derive(Debug, Clone, PartialEq, Eq)]
10 | pub struct HashAgile {
11 | algorithm: HashingAlgorithm,
12 | digest: Digest,
13 | }
14 |
15 | impl HashAgile {
16 | pub fn new(algorithm: HashingAlgorithm, digest: Digest) -> Self {
17 | HashAgile { algorithm, digest }
18 | }
19 | }
20 |
21 | impl TryFrom for TPMT_HA {
22 | type Error = Error;
23 | fn try_from(ha: HashAgile) -> Result {
24 | let algid: crate::tss2_esys::TPM2_ALG_ID = ha.algorithm.into();
25 | let digest_val = ha.digest;
26 | Ok(TPMT_HA {
27 | hashAlg: algid,
28 | digest: match ha.algorithm {
29 | HashingAlgorithm::Sha1 => TPMU_HA {
30 | sha1: digest_val.try_into()?,
31 | },
32 | HashingAlgorithm::Sha256 => TPMU_HA {
33 | sha256: digest_val.try_into()?,
34 | },
35 | HashingAlgorithm::Sha384 => TPMU_HA {
36 | sha384: digest_val.try_into()?,
37 | },
38 | HashingAlgorithm::Sha512 => TPMU_HA {
39 | sha512: digest_val.try_into()?,
40 | },
41 | HashingAlgorithm::Sm3_256 => TPMU_HA {
42 | sm3_256: digest_val.try_into()?,
43 | },
44 | _ => return Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
45 | },
46 | })
47 | }
48 | }
49 |
50 | impl TryFrom for HashAgile {
51 | type Error = Error;
52 |
53 | fn try_from(tpmt_ha: TPMT_HA) -> Result {
54 | let algorithm = HashingAlgorithm::try_from(tpmt_ha.hashAlg)?;
55 | Ok(HashAgile {
56 | algorithm,
57 | digest: match algorithm {
58 | HashingAlgorithm::Sha1 => unsafe { tpmt_ha.digest.sha1 }.into(),
59 | HashingAlgorithm::Sha256 => unsafe { tpmt_ha.digest.sha256 }.into(),
60 | HashingAlgorithm::Sha384 => unsafe { tpmt_ha.digest.sha384 }.into(),
61 | HashingAlgorithm::Sha512 => unsafe { tpmt_ha.digest.sha512 }.into(),
62 | HashingAlgorithm::Sm3_256 => unsafe { tpmt_ha.digest.sm3_256 }.into(),
63 | _ => return Err(Error::local_error(WrapperErrorKind::WrongValueFromTpm)),
64 | },
65 | })
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/hash/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | pub mod agile;
4 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/lists/digest_values.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::interface_types::algorithm::HashingAlgorithm;
4 | use crate::structures::Digest;
5 | use crate::structures::HashAgile;
6 | use crate::tss2_esys::TPML_DIGEST_VALUES;
7 | use crate::{Error, Result};
8 | use std::collections::HashMap;
9 | use std::convert::{TryFrom, TryInto};
10 |
11 | #[derive(Debug, Clone, Default)]
12 | pub struct DigestValues {
13 | digests: HashMap,
14 | }
15 |
16 | impl DigestValues {
17 | pub fn new() -> Self {
18 | DigestValues {
19 | digests: HashMap::new(),
20 | }
21 | }
22 |
23 | pub fn set(&mut self, alg: HashingAlgorithm, dig: Digest) {
24 | let _ = self.digests.insert(alg, dig);
25 | }
26 | }
27 |
28 | impl TryFrom for TPML_DIGEST_VALUES {
29 | type Error = Error;
30 | fn try_from(digest_values: DigestValues) -> Result {
31 | let mut digest_values = digest_values;
32 | let mut tss_digest_values: TPML_DIGEST_VALUES = Default::default();
33 | for (digest_hash, digest_val) in digest_values.digests.drain() {
34 | let ha = HashAgile::new(digest_hash, digest_val);
35 | tss_digest_values.digests[tss_digest_values.count as usize] = ha.try_into()?;
36 | tss_digest_values.count += 1;
37 | }
38 | Ok(tss_digest_values)
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/lists/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | pub mod algorithm_property;
4 | pub mod command_code;
5 | pub mod command_code_attributes;
6 | pub mod digest;
7 | pub mod digest_values;
8 | pub mod ecc_curves;
9 | pub mod handles;
10 | pub mod pcr_selection;
11 | pub mod tagged_pcr_property;
12 | pub mod tagged_tpm_property;
13 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/names/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | pub mod name;
4 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/names/name.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::tss2_esys::TPM2B_NAME;
4 | use crate::{Error, Result, WrapperErrorKind};
5 | use log::error;
6 | use std::convert::TryFrom;
7 | /// Structure holding the data representing names
8 | #[allow(missing_copy_implementations)]
9 | #[derive(Debug, Clone)]
10 | pub struct Name {
11 | value: TPM2B_NAME,
12 | }
13 |
14 | impl Name {
15 | const MAX_SIZE: usize = 68;
16 | pub fn value(&self) -> &[u8] {
17 | &self.value.name[..self.value.size as usize]
18 | }
19 | }
20 |
21 | impl PartialEq for Name {
22 | fn eq(&self, other: &Self) -> bool {
23 | self.value() == other.value()
24 | }
25 | }
26 |
27 | impl Eq for Name {}
28 |
29 | impl TryFrom> for Name {
30 | type Error = Error;
31 | fn try_from(bytes: Vec) -> Result {
32 | if bytes.len() > Name::MAX_SIZE {
33 | error!("Invalid Vec size(> {})", Name::MAX_SIZE);
34 | return Err(Error::local_error(WrapperErrorKind::WrongParamSize));
35 | }
36 | let size = bytes.len() as u16;
37 | let mut name = [0; Name::MAX_SIZE];
38 | name[..bytes.len()].copy_from_slice(&bytes);
39 | Ok(Name {
40 | value: TPM2B_NAME { size, name },
41 | })
42 | }
43 | }
44 |
45 | impl TryFrom for Name {
46 | type Error = Error;
47 | fn try_from(tss_name: TPM2B_NAME) -> Result {
48 | let size = tss_name.size as usize;
49 | if size > Name::MAX_SIZE {
50 | error!("Invalid TPM2B_NAME size(> {})", Name::MAX_SIZE);
51 | return Err(Error::local_error(WrapperErrorKind::InvalidParam));
52 | }
53 | Ok(Name { value: tss_name })
54 | }
55 | }
56 |
57 | impl From for TPM2B_NAME {
58 | fn from(name: Name) -> Self {
59 | name.value
60 | }
61 | }
62 |
63 | impl AsRef for Name {
64 | fn as_ref(&self) -> &TPM2B_NAME {
65 | &self.value
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/nv/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | //! This module contains code that deals with the non volatile
5 | //! parts of the tpm.
6 |
7 | /// Non volatile storage module.
8 | pub mod storage;
9 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/nv/storage/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | /// This module contains code that deaals with non volatile storage
5 | /// in the TPM.
6 | ///
7 | mod public;
8 |
9 | pub use public::{NvPublic, NvPublicBuilder};
10 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/parameters.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::{
5 | structures::SymmetricDefinitionObject, tss2_esys::TPMS_SYMCIPHER_PARMS, Error, Result,
6 | };
7 |
8 | use std::convert::{TryFrom, TryInto};
9 |
10 | /// Symmetric cipher parameters
11 | ///
12 | /// # Details
13 | /// Corresponds to TPMS_SYMCIPHER_PARMS
14 | #[derive(Clone, Debug, Copy, PartialEq, Eq)]
15 | pub struct SymmetricCipherParameters {
16 | symmetric_definition_object: SymmetricDefinitionObject,
17 | }
18 |
19 | impl SymmetricCipherParameters {
20 | /// Creates a new [SymmetricDefinitionObject]
21 | pub const fn new(
22 | symmetric_definition_object: SymmetricDefinitionObject,
23 | ) -> SymmetricCipherParameters {
24 | SymmetricCipherParameters {
25 | symmetric_definition_object,
26 | }
27 | }
28 |
29 | /// Returns the [SymmetricDefinitionObject].
30 | pub const fn symmetric_definition_object(&self) -> SymmetricDefinitionObject {
31 | self.symmetric_definition_object
32 | }
33 | }
34 |
35 | impl TryFrom for SymmetricCipherParameters {
36 | type Error = Error;
37 | fn try_from(tpms_symcipher_params: TPMS_SYMCIPHER_PARMS) -> Result {
38 | Ok(SymmetricCipherParameters {
39 | symmetric_definition_object: tpms_symcipher_params.sym.try_into()?,
40 | })
41 | }
42 | }
43 |
44 | impl From for TPMS_SYMCIPHER_PARMS {
45 | fn from(symmetric_cipher_parameters: SymmetricCipherParameters) -> TPMS_SYMCIPHER_PARMS {
46 | TPMS_SYMCIPHER_PARMS {
47 | sym: symmetric_cipher_parameters
48 | .symmetric_definition_object
49 | .into(),
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/pcr/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | pub mod select;
4 | pub mod select_size;
5 | pub mod selection;
6 | pub mod slot;
7 | pub mod slot_collection;
8 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/pcr/select.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::{
4 | structures::{PcrSelectSize, PcrSlot, PcrSlotCollection},
5 | tss2_esys::TPMS_PCR_SELECT,
6 | Error, Result,
7 | };
8 |
9 | use std::convert::TryFrom;
10 | /// This module contains necessary representations
11 | /// of the items belonging to the TPMS_PCR_SELECT
12 | /// structure.
13 | ///
14 | /// The minimum number of octets allowed in a TPMS_PCR_SELECT.sizeOfSelect
15 | /// is not determined by the number of PCR implemented but by the
16 | /// number of PCR required by the platform-specific
17 | /// specification with which the TPM is compliant or by the implementer if
18 | /// not adhering to a platform-specific specification.
19 | #[derive(Debug, Copy, Clone, PartialEq, Eq)]
20 | pub struct PcrSelect {
21 | pcr_slot_collection: PcrSlotCollection,
22 | }
23 |
24 | impl PcrSelect {
25 | /// Creates a new PcrSelect
26 | pub fn create(pcr_select_size: PcrSelectSize, pcr_slots: &[PcrSlot]) -> Result {
27 | PcrSlotCollection::create(pcr_select_size, pcr_slots).map(|pcr_slot_collection| PcrSelect {
28 | pcr_slot_collection,
29 | })
30 | }
31 |
32 | /// Returns the size of the select.
33 | ///
34 | /// NB! This is not the same as how many [PcrSlot]
35 | /// there are in the select but rather how many
36 | /// octets that are needed to hold the bit field
37 | /// that indicate what slots that are selected.
38 | pub fn size_of_select(&self) -> PcrSelectSize {
39 | self.pcr_slot_collection.size_of_select()
40 | }
41 |
42 | /// Returns the selected PCRs in the select.
43 | pub fn selected_pcrs(&self) -> Vec {
44 | self.pcr_slot_collection.collection()
45 | }
46 | }
47 |
48 | impl TryFrom for PcrSelect {
49 | type Error = Error;
50 | fn try_from(tss_pcr_select: TPMS_PCR_SELECT) -> Result {
51 | PcrSlotCollection::try_from((tss_pcr_select.sizeofSelect, tss_pcr_select.pcrSelect)).map(
52 | |pcr_slot_collection| PcrSelect {
53 | pcr_slot_collection,
54 | },
55 | )
56 | }
57 | }
58 |
59 | impl From for TPMS_PCR_SELECT {
60 | fn from(pcr_select: PcrSelect) -> Self {
61 | let (size_of_select, pcr_select) = pcr_select.pcr_slot_collection.into();
62 | TPMS_PCR_SELECT {
63 | sizeofSelect: size_of_select,
64 | pcrSelect: pcr_select,
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/pcr/slot.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::{tss2_esys::TPM2_PCR_SELECT_MAX, Error, Result, WrapperErrorKind};
4 | use enumflags2::bitflags;
5 | use log::error;
6 | use num_derive::{FromPrimitive, ToPrimitive};
7 | use num_traits::{FromPrimitive, ToPrimitive};
8 | use std::convert::TryFrom;
9 |
10 | /// Enum with the bit flag for each PCR slot.
11 | #[bitflags]
12 | #[repr(u32)]
13 | #[derive(FromPrimitive, ToPrimitive, Hash, Debug, Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
14 | pub enum PcrSlot {
15 | Slot0 = 0x0000_0001,
16 | Slot1 = 0x0000_0002,
17 | Slot2 = 0x0000_0004,
18 | Slot3 = 0x0000_0008,
19 | Slot4 = 0x0000_0010,
20 | Slot5 = 0x0000_0020,
21 | Slot6 = 0x0000_0040,
22 | Slot7 = 0x0000_0080,
23 | Slot8 = 0x0000_0100,
24 | Slot9 = 0x0000_0200,
25 | Slot10 = 0x0000_0400,
26 | Slot11 = 0x0000_0800,
27 | Slot12 = 0x0000_1000,
28 | Slot13 = 0x0000_2000,
29 | Slot14 = 0x0000_4000,
30 | Slot15 = 0x0000_8000,
31 | Slot16 = 0x0001_0000,
32 | Slot17 = 0x0002_0000,
33 | Slot18 = 0x0004_0000,
34 | Slot19 = 0x0008_0000,
35 | Slot20 = 0x0010_0000,
36 | Slot21 = 0x0020_0000,
37 | Slot22 = 0x0040_0000,
38 | Slot23 = 0x0080_0000,
39 | Slot24 = 0x0100_0000,
40 | Slot25 = 0x0200_0000,
41 | Slot26 = 0x0400_0000,
42 | Slot27 = 0x0800_0000,
43 | Slot28 = 0x1000_0000,
44 | Slot29 = 0x2000_0000,
45 | Slot30 = 0x4000_0000,
46 | Slot31 = 0x8000_0000,
47 | }
48 |
49 | impl From for u32 {
50 | fn from(pcr_slot: PcrSlot) -> u32 {
51 | pcr_slot.to_u32().unwrap()
52 | }
53 | }
54 |
55 | impl TryFrom for PcrSlot {
56 | type Error = Error;
57 |
58 | fn try_from(value: u32) -> Result {
59 | PcrSlot::from_u32(value).ok_or_else(|| {
60 | error!("{} is not valid PcrSlot value", value);
61 | Error::local_error(WrapperErrorKind::InvalidParam)
62 | })
63 | }
64 | }
65 |
66 | impl From for [u8; TPM2_PCR_SELECT_MAX as usize] {
67 | fn from(pcr_slot: PcrSlot) -> [u8; TPM2_PCR_SELECT_MAX as usize] {
68 | u32::from(pcr_slot).to_le_bytes()
69 | }
70 | }
71 |
72 | impl TryFrom<[u8; TPM2_PCR_SELECT_MAX as usize]> for PcrSlot {
73 | type Error = Error;
74 |
75 | fn try_from(tss_pcr_slot: [u8; TPM2_PCR_SELECT_MAX as usize]) -> Result {
76 | PcrSlot::try_from(u32::from_le_bytes(tss_pcr_slot))
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/property/algorithm_property.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::{
5 | attributes::AlgorithmAttributes, constants::AlgorithmIdentifier, tss2_esys::TPMS_ALG_PROPERTY,
6 | Error, Result,
7 | };
8 | use std::convert::{TryFrom, TryInto};
9 |
10 | /// Structure for holding information describing an
11 | /// algorithm.
12 | ///
13 | /// # Details
14 | /// This corresponds to the TPMS_ALG_PROPERTY
15 | /// structure.
16 | #[derive(Copy, Clone, Debug, PartialEq, Eq)]
17 | pub struct AlgorithmProperty {
18 | algorithm_identifier: AlgorithmIdentifier,
19 | algorithm_properties: AlgorithmAttributes,
20 | }
21 |
22 | impl AlgorithmProperty {
23 | /// Creates a new AlgorithmProperty with the
24 | /// given parameters.
25 | pub const fn new(
26 | algorithm_identifier: AlgorithmIdentifier,
27 | algorithm_properties: AlgorithmAttributes,
28 | ) -> Self {
29 | AlgorithmProperty {
30 | algorithm_identifier,
31 | algorithm_properties,
32 | }
33 | }
34 |
35 | /// Returns the algorithm identifier
36 | pub const fn algorithm_identifier(&self) -> AlgorithmIdentifier {
37 | self.algorithm_identifier
38 | }
39 |
40 | /// Returns the algorithm properties
41 | pub const fn algorithm_properties(&self) -> AlgorithmAttributes {
42 | self.algorithm_properties
43 | }
44 | }
45 |
46 | impl TryFrom for AlgorithmProperty {
47 | type Error = Error;
48 |
49 | fn try_from(tpms_algorithm_description: TPMS_ALG_PROPERTY) -> Result {
50 | Ok(AlgorithmProperty {
51 | algorithm_identifier: tpms_algorithm_description.alg.try_into()?,
52 | algorithm_properties: tpms_algorithm_description.algProperties.into(),
53 | })
54 | }
55 | }
56 |
57 | impl From for TPMS_ALG_PROPERTY {
58 | fn from(algorithm_description: AlgorithmProperty) -> Self {
59 | TPMS_ALG_PROPERTY {
60 | alg: algorithm_description.algorithm_identifier.into(),
61 | algProperties: algorithm_description.algorithm_properties.into(),
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/property/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | pub mod algorithm_property;
4 | pub mod tagged_pcr_select;
5 | pub mod tagged_property;
6 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/property/tagged_property.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::{constants::PropertyTag, tss2_esys::TPMS_TAGGED_PROPERTY, Error, Result};
5 | use std::convert::TryFrom;
6 |
7 | /// Struct representing a tagged property
8 | ///
9 | /// # Details
10 | /// This corresponds to TPMS_TAGGED_PROPERTY
11 | #[derive(Debug, Clone, Copy, Eq, PartialEq)]
12 | pub struct TaggedProperty {
13 | property: PropertyTag,
14 | value: u32,
15 | }
16 |
17 | impl TaggedProperty {
18 | /// Creates a new TaggedProperty
19 | pub const fn new(property: PropertyTag, value: u32) -> Self {
20 | TaggedProperty { property, value }
21 | }
22 |
23 | /// Returns the property tag
24 | pub const fn property(&self) -> PropertyTag {
25 | self.property
26 | }
27 |
28 | /// Returns the value
29 | pub const fn value(&self) -> u32 {
30 | self.value
31 | }
32 | }
33 |
34 | impl TryFrom for TaggedProperty {
35 | type Error = Error;
36 |
37 | fn try_from(tpms_tagged_property: TPMS_TAGGED_PROPERTY) -> Result {
38 | let value = tpms_tagged_property.value;
39 | PropertyTag::try_from(tpms_tagged_property.property)
40 | .map(|property| TaggedProperty { property, value })
41 | }
42 | }
43 |
44 | impl From for TPMS_TAGGED_PROPERTY {
45 | fn from(tagged_property: TaggedProperty) -> Self {
46 | TPMS_TAGGED_PROPERTY {
47 | property: tagged_property.property.into(),
48 | value: tagged_property.value,
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/result.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use crate::{
5 | handles::KeyHandle,
6 | structures::{CreationData, CreationTicket, Digest, Private, Public},
7 | };
8 |
9 | #[allow(missing_debug_implementations)]
10 | pub struct CreateKeyResult {
11 | pub out_private: Private,
12 | pub out_public: Public,
13 | pub creation_data: CreationData,
14 | pub creation_hash: Digest,
15 | pub creation_ticket: CreationTicket,
16 | }
17 |
18 | #[allow(missing_debug_implementations)]
19 | pub struct CreatePrimaryKeyResult {
20 | pub key_handle: KeyHandle,
21 | pub out_public: Public,
22 | pub creation_data: CreationData,
23 | pub creation_hash: Digest,
24 | pub creation_ticket: CreationTicket,
25 | }
26 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/tagged/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | pub mod parameters;
4 | pub mod public;
5 | pub mod schemes;
6 | pub mod sensitive;
7 | pub mod signature;
8 | pub mod symmetric;
9 |
--------------------------------------------------------------------------------
/tss-esapi/src/structures/tagged/public/keyed_hash.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use crate::{structures::KeyedHashScheme, tss2_esys::TPMS_KEYEDHASH_PARMS, Error, Result};
4 | use std::convert::{TryFrom, TryInto};
5 |
6 | /// Keyed hash parameters
7 | ///
8 | /// # Details
9 | /// Corresponds to TPMS_KEYEDHASH_PARMS
10 | ///
11 | /// These keyed hash parameters are specific to the [`crate::structures::Public`] type.
12 | #[derive(Clone, Copy, Debug, PartialEq, Eq)]
13 | pub struct PublicKeyedHashParameters {
14 | keyed_hash_scheme: KeyedHashScheme,
15 | }
16 |
17 | impl PublicKeyedHashParameters {
18 | pub const fn new(keyed_hash_scheme: KeyedHashScheme) -> PublicKeyedHashParameters {
19 | PublicKeyedHashParameters { keyed_hash_scheme }
20 | }
21 | }
22 |
23 | impl TryFrom for PublicKeyedHashParameters {
24 | type Error = Error;
25 |
26 | fn try_from(tpms_keyed_hash_parms: TPMS_KEYEDHASH_PARMS) -> Result {
27 | Ok(PublicKeyedHashParameters {
28 | keyed_hash_scheme: tpms_keyed_hash_parms.scheme.try_into()?,
29 | })
30 | }
31 | }
32 |
33 | impl From for TPMS_KEYEDHASH_PARMS {
34 | fn from(public_keyed_hash_prams: PublicKeyedHashParameters) -> Self {
35 | TPMS_KEYEDHASH_PARMS {
36 | scheme: public_keyed_hash_prams.keyed_hash_scheme.into(),
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/tss-esapi/tests/Dockerfile-fedora:
--------------------------------------------------------------------------------
1 | FROM fedora:38
2 |
3 | RUN dnf install -y \
4 | tpm2-tss-devel tpm2-abrmd tpm2-tools \
5 | swtpm swtpm-tools \
6 | rust clippy cargo \
7 | llvm llvm-devel clang pkg-config \
8 | dbus-daemon
9 |
--------------------------------------------------------------------------------
/tss-esapi/tests/Dockerfile-fedora-rawhide:
--------------------------------------------------------------------------------
1 | FROM fedora:rawhide
2 |
3 | RUN dnf install -y \
4 | tpm2-tss-devel tpm2-abrmd tpm2-tools \
5 | swtpm swtpm-tools swtpm-selinux\
6 | rust clippy cargo \
7 | llvm llvm-devel clang pkg-config \
8 | dbus-daemon rust-gobject-sys-devel
9 |
--------------------------------------------------------------------------------
/tss-esapi/tests/Dockerfile-opensuse-tw:
--------------------------------------------------------------------------------
1 | # USAGE:
2 | # docker build -t tssdev -f ./tss-esapi/tests/Dockerfile-opensuse-tw .
3 | # docker run -v ./:/usr/src/rust-tss-esapi --rm -i -t tssdev
4 | #
5 | # It is a good idea to vendor to prevent repeat crate downloads.
6 | # mkdir .cargo
7 | # cargo vendor > .cargo/config.toml
8 |
9 | FROM opensuse/tumbleweed:latest
10 |
11 | RUN zypper install -y \
12 | tpm2-0-tss-devel tpm2.0-tools tpm2.0-abrmd \
13 | swtpm \
14 | cargo \
15 | clang \
16 | dbus-1-daemon
17 |
18 | # Instead of bind mounting, we could do this instead.
19 | # COPY . /usr/src/rust-tss-esapi
20 |
21 | WORKDIR /usr/src/rust-tss-esapi
22 |
23 | CMD ["/usr/bin/bash", "tss-esapi/tests/all-opensuse.sh"]
24 |
--------------------------------------------------------------------------------
/tss-esapi/tests/Dockerfile-ubuntu:
--------------------------------------------------------------------------------
1 | FROM ghcr.io/tpm2-software/ubuntu-20.04:latest AS base
2 |
3 | FROM base AS rust-toolchain
4 | # Install Rust toolchain
5 | RUN (curl https://sh.rustup.rs -sSf || exit 1) | bash -s -- -y
6 | ENV PATH="/root/.cargo/bin:${PATH}"
7 |
8 | FROM rust-toolchain AS tpm2-tss
9 | # Download and install the TSS library
10 | ENV TPM2_TSS_BINDINGS_VERSION=4.0.1
11 | ARG TPM2_TSS_VERSION=$TPM2_TSS_BINDINGS_VERSION
12 | ENV TPM2_TSS_VERSION=$TPM2_TSS_VERSION
13 | ENV PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
14 |
15 | RUN git clone https://github.com/tpm2-software/tpm2-tss.git --branch $TPM2_TSS_VERSION
16 | RUN cd tpm2-tss \
17 | && ./bootstrap \
18 | && ./configure \
19 | && make -j$(nproc) \
20 | && make install \
21 | && ldconfig
22 |
23 | FROM tpm2-tss AS tpm2-tools
24 | # Download and install TPM2 tools
25 | RUN git clone https://github.com/tpm2-software/tpm2-tools.git --branch 5.6
26 | RUN cd tpm2-tools \
27 | && ./bootstrap \
28 | && ./configure \
29 | && make install
30 |
31 | FROM tpm2-tools AS tpm2-tss-install-dir
32 | # TPM2_TSS_PATH is the env variable build.rs looks for
33 | # an installation.
34 | ENV TPM2_TSS_PATH=/tpm2-tss-install-dir
35 | RUN mkdir -p /tpm2-tss-install-dir/lib /tpm2-tss-install-dir/include
36 | COPY --from=tpm2-tss tpm2-tss/src/tss2-*/.libs/libtss2-*.so /tpm2-tss-install-dir/lib/
37 | COPY --from=tpm2-tss tpm2-tss/include/ /tpm2-tss-install-dir/include/
38 | COPY --from=tpm2-tss tpm2-tss/VERSION /tpm2-tss-install-dir/
--------------------------------------------------------------------------------
/tss-esapi/tests/all-fedora.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2019 Contributors to the Parsec project.
4 | # SPDX-License-Identifier: Apache-2.0
5 |
6 | # This script executes tests for the tss-esapi crate.
7 | # It can be run inside the container which Dockerfile is in the same folder.
8 | #
9 | # Usage: ./tests/all.sh
10 |
11 | set -euf -o pipefail
12 |
13 | if [[ ! -z ${USE_FROZEN_LOCKFILE:+x} ]]; then
14 | # Some versions of Fedora that are used during testing are old
15 | # so in order to prevent any drift from the versions available
16 | # in the old versions the frozen Cargo lock is used.
17 | cp tests/Cargo.lock.frozen ../Cargo.lock
18 | fi
19 |
20 | ############################
21 | # Run the TPM SWTPM server #
22 | ############################
23 | mkdir /tmp/tpmdir
24 | swtpm_setup --tpm2 \
25 | --tpmstate /tmp/tpmdir \
26 | --createek --decryption --create-ek-cert \
27 | --create-platform-cert \
28 | --pcr-banks sha1,sha256 \
29 | --display
30 | swtpm socket --tpm2 \
31 | --tpmstate dir=/tmp/tpmdir \
32 | --flags startup-clear \
33 | --ctrl type=tcp,port=2322 \
34 | --server type=tcp,port=2321 \
35 | --daemon
36 | tpm2-abrmd \
37 | --logger=stdout \
38 | --tcti=swtpm: \
39 | --allow-root \
40 | --session \
41 | --flush-all &
42 |
43 | ###################
44 | # Build the crate #
45 | ###################
46 | RUST_BACKTRACE=1 cargo build --features "generate-bindings integration-tests serde"
47 |
48 | #################
49 | # Run the tests #
50 | #################
51 | TEST_TCTI=tabrmd:bus_type=session RUST_BACKTRACE=1 RUST_LOG=info cargo test --features "generate-bindings integration-tests serde" -- --test-threads=1 --nocapture
52 |
--------------------------------------------------------------------------------
/tss-esapi/tests/all-opensuse.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2024 Contributors to the Parsec project.
4 | # SPDX-License-Identifier: Apache-2.0
5 |
6 | # This script executes tests for the tss-esapi crate.
7 | # It can be run inside the container which Dockerfile is in the same folder.
8 | #
9 | # Usage: ./tests/all.sh
10 |
11 | set -euf -o pipefail
12 |
13 | ############################
14 | # Run the TPM SWTPM server #
15 | ############################
16 | mkdir /tmp/tpmdir
17 | swtpm_setup --tpm2 \
18 | --tpmstate /tmp/tpmdir \
19 | --createek --decryption --create-ek-cert \
20 | --create-platform-cert \
21 | --pcr-banks sha1,sha256 \
22 | --display
23 | swtpm socket --tpm2 \
24 | --tpmstate dir=/tmp/tpmdir \
25 | --flags startup-clear \
26 | --ctrl type=tcp,port=2322 \
27 | --server type=tcp,port=2321 \
28 | --daemon
29 |
30 | ###################
31 | # Build the crate #
32 | ###################
33 | RUST_BACKTRACE=1 cargo build --features "generate-bindings integration-tests serde"
34 |
35 | #################
36 | # Run the tests #
37 | #################
38 | TEST_TCTI="swtpm:host=localhost,port=2321" RUST_BACKTRACE=1 RUST_LOG=info cargo test --features "generate-bindings integration-tests serde" -- --test-threads=1 --nocapture
39 |
40 |
--------------------------------------------------------------------------------
/tss-esapi/tests/all-ubuntu.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2019 Contributors to the Parsec project.
4 | # SPDX-License-Identifier: Apache-2.0
5 |
6 | # This script executes tests for the tss-esapi crate.
7 | # It can be run inside the container which Dockerfile is in the same folder.
8 | #
9 | # Usage: ./tests/all.sh
10 |
11 | set -euf -o pipefail
12 |
13 | #################################################
14 | # Change rust toolchain version
15 | #################################################
16 | if [[ ! -z ${RUST_TOOLCHAIN_VERSION:+x} ]]; then
17 | rustup override set ${RUST_TOOLCHAIN_VERSION}
18 | # Use the frozen Cargo lock to prevent any drift from MSRV being upgraded
19 | # underneath our feet.
20 | cp tests/Cargo.lock.frozen ../Cargo.lock
21 | fi
22 |
23 | #################################################
24 | # Generate bindings for non-"standard" versions #
25 | #################################################
26 | if [[ "${TPM2_TSS_VERSION}" != "${TPM2_TSS_BINDINGS_VERSION}" ]]; then
27 | FEATURES="generate-bindings integration-tests serde"
28 | else
29 | FEATURES="integration-tests serde"
30 | fi
31 |
32 | if [[ ! -z ${TPM2_TSS_PATH:+x} ]]; then
33 | export LD_LIBRARY_PATH="${TPM2_TSS_PATH}"
34 | fi
35 | #################################
36 | # Run the TPM simulation server #
37 | #################################
38 | tpm_server &
39 | sleep 5
40 | tpm2_startup -c -T mssim
41 |
42 | ###################
43 | # Build the crate #
44 | ###################
45 | RUST_BACKTRACE=1 cargo build --features "$FEATURES"
46 |
47 | #################
48 | # Run the tests #
49 | #################
50 | TEST_TCTI=mssim: RUST_BACKTRACE=1 RUST_LOG=info cargo test --features "${FEATURES}" -- --test-threads=1 --nocapture
51 |
--------------------------------------------------------------------------------
/tss-esapi/tests/coverage.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2021 Contributors to the Parsec project.
4 | # SPDX-License-Identifier: Apache-2.0
5 |
6 | set -euf -o pipefail
7 |
8 | #################################
9 | # Run the TPM simulation server #
10 | #################################
11 | tpm_server &
12 | sleep 5
13 | tpm2_startup -c -T mssim
14 |
15 | #############################
16 | # Install and run tarpaulin #
17 | #############################
18 | cargo install cargo-tarpaulin
19 | cargo tarpaulin --features "integration-tests serde" --tests --out xml --exclude-files="tests/*,../*" -- --test-threads=1 --nocapture
20 |
--------------------------------------------------------------------------------
/tss-esapi/tests/create_frozen_cargo_lock:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2024 Contributors to the Parsec project.
4 | # SPDX-License-Identifier: Apache-2.0
5 |
6 | export MSRV=1.74.0
7 | export EXEC_DIR="tss-esapi"
8 |
9 | if [[ "$(basename `pwd`)" != "$EXEC_DIR" ]]; then
10 | echo "Script should be run from ./$EXEC_DIR ."
11 | exit 1
12 | fi
13 |
14 | rustup toolchain install $MSRV
15 | cargo +$MSRV build
16 | cp ../Cargo.lock tests/Cargo.lock.frozen
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/abstraction_tests/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod ak_tests;
4 | mod ek_tests;
5 | mod no_tpm;
6 | mod nv_tests;
7 | mod pcr_data_tests;
8 | mod pcr_tests;
9 | mod public_tests;
10 | mod transient_key_context_tests;
11 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/abstraction_tests/no_tpm/mod.rs:
--------------------------------------------------------------------------------
1 | mod quote_test;
2 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/attributes_tests/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod algorithm_attributes_tests;
4 | mod command_code_attributes_tests;
5 | mod locality_attributes_tests;
6 | mod nv_index_attributes_tests;
7 | mod session_attributes_tests;
8 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/common/marshall.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use tss_esapi::traits::{Marshall, UnMarshall};
4 |
5 | pub fn check_marshall_unmarshall(val: &T) {
6 | let buf = val.marshall().expect("Failed to marshall value");
7 |
8 | let unmarshalled = T::unmarshall(&buf).expect("Failed to unmarshall");
9 |
10 | assert_eq!(val, &unmarshalled);
11 | }
12 |
13 | pub fn check_marshall_unmarshall_offset(val: &T) {
14 | let buf = val.marshall().expect("Failed to marshall value");
15 | let len = buf.len();
16 |
17 | let mut buf = vec![0xff; 1024];
18 | let mut offset = 0;
19 |
20 | val.marshall_offset(&mut buf, &mut offset)
21 | .expect("Failed first marshall_offset");
22 | assert_eq!(offset, len);
23 |
24 | val.marshall_offset(&mut buf, &mut offset)
25 | .expect("Failed second marshall_offset");
26 | assert_eq!(offset, (len * 2));
27 |
28 | offset = 0;
29 | let unmarshalled_one =
30 | T::unmarshall_offset(&buf, &mut offset).expect("Failed to unmarshall_offset first copy");
31 | assert_eq!(offset, len);
32 | assert_eq!(val, &unmarshalled_one);
33 |
34 | let unmarshalled_two =
35 | T::unmarshall_offset(&buf, &mut offset).expect("Failed to unmarshall_offset second copy");
36 | assert_eq!(offset, (len * 2));
37 | assert_eq!(val, &unmarshalled_two);
38 | }
39 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/common/serde.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2023 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use serde::{de::DeserializeOwned, Serialize};
4 | use tss_esapi::traits::{Marshall, UnMarshall};
5 |
6 | pub fn check_serialise_deserialise<
7 | T: Serialize + DeserializeOwned + Marshall + UnMarshall + Eq + std::fmt::Debug,
8 | >(
9 | val: &T,
10 | ) {
11 | let json = serde_json::to_vec(val).expect("Failed to serialise value");
12 |
13 | let unmarshalled: T = serde_json::from_slice(&json).expect("Failed to deserialise");
14 |
15 | assert_eq!(val, &unmarshalled);
16 | }
17 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/common/tpm2b_types_equality_checks.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use tss_esapi::tss2_esys::{
4 | TPM2B_AUTH, TPM2B_CONTEXT_DATA, TPM2B_DATA, TPM2B_DIGEST, TPM2B_MAX_NV_BUFFER, TPM2B_NAME,
5 | TPM2B_SENSITIVE_CREATE, TPM2B_SENSITIVE_DATA,
6 | };
7 |
8 | macro_rules! ensure_sized_buffer_equality {
9 | ($expected:ident, $actual:ident, $buffer_field_name:ident, $tss_type:ident) => {
10 | assert_eq!(
11 | $expected.size,
12 | $actual.size,
13 | "'size' value in {}, mismatch between actual and expected",
14 | stringify!($tss_type),
15 | );
16 | assert_eq!(
17 | $expected.$buffer_field_name,
18 | $actual.$buffer_field_name,
19 | "'{}' value in {}, mismatch between actual and expected",
20 | stringify!($buffer_field_name),
21 | stringify!($tss_type),
22 | );
23 | };
24 | }
25 |
26 | pub fn ensure_tpm2b_name_equality(expected: &TPM2B_NAME, actual: &TPM2B_NAME) {
27 | ensure_sized_buffer_equality!(expected, actual, name, TPM2B_NAME);
28 | }
29 |
30 | pub fn ensure_tpm2b_digest_equality(expected: &TPM2B_DIGEST, actual: &TPM2B_DIGEST) {
31 | ensure_sized_buffer_equality!(expected, actual, buffer, TPM2B_DIGEST);
32 | }
33 |
34 | pub fn ensure_tpm2b_data_equality(expected: &TPM2B_DATA, actual: &TPM2B_DATA) {
35 | ensure_sized_buffer_equality!(expected, actual, buffer, TPM2B_DATA);
36 | }
37 |
38 | pub fn ensure_tpm2b_auth_equality(expected: &TPM2B_AUTH, actual: &TPM2B_AUTH) {
39 | ensure_sized_buffer_equality!(expected, actual, buffer, TPM2B_AUTH);
40 | }
41 |
42 | pub fn ensure_tpm2b_sensitive_data(expected: &TPM2B_SENSITIVE_DATA, actual: &TPM2B_SENSITIVE_DATA) {
43 | ensure_sized_buffer_equality!(expected, actual, buffer, TPM2B_SENSITIVE_DATA);
44 | }
45 |
46 | pub fn ensure_tpm2b_max_nv_buffer_equality(
47 | expected: &TPM2B_MAX_NV_BUFFER,
48 | actual: &TPM2B_MAX_NV_BUFFER,
49 | ) {
50 | ensure_sized_buffer_equality!(expected, actual, buffer, TPM2B_MAX_NV_BUFFER);
51 | }
52 |
53 | pub fn ensure_tpm2b_sensitive_create_equality(
54 | expected: &TPM2B_SENSITIVE_CREATE,
55 | actual: &TPM2B_SENSITIVE_CREATE,
56 | ) {
57 | assert_eq!(
58 | expected.size, actual.size,
59 | "'size' value in TPM2B_SENSITIVE_CREATE, mismatch between actual and expected",
60 | );
61 | crate::common::ensure_tpms_sensitive_create_equality(&expected.sensitive, &actual.sensitive);
62 | }
63 |
64 | pub fn ensure_tpm2b_context_data_equality(
65 | expected: &TPM2B_CONTEXT_DATA,
66 | actual: &TPM2B_CONTEXT_DATA,
67 | ) {
68 | ensure_sized_buffer_equality!(expected, actual, buffer, TPM2B_CONTEXT_DATA);
69 | }
70 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/common/tpma_types_equality_checks.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use tss_esapi::tss2_esys::TPMA_CC;
5 |
6 | pub fn ensure_tpma_cc_equality(expected: &TPMA_CC, actual: &TPMA_CC) {
7 | assert_eq!(
8 | expected, actual,
9 | "mismatch between actual and expected TPMA_CC value"
10 | );
11 | }
12 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/common/tpml_types_equality_checks.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use tss_esapi::tss2_esys::{
4 | TPML_ALG_PROPERTY, TPML_CCA, TPML_PCR_SELECTION, TPML_TAGGED_PCR_PROPERTY,
5 | TPML_TAGGED_TPM_PROPERTY,
6 | };
7 |
8 | macro_rules! ensure_list_equality {
9 | ($name:ident, $list_type:ident, $items_field_name:ident, $item_equality_func:ident) => {
10 | pub fn $name(expected: &$list_type, actual: &$list_type) {
11 | assert_eq!(
12 | expected.count,
13 | actual.count,
14 | "'count' value in {}, mismatch between actual and expected",
15 | stringify!($list_type)
16 | );
17 | expected.$items_field_name[..expected.count as usize]
18 | .iter()
19 | .zip(actual.$items_field_name[..actual.count as usize].iter())
20 | .for_each(|(expected, actual)| {
21 | crate::common::$item_equality_func(expected, actual)
22 | });
23 | }
24 | };
25 | }
26 |
27 | ensure_list_equality!(
28 | ensure_tpml_pcr_selection_equality,
29 | TPML_PCR_SELECTION,
30 | pcrSelections,
31 | ensure_tpms_pcr_selection_equality
32 | );
33 |
34 | ensure_list_equality!(
35 | ensure_tpml_tagged_tpm_property_equality,
36 | TPML_TAGGED_TPM_PROPERTY,
37 | tpmProperty,
38 | ensure_tpms_tagged_property_equality
39 | );
40 |
41 | ensure_list_equality!(
42 | ensure_tpml_alg_property_equality,
43 | TPML_ALG_PROPERTY,
44 | algProperties,
45 | ensure_tpms_alg_property_equality
46 | );
47 |
48 | ensure_list_equality!(
49 | ensure_tpml_tagged_pcr_property_equality,
50 | TPML_TAGGED_PCR_PROPERTY,
51 | pcrProperty,
52 | ensure_tpms_tagged_pcr_select_equality
53 | );
54 |
55 | ensure_list_equality!(
56 | ensure_tpml_cca_equality,
57 | TPML_CCA,
58 | commandAttributes,
59 | ensure_tpma_cc_equality
60 | );
61 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/constants_tests/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod algorithm_tests;
4 | mod capabilities_tests;
5 | mod command_code_tests;
6 | mod nv_index_type_tests;
7 | mod pcr_property_tag_tests;
8 | mod return_code_tests;
9 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/constants_tests/nv_index_type_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use tss_esapi::{
4 | constants::{
5 | tss::{
6 | TPM2_NT_BITS, TPM2_NT_COUNTER, TPM2_NT_EXTEND, TPM2_NT_ORDINARY, TPM2_NT_PIN_FAIL,
7 | TPM2_NT_PIN_PASS,
8 | },
9 | NvIndexType,
10 | },
11 | tss2_esys::TPM2_NT,
12 | };
13 |
14 | use std::convert::{From, TryFrom};
15 |
16 | #[test]
17 | fn test_conversion_to_tss_type() {
18 | assert_eq!(TPM2_NT_ORDINARY, TPM2_NT::from(NvIndexType::Ordinary));
19 | assert_eq!(TPM2_NT_COUNTER, TPM2_NT::from(NvIndexType::Counter));
20 | assert_eq!(TPM2_NT_BITS, TPM2_NT::from(NvIndexType::Bits));
21 | assert_eq!(TPM2_NT_EXTEND, TPM2_NT::from(NvIndexType::Extend));
22 | assert_eq!(TPM2_NT_PIN_FAIL, TPM2_NT::from(NvIndexType::PinFail));
23 | assert_eq!(TPM2_NT_PIN_PASS, TPM2_NT::from(NvIndexType::PinPass));
24 | }
25 |
26 | #[test]
27 | fn test_conversion_from_tss_type() {
28 | assert_eq!(
29 | NvIndexType::Ordinary,
30 | NvIndexType::try_from(TPM2_NT_ORDINARY).unwrap()
31 | );
32 | assert_eq!(
33 | NvIndexType::Counter,
34 | NvIndexType::try_from(TPM2_NT_COUNTER).unwrap()
35 | );
36 | assert_eq!(
37 | NvIndexType::Bits,
38 | NvIndexType::try_from(TPM2_NT_BITS).unwrap()
39 | );
40 | assert_eq!(
41 | NvIndexType::Extend,
42 | NvIndexType::try_from(TPM2_NT_EXTEND).unwrap()
43 | );
44 | assert_eq!(
45 | NvIndexType::PinFail,
46 | NvIndexType::try_from(TPM2_NT_PIN_FAIL).unwrap()
47 | );
48 | assert_eq!(
49 | NvIndexType::PinPass,
50 | NvIndexType::try_from(TPM2_NT_PIN_PASS).unwrap()
51 | );
52 |
53 | const INVALID_VALUE: TPM2_NT = 15;
54 | let _ = NvIndexType::try_from(INVALID_VALUE).unwrap_err();
55 | }
56 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/constants_tests/return_code_tests/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod base_return_code_tests;
4 | mod return_code_layer_tests;
5 | mod tpm_format_one_error_tests;
6 | mod tpm_format_zero_error_tests;
7 | mod tpm_format_zero_warning_tests;
8 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/context_tests/mod.rs:
--------------------------------------------------------------------------------
1 | mod general_esys_tr_tests;
2 | mod tpm_commands;
3 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/context_tests/tpm_commands/attached_components_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/context_tests/tpm_commands/authenticated_countdown_timer_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/context_tests/tpm_commands/capability_commands_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod test_get_capability {
4 | use crate::common::create_ctx_without_session;
5 | use tss_esapi::{
6 | constants::{tss::TPM2_PT_VENDOR_STRING_1, CapabilityType, PropertyTag},
7 | structures::CapabilityData,
8 | };
9 |
10 | #[test]
11 | fn test_get_capability() {
12 | let mut context = create_ctx_without_session();
13 | let (res, _more) = context
14 | .get_capability(CapabilityType::TpmProperties, TPM2_PT_VENDOR_STRING_1, 4)
15 | .unwrap();
16 | match res {
17 | CapabilityData::TpmProperties(props) => {
18 | assert_ne!(props.len(), 0);
19 | }
20 | _ => panic!("Invalid properties returned"),
21 | };
22 | }
23 |
24 | #[test]
25 | fn test_get_tpm_property() {
26 | let mut context = create_ctx_without_session();
27 |
28 | let rev = context
29 | .get_tpm_property(PropertyTag::Revision)
30 | .expect("Failed to call get_tpm_property")
31 | .expect("The TPM did not have a value for the Reveision property tag");
32 | assert_ne!(rev, 0);
33 |
34 | let year = context
35 | .get_tpm_property(PropertyTag::Year)
36 | .expect("Failed to call get_tpm_property")
37 | .expect("The TPM did not have a value for the Year property tag");
38 | assert_ne!(year, 0);
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/context_tests/tpm_commands/clocks_and_timers_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/context_tests/tpm_commands/command_audit_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/context_tests/tpm_commands/dictionary_attack_functions_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/context_tests/tpm_commands/ephemeral_ec_keys_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/context_tests/tpm_commands/field_upgrade_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/context_tests/tpm_commands/hash_hmac_event_sequences_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/context_tests/tpm_commands/miscellaneous_management_functions_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/context_tests/tpm_commands/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod asymmetric_primitives_tests;
4 | mod attached_components_tests;
5 | mod attestation_commands_tests;
6 | mod authenticated_countdown_timer_tests;
7 | mod capability_commands_tests;
8 | mod clocks_and_timers_tests;
9 | mod command_audit_tests;
10 | mod context_management_tests;
11 | mod dictionary_attack_functions_tests;
12 | mod duplication_commands_tests;
13 | mod enhanced_authorization_ea_commands_tests;
14 | mod ephemeral_ec_keys_tests;
15 | mod field_upgrade_tests;
16 | mod hash_hmac_event_sequences_tests;
17 | mod hierarchy_commands_tests;
18 | mod integrity_collection_pcr_tests;
19 | mod miscellaneous_management_functions_tests;
20 | mod non_volatile_storage_tests;
21 | mod object_commands_tests;
22 | mod random_number_generator_tests;
23 | mod session_commands_tests;
24 | mod signing_and_signature_verification_tests;
25 | mod startup_tests;
26 | mod symmetric_primitives_tests;
27 | mod testing_tests;
28 | mod vendor_specific_tests;
29 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/context_tests/tpm_commands/startup_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod test_startup {
4 | use crate::common::create_ctx_without_session;
5 | use tss_esapi::constants::StartupType;
6 |
7 | #[test]
8 | fn test_startup() {
9 | let mut context = create_ctx_without_session();
10 | context.startup(StartupType::Clear).unwrap();
11 | }
12 | }
13 |
14 | mod test_shutdown {
15 | use crate::common::create_ctx_without_session;
16 | use tss_esapi::constants::StartupType;
17 | #[test]
18 | fn test_shutdown() {
19 | let mut context = create_ctx_without_session();
20 | context.shutdown(StartupType::Clear).unwrap();
21 | // Re-start the TPM so our tests won't fail
22 | context.startup(StartupType::Clear).unwrap();
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/context_tests/tpm_commands/testing_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod test_self_test {
4 | use crate::common::create_ctx_without_session;
5 |
6 | #[test]
7 | fn test_self_test() {
8 | let mut context = create_ctx_without_session();
9 | context.self_test(false).unwrap();
10 | context.self_test(true).unwrap();
11 | }
12 | }
13 |
14 | mod test_get_test_result {
15 | use crate::common::create_ctx_without_session;
16 | #[test]
17 | fn test_get_test_result() {
18 | let mut context = create_ctx_without_session();
19 | let (_, rc) = context.get_test_result().unwrap();
20 | rc.unwrap();
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/context_tests/tpm_commands/vendor_specific_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/error_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2023 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod return_code_tests;
4 | mod wrapper_error_kind_tests;
5 |
6 | use std::{convert::TryFrom, error::Error};
7 |
8 | use tss_esapi::{
9 | constants::tss::{TPM2_RC_INITIALIZE, TSS2_TPM_RC_LAYER},
10 | error::{ReturnCode, WrapperErrorKind},
11 | };
12 |
13 | #[test]
14 | fn test_error_trait_implementation() {
15 | // The Error type is only expected to forward everything to the
16 | // underlying error types.
17 | let expected_wrapper_error_kind = WrapperErrorKind::InconsistentParams;
18 | let wrapper_error = tss_esapi::Error::WrapperError(expected_wrapper_error_kind);
19 | let actual_wrapper_error_kind = wrapper_error
20 | .source()
21 | .expect("`source()` for an Error of type WrapperError returned None.");
22 | assert_eq!(
23 | format!("{}", expected_wrapper_error_kind),
24 | format!("{}", actual_wrapper_error_kind)
25 | );
26 |
27 | let expected_return_code = ReturnCode::try_from(TSS2_TPM_RC_LAYER | TPM2_RC_INITIALIZE)
28 | .expect("Failed to convert TSS return code into a ReturnCode object.");
29 | let tss_error = tss_esapi::Error::TssError(expected_return_code);
30 | let actual_return_code = tss_error
31 | .source()
32 | .expect("`source()` for an Error of type ReturnCode returned None.");
33 | assert_eq!(
34 | format!("{}", expected_return_code),
35 | format!("{}", actual_return_code)
36 | );
37 | }
38 |
39 | #[test]
40 | fn test_display_trait_implementation() {
41 | // The Error type is only expected to forward everything to the
42 | // underlying error types.
43 | let expected_wrapper_error_kind = WrapperErrorKind::InconsistentParams;
44 | let wrapper_error = tss_esapi::Error::WrapperError(expected_wrapper_error_kind);
45 | assert_eq!(
46 | format!("{}", expected_wrapper_error_kind),
47 | format!("{}", wrapper_error)
48 | );
49 |
50 | let expected_return_code = ReturnCode::try_from(TSS2_TPM_RC_LAYER | TPM2_RC_INITIALIZE)
51 | .expect("Failed to convert TSS return code into a ReturnCode object.");
52 | let tss_error = tss_esapi::Error::TssError(expected_return_code);
53 | assert_eq!(
54 | format!("{}", expected_return_code),
55 | format!("{}", tss_error)
56 | );
57 | }
58 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/error_tests/return_code_tests/resource_manager_tpm_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2023 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use std::convert::TryFrom;
4 | use tss_esapi::{
5 | constants::tss::{TPM2_RC_ASYMMETRIC, TPM2_RC_SEQUENCE, TSS2_RESMGR_TPM_RC_LAYER},
6 | error::{ReturnCode, TpmResponseCode},
7 | tss2_esys::TSS2_RC,
8 | };
9 |
10 | #[test]
11 | fn test_valid_tpm_resmgr_format_zero_response_code() {
12 | let expected_tss_rc = TSS2_RESMGR_TPM_RC_LAYER | TPM2_RC_SEQUENCE;
13 | let actual_rc = ReturnCode::try_from(expected_tss_rc)
14 | .expect("Failed to convert TPM2_RC_SEQUENCE in the TPM RESMGR layer to a ReturnCode.");
15 |
16 | if let ReturnCode::TpmResourceManager(actual_tpm_response_code) = actual_rc {
17 | assert!(
18 | matches!(actual_tpm_response_code,TpmResponseCode::FormatZero(_)),
19 | "TPM2_RC_SEQUENCE in the TPM RESMGR layer did not convert into the expected TpmResponseCode"
20 | );
21 | } else {
22 | panic!("The TPM RESMGR layer did not convert into the expected ReturnCode");
23 | }
24 |
25 | assert_eq!(
26 | expected_tss_rc,
27 | TSS2_RC::from(actual_rc),
28 | "ReturnCode::TpmResourceManager did not convert into the expected TSS2_RC value"
29 | );
30 | }
31 |
32 | #[test]
33 | fn test_valid_tpm_resmgr_format_one_response_code() {
34 | let expected_tss_rc = TSS2_RESMGR_TPM_RC_LAYER | TPM2_RC_ASYMMETRIC;
35 | let actual_rc = ReturnCode::try_from(expected_tss_rc)
36 | .expect("Failed to convert TPM2_RC_ASYMMETRIC in the TPM RESMGR layer to a ReturnCode.");
37 |
38 | if let ReturnCode::TpmResourceManager(actual_tpm_response_code) = actual_rc {
39 | assert!(
40 | matches!(actual_tpm_response_code, TpmResponseCode::FormatOne(_)),
41 | "TPM2_RC_ASYMMETRIC in the TPM RESMGR layer did not convert into the expected TpmResponseCode"
42 | );
43 | } else {
44 | panic!("The TPM RESMGR layer did not convert into the expected ReturnCode");
45 | }
46 |
47 | assert_eq!(
48 | expected_tss_rc,
49 | TSS2_RC::from(actual_rc),
50 | "ReturnCode::TpmResourceManager did not convert into the expected TSS2_RC value"
51 | );
52 | }
53 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/error_tests/wrapper_error_kind_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2023 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use tss_esapi::error::WrapperErrorKind;
4 |
5 | #[test]
6 | fn test_display() {
7 | assert_eq!(
8 | "Parameter provided is of the wrong size.",
9 | format!("{}", WrapperErrorKind::WrongParamSize)
10 | );
11 |
12 | assert_eq!(
13 | "Some of the required parameters were not provided.",
14 | format!("{}", WrapperErrorKind::ParamsMissing)
15 | );
16 |
17 | assert_eq!(
18 | "The provided parameters have inconsistent values or variants.",
19 | format!("{}", WrapperErrorKind::InconsistentParams)
20 | );
21 |
22 | assert_eq!(
23 | "The provided parameter is not yet supported by the library.",
24 | format!("{}", WrapperErrorKind::UnsupportedParam)
25 | );
26 |
27 | assert_eq!(
28 | "The provided parameter is invalid for that type.",
29 | format!("{}", WrapperErrorKind::InvalidParam)
30 | );
31 |
32 | assert_eq!(
33 | "The TPM returned an invalid value.",
34 | format!("{}", WrapperErrorKind::WrongValueFromTpm)
35 | );
36 |
37 | assert_eq!(
38 | "Missing authorization session.",
39 | format!("{}", WrapperErrorKind::MissingAuthSession)
40 | );
41 |
42 | assert_eq!(
43 | "Invalid handle state.",
44 | format!("{}", WrapperErrorKind::InvalidHandleState)
45 | );
46 |
47 | assert_eq!(
48 | "An unexpected error occurred within the crate.",
49 | format!("{}", WrapperErrorKind::InternalError)
50 | );
51 | }
52 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/handles_tests/auth_handle_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use tss_esapi::{
4 | handles::{AuthHandle, ObjectHandle},
5 | tss2_esys::{
6 | ESYS_TR, ESYS_TR_RH_ENDORSEMENT, ESYS_TR_RH_LOCKOUT, ESYS_TR_RH_OWNER, ESYS_TR_RH_PLATFORM,
7 | },
8 | };
9 |
10 | #[test]
11 | fn test_constants_conversions() {
12 | let conversion_check =
13 | |esys_handle: ESYS_TR, object_handle: ObjectHandle, auth_handle: AuthHandle| {
14 | assert_eq!(esys_handle, ESYS_TR::from(auth_handle));
15 | assert_eq!(auth_handle, AuthHandle::from(esys_handle));
16 | assert_eq!(object_handle, ObjectHandle::from(auth_handle));
17 | assert_eq!(auth_handle, AuthHandle::from(object_handle));
18 | };
19 |
20 | // Check conversion of esys handles to TPM constants
21 | conversion_check(ESYS_TR_RH_OWNER, ObjectHandle::Owner, AuthHandle::Owner);
22 | conversion_check(
23 | ESYS_TR_RH_LOCKOUT,
24 | ObjectHandle::Lockout,
25 | AuthHandle::Lockout,
26 | );
27 | conversion_check(
28 | ESYS_TR_RH_ENDORSEMENT,
29 | ObjectHandle::Endorsement,
30 | AuthHandle::Endorsement,
31 | );
32 | conversion_check(
33 | ESYS_TR_RH_PLATFORM,
34 | ObjectHandle::Platform,
35 | AuthHandle::Platform,
36 | );
37 | }
38 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/handles_tests/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod auth_handle_tests;
4 | mod object_handle_tests;
5 | mod pcr_handle_tests;
6 | mod session_handle_tests;
7 | mod tpm_handles_tests;
8 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/handles_tests/object_handle_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use std::convert::From;
4 | use tss_esapi::{
5 | handles::ObjectHandle,
6 | tss2_esys::{
7 | ESYS_TR, ESYS_TR_NONE, ESYS_TR_RH_ENDORSEMENT, ESYS_TR_RH_LOCKOUT, ESYS_TR_RH_NULL,
8 | ESYS_TR_RH_OWNER, ESYS_TR_RH_PLATFORM, ESYS_TR_RH_PLATFORM_NV,
9 | },
10 | };
11 |
12 | #[test]
13 | fn test_constants_conversions() {
14 | // closure used for the repeated tests
15 | let conversion_check = |esys_handle: ESYS_TR, object_handle: ObjectHandle| {
16 | assert_eq!(esys_handle, ESYS_TR::from(object_handle));
17 | assert_eq!(object_handle, ObjectHandle::from(esys_handle));
18 | };
19 |
20 | // Check conversion of esys handles to TPM constants
21 | conversion_check(ESYS_TR_RH_OWNER, ObjectHandle::Owner);
22 | conversion_check(ESYS_TR_RH_NULL, ObjectHandle::Null);
23 | conversion_check(ESYS_TR_RH_LOCKOUT, ObjectHandle::Lockout);
24 | conversion_check(ESYS_TR_RH_ENDORSEMENT, ObjectHandle::Endorsement);
25 | conversion_check(ESYS_TR_RH_PLATFORM, ObjectHandle::Platform);
26 | conversion_check(ESYS_TR_RH_PLATFORM_NV, ObjectHandle::PlatformNv);
27 | conversion_check(ESYS_TR_NONE, ObjectHandle::None);
28 | }
29 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/handles_tests/session_handle_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use std::convert::From;
4 | use tss_esapi::{
5 | handles::{ObjectHandle, SessionHandle},
6 | tss2_esys::{ESYS_TR, ESYS_TR_NONE, ESYS_TR_PASSWORD},
7 | };
8 |
9 | #[test]
10 | fn test_constants_conversions() {
11 | let conversion_check =
12 | |esys_handle: ESYS_TR, object_handle: ObjectHandle, session_handle: SessionHandle| {
13 | assert_eq!(esys_handle, ESYS_TR::from(session_handle));
14 | assert_eq!(session_handle, SessionHandle::from(esys_handle));
15 | assert_eq!(object_handle, ObjectHandle::from(session_handle));
16 | assert_eq!(session_handle, SessionHandle::from(object_handle));
17 | };
18 |
19 | conversion_check(
20 | ESYS_TR_PASSWORD,
21 | ObjectHandle::Password,
22 | SessionHandle::Password,
23 | );
24 | conversion_check(ESYS_TR_NONE, ObjectHandle::None, SessionHandle::None);
25 | }
26 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/interface_types_tests/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod algorithms_tests;
4 | mod data_handles_tests;
5 | mod key_bits_tests;
6 | mod reserved_handles_tests;
7 | mod structure_tags_tests;
8 | mod yes_no_tests;
9 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/interface_types_tests/yes_no_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use std::convert::TryFrom;
5 | use tss_esapi::{interface_types::YesNo, tss2_esys::TPMI_YES_NO, Error, WrapperErrorKind};
6 | #[test]
7 | fn test_conversions() {
8 | let expected_yes_value: TPMI_YES_NO = 1;
9 | let expected_no_value: TPMI_YES_NO = 0;
10 |
11 | assert_eq!(
12 | expected_yes_value,
13 | TPMI_YES_NO::from(YesNo::Yes),
14 | "Yes did not convert to the correct value '{}'",
15 | expected_yes_value,
16 | );
17 | assert_eq!(
18 | expected_no_value,
19 | TPMI_YES_NO::from(YesNo::No),
20 | "No did not convert to the correct value '{}'",
21 | expected_no_value,
22 | );
23 | assert_eq!(
24 | YesNo::Yes,
25 | YesNo::try_from(1).expect("Failed to convert interface type to enum for Yes"),
26 | "'1' did not convert to the correct value Yes"
27 | );
28 | assert_eq!(
29 | YesNo::No,
30 | YesNo::try_from(0).expect("Failed to convert interface type to enum for No"),
31 | "'0' did not convert to the correct value No"
32 | );
33 | assert!(
34 | bool::from(YesNo::Yes),
35 | "Yes did not convert to the correct boolean value 'true'"
36 | );
37 | assert!(
38 | !bool::from(YesNo::No),
39 | "No did not convert to the correct boolean value 'false'"
40 | );
41 | }
42 |
43 | #[test]
44 | fn test_invalid_conversions() {
45 | assert_eq!(
46 | Err(Error::WrapperError(WrapperErrorKind::InvalidParam)),
47 | YesNo::try_from(100),
48 | "Conversion of invalid value did not result in expected result"
49 | );
50 | }
51 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/main.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | #[path = "common/mod.rs"]
5 | mod common;
6 |
7 | #[cfg(feature = "abstraction")]
8 | mod abstraction_tests;
9 | mod attributes_tests;
10 | mod constants_tests;
11 | mod context_tests;
12 | mod error_tests;
13 | mod handles_tests;
14 | mod interface_types_tests;
15 | mod structures_tests;
16 | mod tcti_ldr_tests;
17 | mod traits;
18 | mod utils_tests;
19 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/algorithm_property_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use std::convert::TryInto;
5 | use tss_esapi::{
6 | attributes::AlgorithmAttributes, constants::AlgorithmIdentifier, structures::AlgorithmProperty,
7 | tss2_esys::TPMS_ALG_PROPERTY,
8 | };
9 |
10 | #[test]
11 | fn test_new() {
12 | let expected_algorithm_identifier = AlgorithmIdentifier::Rsa;
13 | let expected_algorithm_properties = AlgorithmAttributes(0x1);
14 | let algorithm_proprty =
15 | AlgorithmProperty::new(expected_algorithm_identifier, expected_algorithm_properties);
16 |
17 | assert_eq!(
18 | expected_algorithm_identifier,
19 | algorithm_proprty.algorithm_identifier(),
20 | "AlgorithmProperty, created with new, did not contain expected algorithm identifier value"
21 | );
22 |
23 | assert_eq!(
24 | expected_algorithm_properties,
25 | algorithm_proprty.algorithm_properties(),
26 | "AlgorithmProperty, created with new, did not contain expected algorithm properties value"
27 | );
28 | }
29 |
30 | #[test]
31 | fn test_conversions() {
32 | let expected_algorithm_identifier = AlgorithmIdentifier::Rsa;
33 | let expected_algorithm_properties = AlgorithmAttributes(0x1);
34 |
35 | let expected_tpms_algorithm_property = TPMS_ALG_PROPERTY {
36 | alg: expected_algorithm_identifier.into(),
37 | algProperties: expected_algorithm_properties.into(),
38 | };
39 |
40 | let algorithm_property: AlgorithmProperty = expected_tpms_algorithm_property
41 | .try_into()
42 | .expect("Failed to convert TPMS_ALG_PROPERTY into AlgorithmProperty");
43 |
44 | assert_eq!(
45 | expected_algorithm_identifier,
46 | algorithm_property.algorithm_identifier(),
47 | "AlgorithmProperty, converted from TPMS_ALG_PROPERTY, did not contain the expected algorithm identifier value"
48 | );
49 |
50 | assert_eq!(
51 | expected_algorithm_properties,
52 | algorithm_property.algorithm_properties(),
53 | "AlgorithmProperty, converted from TPMS_ALG_PROPERTY, did not contain the expected algorithm properties value"
54 | );
55 |
56 | let actual_tpms_algorithm_property: TPMS_ALG_PROPERTY = algorithm_property.into();
57 |
58 | crate::common::ensure_tpms_alg_property_equality(
59 | &expected_tpms_algorithm_property,
60 | &actual_tpms_algorithm_property,
61 | );
62 | }
63 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/algorithm_tests/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod symmetric_tests;
4 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/algorithm_tests/symmetric_tests/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod sensitive_create_tests;
4 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/buffers_tests/attest_buffer_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use std::convert::TryFrom;
5 | use tss_esapi::{structures::AttestBuffer, tss2_esys::TPM2B_ATTEST, Error, WrapperErrorKind};
6 |
7 | const ATTEST_BUFFER_MAX_SIZE: usize = 2304;
8 |
9 | #[test]
10 | fn test_max_sized_data() {
11 | let _ = AttestBuffer::try_from(vec![0xFFu8; ATTEST_BUFFER_MAX_SIZE])
12 | .expect("Failed to parse buffer if maximum size as AttestBuffer");
13 | }
14 |
15 | #[test]
16 | fn test_to_large_data() {
17 | assert_eq!(
18 | AttestBuffer::try_from(vec![0xFFu8; ATTEST_BUFFER_MAX_SIZE + 1])
19 | .expect_err("Converting a buffer that is to large did not produce an error"),
20 | Error::WrapperError(WrapperErrorKind::WrongParamSize),
21 | "Wrong kind of error when converting a buffer with size {} to AttestBuffer",
22 | ATTEST_BUFFER_MAX_SIZE + 1
23 | );
24 | }
25 |
26 | #[test]
27 | fn test_default() {
28 | {
29 | let attest_buffer: AttestBuffer = Default::default();
30 | let expected: TPM2B_ATTEST = Default::default();
31 | let actual = TPM2B_ATTEST::from(attest_buffer);
32 | assert_eq!(expected.size, actual.size);
33 | assert_eq!(
34 | expected.attestationData.len(),
35 | actual.attestationData.len(),
36 | "Native and TSS attest buffer don't have the same length"
37 | );
38 | assert!(
39 | expected
40 | .attestationData
41 | .iter()
42 | .zip(actual.attestationData.iter())
43 | .all(|(a, b)| a == b),
44 | "Native and TSS attest buffer is not equal"
45 | );
46 | }
47 | {
48 | let tss_attest_buffer: TPM2B_ATTEST = Default::default();
49 | let expected: AttestBuffer = Default::default();
50 | let actual = AttestBuffer::try_from(tss_attest_buffer).unwrap();
51 | assert_eq!(expected, actual);
52 | }
53 | }
54 |
55 | #[test]
56 | fn test_max_sized_attest_buffer_conversions() {
57 | let expected_attestation_data = [0xffu8; AttestBuffer::MAX_SIZE];
58 | let native = AttestBuffer::try_from(expected_attestation_data.as_slice().to_vec()).expect(
59 | "It should be possible to convert an array of MAX size into a AttestBuffer object.",
60 | );
61 | let tss = TPM2B_ATTEST::from(native);
62 | assert_eq!(AttestBuffer::MAX_SIZE, tss.size as usize);
63 | // This will be a compiler error if the max size does not match the TSS buffer size.
64 | assert_eq!(expected_attestation_data, tss.attestationData);
65 | }
66 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/buffers_tests/auth_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use std::convert::TryFrom;
4 | use tss_esapi::structures::Auth;
5 | use tss_esapi::tss2_esys::TPM2B_AUTH;
6 | // The TPM2B_AUTH is currently
7 | // just a typedef in the C code which results
8 | // in it being just a type alias for TPM2B_DIGEST
9 | // in the rust code. So the same size restrictions that
10 | // TPM2B_DIGEST have will apply here as well.
11 |
12 | #[test]
13 | fn test_max_sized_data() {
14 | let _ = Auth::try_from([0xff; 64].to_vec()).unwrap();
15 | }
16 |
17 | #[test]
18 | fn test_to_large_data() {
19 | // Removed:
20 | // - test_handle_auth::test_set_large_handle
21 | // - test_create::test_long_auth_create
22 | // - test_create_primary::test_long_auth_create_primary
23 | // from the context tests and put here instead.
24 |
25 | let _ = Auth::try_from([0xff; 100].to_vec()).unwrap_err();
26 | }
27 |
28 | #[test]
29 | fn test_default() {
30 | {
31 | let auth: Auth = Default::default();
32 | let expected: TPM2B_AUTH = Default::default();
33 | let actual = TPM2B_AUTH::from(auth);
34 | assert_eq!(expected.size, actual.size);
35 | assert_eq!(
36 | expected.buffer.len(),
37 | actual.buffer.len(),
38 | "Buffers don't have the same length"
39 | );
40 | assert!(
41 | expected
42 | .buffer
43 | .iter()
44 | .zip(actual.buffer.iter())
45 | .all(|(a, b)| a == b),
46 | "Buffers are not equal"
47 | );
48 | }
49 | {
50 | let tss_auth: TPM2B_AUTH = Default::default();
51 | let expected: Auth = Default::default();
52 | let actual = Auth::try_from(tss_auth).unwrap();
53 | assert_eq!(expected, actual);
54 | }
55 | }
56 |
57 | #[test]
58 | fn test_max_sized_auth_conversions() {
59 | let expected_buffer = [0xffu8; Auth::MAX_SIZE];
60 | let native = Auth::try_from(expected_buffer.as_slice().to_vec())
61 | .expect("It should be possible to convert an array of MAX size into a Auth object.");
62 | let tss = TPM2B_AUTH::from(native);
63 | assert_eq!(Auth::MAX_SIZE, tss.size as usize);
64 | // This will be a compiler error if the max size does not match the TSS buffer size.
65 | assert_eq!(expected_buffer, tss.buffer);
66 | }
67 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/buffers_tests/data_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use std::convert::TryFrom;
4 | use tss_esapi::structures::Data;
5 | use tss_esapi::tss2_esys::TPM2B_DATA;
6 | // The TPM2B_DATA has a size of 64 bytes
7 |
8 | #[test]
9 | fn test_max_sized_data() {
10 | let _ = Data::try_from([0xff; 64].to_vec()).unwrap();
11 | }
12 |
13 | #[test]
14 | fn test_to_large_data() {
15 | // Removed:
16 | // - test_create::test_long_outside_info_create
17 | // - test_create_primary::test_long_outside_info_create_primary
18 | // from the context tests and put here instead.
19 |
20 | let _ = Data::try_from([0xff; 100].to_vec()).unwrap_err();
21 | }
22 |
23 | #[test]
24 | fn test_default() {
25 | {
26 | let data: Data = Default::default();
27 | let expected: TPM2B_DATA = Default::default();
28 | let actual = TPM2B_DATA::from(data);
29 | assert_eq!(expected.size, actual.size);
30 | assert_eq!(
31 | expected.buffer.len(),
32 | actual.buffer.len(),
33 | "Buffers don't have the same length"
34 | );
35 | assert!(
36 | expected
37 | .buffer
38 | .iter()
39 | .zip(actual.buffer.iter())
40 | .all(|(a, b)| a == b),
41 | "Buffers are not equal"
42 | );
43 | }
44 | {
45 | let tss_data: TPM2B_DATA = Default::default();
46 | let expected: Data = Default::default();
47 | let actual = Data::try_from(tss_data).unwrap();
48 | assert_eq!(expected, actual);
49 | }
50 | }
51 |
52 | #[test]
53 | fn test_max_sized_data_conversions() {
54 | let expected_buffer = [0xffu8; Data::MAX_SIZE];
55 | let native = Data::try_from(expected_buffer.as_slice().to_vec())
56 | .expect("It should be possible to convert an array of MAX size into a Data object.");
57 | let tss = TPM2B_DATA::from(native);
58 | assert_eq!(Data::MAX_SIZE, tss.size as usize);
59 | // This will be a compiler error if the max size does not match the TSS buffer size.
60 | assert_eq!(expected_buffer, tss.buffer);
61 | }
62 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/buffers_tests/digest_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use std::convert::{TryFrom, TryInto};
4 | use tss_esapi::{structures::Digest, tss2_esys::TPM2B_DIGEST};
5 | // Digest has some custom functions for conversion to [u8; N] for common values of N
6 |
7 | #[test]
8 | fn test_correctly_sized_digests() {
9 | // N = 20
10 | let sha1_ex = Digest::try_from((1..21).collect::>()).unwrap();
11 | let sha1: [u8; 20] = sha1_ex.try_into().unwrap();
12 | assert_eq!(sha1.to_vec(), (1..21).collect::>());
13 | // N = 32
14 | let sha256_ex = Digest::try_from((1..33).collect::>()).unwrap();
15 | let sha256: [u8; 32] = sha256_ex.try_into().unwrap();
16 | assert_eq!(sha256.to_vec(), (1..33).collect::>());
17 | // N = 48
18 | let sha384_ex = Digest::try_from((1..49).collect::>()).unwrap();
19 | let sha384: [u8; 48] = sha384_ex.try_into().unwrap();
20 | assert_eq!(sha384.to_vec(), (1..49).collect::>());
21 | // N = 64
22 | let sha512_ex = Digest::try_from((1..65).collect::>()).unwrap();
23 | let sha512: [u8; 64] = sha512_ex.try_into().unwrap();
24 | assert_eq!(sha512.to_vec(), (1..65).collect::>());
25 | }
26 |
27 | #[test]
28 | fn test_incorrectly_sized_digests() {
29 | // This test uses .err().unwrap() to get around the fact that [u8; N] is only
30 | // Debug if N is LengthAtMost32, since .unwrap_err() requires T ([u8; N]): Debug
31 | // N = 20
32 | let example = Digest::try_from([0xff; 10].to_vec()).unwrap();
33 | TryInto::<[u8; 20]>::try_into(example).err().unwrap();
34 | // N = 32
35 | let example = Digest::try_from([0xff; 10].to_vec()).unwrap();
36 | TryInto::<[u8; 32]>::try_into(example).err().unwrap();
37 | // N = 48
38 | let example = Digest::try_from([0xff; 10].to_vec()).unwrap();
39 | TryInto::<[u8; 48]>::try_into(example).err().unwrap();
40 | // N = 64
41 | let example = Digest::try_from([0xff; 10].to_vec()).unwrap();
42 | TryInto::<[u8; 64]>::try_into(example).err().unwrap();
43 | }
44 |
45 | #[test]
46 | fn test_max_sized_digest_conversions() {
47 | let expected_buffer = [0xffu8; Digest::MAX_SIZE];
48 | let native = Digest::try_from(expected_buffer.as_slice().to_vec())
49 | .expect("It should be possible to convert an array of MAX size into a Digest object.");
50 | let tss = TPM2B_DIGEST::from(native);
51 | assert_eq!(Digest::MAX_SIZE, tss.size as usize);
52 | // This will be a compiler error if the max size does not match the TSS buffer size.
53 | assert_eq!(expected_buffer, tss.buffer);
54 | }
55 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/buffers_tests/ecc_parameters_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2024 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use std::convert::TryFrom;
4 | use tss_esapi::{structures::EccParameter, tss2_esys::TPM2B_ECC_PARAMETER};
5 | #[test]
6 | fn test_max_sized_ecc_parameter_conversions() {
7 | let expected_buffer: [u8; 128] = [0xffu8; EccParameter::MAX_SIZE];
8 | let native = EccParameter::try_from(expected_buffer.as_slice().to_vec()).expect(
9 | "It should be possible to convert an array of MAX size into a EccParameter object.",
10 | );
11 | let tss = TPM2B_ECC_PARAMETER::from(native);
12 | assert_eq!(EccParameter::MAX_SIZE, tss.size as usize);
13 | // This will be a compiler error if the max size does not match the TSS buffer size.
14 | assert_eq!(expected_buffer, tss.buffer);
15 | }
16 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/buffers_tests/encrypted_secret_test.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2024 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use std::convert::TryFrom;
4 | use tss_esapi::{structures::EncryptedSecret, tss2_esys::TPM2B_ENCRYPTED_SECRET};
5 | #[test]
6 | fn test_max_sized_ecc_parameter_conversions() {
7 | let expected_secret = [0xffu8; EncryptedSecret::MAX_SIZE];
8 | let native = EncryptedSecret::try_from(expected_secret.as_slice().to_vec()).expect(
9 | "It should be possible to convert an array of MAX size into a EncryptedSecret object.",
10 | );
11 | let tss = TPM2B_ENCRYPTED_SECRET::from(native);
12 | assert_eq!(EncryptedSecret::MAX_SIZE, tss.size as usize);
13 | // This will be a compiler error if the max size does not match the TSS buffer size.
14 | assert_eq!(expected_secret, tss.secret);
15 | }
16 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/buffers_tests/id_object_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2024 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use std::convert::TryFrom;
4 | use tss_esapi::{structures::IdObject, tss2_esys::TPM2B_ID_OBJECT};
5 | #[test]
6 | fn test_max_sized_id_object_conversions() {
7 | let expected_credential = [0xffu8; IdObject::MAX_SIZE];
8 | let native = IdObject::try_from(expected_credential.as_slice().to_vec())
9 | .expect("It should be possible to convert an array of MAX size into a IdObject object.");
10 | let tss = TPM2B_ID_OBJECT::from(native);
11 | assert_eq!(IdObject::MAX_SIZE, tss.size as usize);
12 | // This will be a compiler error if the max size does not match the TSS buffer size.
13 | assert_eq!(expected_credential, tss.credential);
14 | }
15 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/buffers_tests/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod attest_buffer_tests;
4 | mod auth_tests;
5 | mod data_tests;
6 | mod digest_tests;
7 | mod ecc_parameters_tests;
8 | mod encrypted_secret_test;
9 | mod id_object_tests;
10 | mod max_buffer_tests;
11 | mod nonce_tests;
12 | mod private;
13 | mod public;
14 | mod sensitive;
15 | mod sensitive_create_buffer_tests;
16 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/buffers_tests/private.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2023 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use std::convert::TryFrom;
5 | use tss_esapi::{structures::Private, tss2_esys::TPM2B_PRIVATE};
6 |
7 | #[test]
8 | fn marshall_unmarshall() {
9 | crate::common::check_marshall_unmarshall(&Private::default());
10 | let private = Private::try_from([0xff; 100].to_vec()).unwrap();
11 | crate::common::check_marshall_unmarshall(&private);
12 | }
13 |
14 | #[test]
15 | #[cfg(feature = "serde")]
16 | fn serialise_deserialise() {
17 | crate::common::check_serialise_deserialise(&Private::default());
18 | let private = Private::try_from([0xff; 100].to_vec()).unwrap();
19 | crate::common::check_serialise_deserialise(&private);
20 | }
21 |
22 | #[test]
23 | fn marshall_unmarshall_offset() {
24 | crate::common::check_marshall_unmarshall_offset(&Private::default());
25 | let private = Private::try_from([0xff; 100].to_vec()).unwrap();
26 | crate::common::check_marshall_unmarshall_offset(&private);
27 | }
28 |
29 | #[test]
30 | fn test_max_sized_private_conversions() {
31 | let expected_buffer = [0xffu8; Private::MAX_SIZE];
32 | let native = Private::try_from(expected_buffer.as_slice().to_vec())
33 | .expect("It should be possible to convert an array of MAX size into a Private object.");
34 | let tss = TPM2B_PRIVATE::from(native);
35 | assert_eq!(Private::MAX_SIZE, tss.size as usize);
36 | // This will be a compiler error if the max size does not match the TSS buffer size.
37 | assert_eq!(expected_buffer, tss.buffer);
38 | }
39 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/buffers_tests/public.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use std::convert::TryFrom;
5 | use tss_esapi::{
6 | structures::{Public, PublicBuffer},
7 | Error, WrapperErrorKind,
8 | };
9 |
10 | const PUBLIC_BUFFER_MAX_SIZE: usize = 612;
11 |
12 | #[test]
13 | fn test_max_sized_data() {
14 | let _ = PublicBuffer::try_from(vec![0xffu8; PUBLIC_BUFFER_MAX_SIZE])
15 | .expect("Failed to parse buffer of maximum size as PublicBuffer");
16 | }
17 |
18 | #[test]
19 | fn test_to_large_data() {
20 | assert_eq!(
21 | PublicBuffer::try_from(vec![0xffu8; PUBLIC_BUFFER_MAX_SIZE + 1])
22 | .expect_err("Converting a buffer that is to large did not produce an error"),
23 | Error::WrapperError(WrapperErrorKind::WrongParamSize),
24 | "Wrong kind of error when converting a buffer with size {} to PublicBuffer",
25 | PUBLIC_BUFFER_MAX_SIZE + 1
26 | );
27 | }
28 |
29 | #[test]
30 | fn marshall_unmarshall() {
31 | crate::common::publics().iter().for_each(|public| {
32 | let public = public.clone();
33 | let pub_buf = PublicBuffer::try_from(public.clone())
34 | .expect("Failed to convert from Public to PublicBuffer");
35 | crate::common::check_marshall_unmarshall(&pub_buf);
36 | assert_eq!(
37 | public,
38 | Public::try_from(pub_buf).expect("Failed to convert from PublicBuffer to Public")
39 | );
40 | });
41 | }
42 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/buffers_tests/sensitive.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use std::convert::TryFrom;
5 | use tss_esapi::{
6 | structures::{Sensitive, SensitiveBuffer},
7 | Error, WrapperErrorKind,
8 | };
9 |
10 | const SENSITIVE_BUFFER_MAX_SIZE: usize = 1416;
11 |
12 | #[test]
13 | fn test_max_sized_data() {
14 | let _ = SensitiveBuffer::try_from(vec![0xffu8; SENSITIVE_BUFFER_MAX_SIZE])
15 | .expect("Failed to parse buffer of maximum size as SensitiveBuffer");
16 | }
17 |
18 | #[test]
19 | fn test_to_large_data() {
20 | assert_eq!(
21 | SensitiveBuffer::try_from(vec![0xffu8; SENSITIVE_BUFFER_MAX_SIZE + 1])
22 | .expect_err("Converting a buffer that is to large did not produce an error"),
23 | Error::WrapperError(WrapperErrorKind::WrongParamSize),
24 | "Wrong kind of error when converting a buffer with size {} to SensitiveBuffer",
25 | SENSITIVE_BUFFER_MAX_SIZE + 1
26 | );
27 | }
28 |
29 | #[test]
30 | fn marshall_unmarshall() {
31 | crate::common::sensitives().iter().for_each(|sensitive| {
32 | let sensitive = sensitive.clone();
33 | let pub_buf = SensitiveBuffer::try_from(sensitive.clone())
34 | .expect("Failed to convert from Sensitive to SensitiveBuffer");
35 | crate::common::check_marshall_unmarshall(&pub_buf);
36 | assert_eq!(
37 | sensitive,
38 | Sensitive::try_from(pub_buf)
39 | .expect("Failed to convert from SensitiveBuffer to Sensitive")
40 | );
41 | });
42 | }
43 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/certify_info_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use std::convert::TryFrom;
5 | use tss_esapi::{
6 | structures::{CertifyInfo, Name},
7 | tss2_esys::TPMS_CERTIFY_INFO,
8 | };
9 |
10 | #[test]
11 | fn test_conversion() {
12 | let expected_name = Name::try_from(vec![0xFFu8; 64]).expect("Failed to create name");
13 | let expected_qualified_name =
14 | Name::try_from(vec![0x0fu8; 64]).expect("Failed to create qualified name");
15 | let expected_tpms_certify_info = TPMS_CERTIFY_INFO {
16 | name: expected_name.clone().into(),
17 | qualifiedName: expected_qualified_name.clone().into(),
18 | };
19 |
20 | let certify_info = CertifyInfo::try_from(expected_tpms_certify_info)
21 | .expect("Failed to convert TPMS_CERTIFY_INFO to certifyInfo");
22 | assert_eq!(
23 | &expected_name,
24 | certify_info.name(),
25 | "Converted certify info did not contain expected name"
26 | );
27 | assert_eq!(
28 | &expected_qualified_name,
29 | certify_info.qualified_name(),
30 | "Converted certify info did not contain expected qualified name"
31 | );
32 |
33 | let actual_tpms_certify_info: TPMS_CERTIFY_INFO = certify_info.into();
34 |
35 | crate::common::ensure_tpms_certify_info_equality(
36 | &expected_tpms_certify_info,
37 | &actual_tpms_certify_info,
38 | );
39 | }
40 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/clock_info_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use std::convert::TryFrom;
5 | use tss_esapi::{
6 | interface_types::YesNo, structures::ClockInfo, tss2_esys::TPMS_CLOCK_INFO, Error,
7 | WrapperErrorKind,
8 | };
9 |
10 | #[test]
11 | fn test_conversions() {
12 | let expected_clock = 1u64;
13 | let expected_reset_count = 2u32;
14 | let expected_restart_count = 3u32;
15 | let expected_safe = YesNo::Yes;
16 |
17 | let expected_tpms_clock_info = TPMS_CLOCK_INFO {
18 | clock: expected_clock,
19 | resetCount: expected_reset_count,
20 | restartCount: expected_restart_count,
21 | safe: expected_safe.into(),
22 | };
23 |
24 | let clock_info = ClockInfo::try_from(expected_tpms_clock_info)
25 | .expect("Failed to convert TPMS_CLOCK_INFO into ClockInfo");
26 |
27 | assert_eq!(
28 | expected_clock,
29 | clock_info.clock(),
30 | "'clock' value mismatch between actual and expected values"
31 | );
32 | assert_eq!(
33 | expected_reset_count,
34 | clock_info.reset_count(),
35 | "'reset count' value mismatch between actual and expected values"
36 | );
37 | assert_eq!(
38 | expected_restart_count,
39 | clock_info.restart_count(),
40 | "'restart count' value mismatch between actual and expected values"
41 | );
42 | assert_eq!(
43 | bool::from(expected_safe),
44 | clock_info.safe(),
45 | "'safe' value mismatch between actual and expected values"
46 | );
47 |
48 | let actual_tpms_clock_info: TPMS_CLOCK_INFO = clock_info.into();
49 |
50 | crate::common::ensure_tpms_clock_info_equality(
51 | &expected_tpms_clock_info,
52 | &actual_tpms_clock_info,
53 | );
54 | }
55 |
56 | #[test]
57 | fn test_invalid_conversion() {
58 | assert_eq!(
59 | Error::WrapperError(WrapperErrorKind::InvalidParam),
60 | ClockInfo::try_from(TPMS_CLOCK_INFO {
61 | clock: 1u64,
62 | resetCount: 2u32,
63 | restartCount: 3u32,
64 | safe: 4u8,
65 | })
66 | .expect_err("Conversion of invalid ClockInfo parameters did not produce an error"),
67 | "Error produced did not match the expected error.",
68 | );
69 | }
70 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/command_audit_info_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use std::convert::{TryFrom, TryInto};
5 | use tss_esapi::{
6 | constants::AlgorithmIdentifier,
7 | interface_types::algorithm::HashingAlgorithm,
8 | structures::{CommandAuditInfo, Digest},
9 | tss2_esys::TPMS_COMMAND_AUDIT_INFO,
10 | };
11 |
12 | #[test]
13 | fn test_conversion() {
14 | let expected_audit_counter = 1u64;
15 | let expected_hashing_algorithm = HashingAlgorithm::Sha512;
16 | let expected_audit_digest =
17 | Digest::try_from(vec![0xffu8; 32]).expect("Failed to create audit digest");
18 | let expected_command_digest =
19 | Digest::try_from(vec![0xf0u8; 32]).expect("Failed to create command digest");
20 | let expected_tpms_command_audit_info = TPMS_COMMAND_AUDIT_INFO {
21 | auditCounter: expected_audit_counter,
22 | digestAlg: AlgorithmIdentifier::from(expected_hashing_algorithm).into(),
23 | auditDigest: expected_audit_digest.clone().into(),
24 | commandDigest: expected_command_digest.clone().into(),
25 | };
26 | let command_audit_info: CommandAuditInfo = expected_tpms_command_audit_info
27 | .try_into()
28 | .expect("Failed to convert TPMS_COMMAND_AUDIT_INFO into CommandAuditInfo");
29 |
30 | assert_eq!(
31 | expected_audit_counter,
32 | command_audit_info.audit_counter(),
33 | "The CommandAuditInfo converted from TPMS_COMMAND_AUDIT_INFO did not contain correct value for 'audit counter'",
34 | );
35 | assert_eq!(
36 | expected_hashing_algorithm,
37 | command_audit_info.hashing_algorithm(),
38 | "The CommandAuditInfo converted from TPMS_COMMAND_AUDIT_INFO did not contain correct value for 'hashing algorithm'",
39 | );
40 | assert_eq!(
41 | &expected_audit_digest,
42 | command_audit_info.audit_digest(),
43 | "The CommandAuditInfo converted from TPMS_COMMAND_AUDIT_INFO did not contain correct value for 'audit digest'",
44 | );
45 | assert_eq!(
46 | &expected_command_digest,
47 | command_audit_info.command_digest(),
48 | "The CommandAuditInfo converted from TPMS_COMMAND_AUDIT_INFO did not contain correct value for 'command digest'",
49 | );
50 |
51 | let actual_tpms_command_audit_info: TPMS_COMMAND_AUDIT_INFO = command_audit_info.into();
52 |
53 | crate::common::ensure_tpms_command_audit_info_equality(
54 | &expected_tpms_command_audit_info,
55 | &actual_tpms_command_audit_info,
56 | );
57 | }
58 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/creation_info_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use std::convert::{TryFrom, TryInto};
5 | use tss_esapi::{
6 | structures::{CreationInfo, Digest, Name},
7 | tss2_esys::TPMS_CREATION_INFO,
8 | };
9 |
10 | #[test]
11 | fn test_conversion() {
12 | let expected_object_name =
13 | Name::try_from(vec![0xf0u8; 68]).expect("Failed to create object name");
14 | let expected_creation_hash =
15 | Digest::try_from(vec![0xffu8; 32]).expect("Failed to create creation digest");
16 | let expected_tpms_creation_info = TPMS_CREATION_INFO {
17 | objectName: expected_object_name.clone().into(),
18 | creationHash: expected_creation_hash.clone().into(),
19 | };
20 |
21 | let creation_info: CreationInfo = expected_tpms_creation_info
22 | .try_into()
23 | .expect("Failed to convert TPMS_CREATION_INFO into CreationInfo");
24 |
25 | assert_eq!(
26 | &expected_object_name,
27 | creation_info.object_name(),
28 | "The CommandAuditInfo converted from TPMS_CREATION_INFO did not contain correct value for 'object name'",
29 | );
30 |
31 | assert_eq!(
32 | &expected_creation_hash,
33 | creation_info.creation_hash(),
34 | "The CommandAuditInfo converted from TPMS_CREATION_INFO did not contain correct value for 'creation hash'",
35 | );
36 |
37 | let actual_tpms_creation_info: TPMS_CREATION_INFO = creation_info.into();
38 |
39 | crate::common::ensure_tpms_creation_info_equality(
40 | &expected_tpms_creation_info,
41 | &actual_tpms_creation_info,
42 | );
43 | }
44 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/lists_tests/digest_list_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use std::convert::TryFrom;
4 | use tss_esapi::structures::{Digest, DigestList};
5 | use tss_esapi::tss2_esys::{TPM2B_DIGEST, TPML_DIGEST};
6 |
7 | #[test]
8 | fn test_conversion_from_tss_digest_list() {
9 | let mut expected_digests = Vec::::new();
10 | let mut tss_digest_list: TPML_DIGEST = Default::default();
11 | for i in 0..3 {
12 | let mut tss_digest = TPM2B_DIGEST {
13 | size: 32,
14 | ..Default::default()
15 | };
16 | tss_digest.buffer[..32].copy_from_slice(&[i; 32]);
17 | expected_digests.push(Digest::try_from(tss_digest).unwrap());
18 | tss_digest_list.digests[i as usize] = tss_digest;
19 | tss_digest_list.count += 1;
20 | }
21 |
22 | let digest_list = DigestList::try_from(tss_digest_list).unwrap();
23 | assert_eq!(digest_list.value().len(), tss_digest_list.count as usize);
24 | for actual_digest in digest_list.value().iter() {
25 | match expected_digests
26 | .iter()
27 | .position(|v| v.as_bytes() == actual_digest.as_bytes())
28 | {
29 | Some(pos) => {
30 | expected_digests.remove(pos);
31 | }
32 | None => panic!("Digest did not exist in the expected digests"),
33 | }
34 | }
35 | assert_eq!(expected_digests.len(), 0);
36 | }
37 |
38 | #[test]
39 | fn test_add_exceeding_max_limit() {
40 | let digest = Digest::try_from(vec![1, 2, 3, 4, 5, 6, 7]).unwrap();
41 | let mut digest_list: DigestList = Default::default();
42 | for _ in 0..DigestList::MAX_SIZE {
43 | digest_list.add(digest.clone()).unwrap();
44 | }
45 | digest_list.add(digest).unwrap_err();
46 | }
47 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/lists_tests/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod algorithm_property_list_tests;
4 | mod command_code_attributes_list_tests;
5 | mod command_code_list_tests;
6 | mod digest_list_tests;
7 | mod ecc_curve_list_tests;
8 | mod handle_list_tests;
9 | mod pcr_selection_list_builder_tests;
10 | mod pcr_selection_list_tests;
11 | mod tagged_pcr_property_list_tests;
12 | mod tagged_tpm_property_list_tests;
13 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod algorithm_property_tests;
4 | mod algorithm_tests;
5 | mod attest_info_test;
6 | mod attest_tests;
7 | mod buffers_tests;
8 | mod capability_data_tests;
9 | mod certify_info_tests;
10 | mod clock_info_tests;
11 | mod command_audit_info_tests;
12 | mod creation_info_tests;
13 | mod lists_tests;
14 | mod nv_certify_info_tests;
15 | mod pcr_tests;
16 | mod quote_info_tests;
17 | mod session_audit_info_tests;
18 | mod tagged_pcr_select_tests;
19 | mod tagged_property_tests;
20 | mod tagged_tests;
21 | mod time_attest_info_tests;
22 | mod time_info_tests;
23 | mod tpm_context_tests;
24 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/nv_certify_info_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use std::convert::{TryFrom, TryInto};
5 | use tss_esapi::{
6 | structures::{MaxNvBuffer, Name, NvCertifyInfo},
7 | tss2_esys::TPMS_NV_CERTIFY_INFO,
8 | };
9 |
10 | #[test]
11 | fn test_conversion() {
12 | let expected_index_name =
13 | Name::try_from(vec![0xf0u8; 68]).expect("Failed to create index name");
14 | let expected_offset = 12u16;
15 | let expected_nv_contents =
16 | MaxNvBuffer::try_from(vec![0xfc; 2048]).expect("Failed to create nv contents");
17 | let expected_tpms_nv_certify_info = TPMS_NV_CERTIFY_INFO {
18 | indexName: expected_index_name.clone().into(),
19 | offset: expected_offset,
20 | nvContents: expected_nv_contents.clone().into(),
21 | };
22 |
23 | let nv_certify_info: NvCertifyInfo = expected_tpms_nv_certify_info
24 | .try_into()
25 | .expect("Failed to convert TPMS_NV_CERTIFY_INFO into NvCertifyInfo");
26 | assert_eq!(
27 | &expected_index_name,
28 | nv_certify_info.index_name(),
29 | "The NvCertifyInfo converted from TPMS_NV_CERTIFY_INFO did not contain correct value for 'index name'",
30 | );
31 | assert_eq!(
32 | expected_offset,
33 | nv_certify_info.offset(),
34 | "The NvCertifyInfo converted from TPMS_NV_CERTIFY_INFO did not contain correct value for 'offset'",
35 | );
36 | assert_eq!(
37 | &expected_nv_contents,
38 | nv_certify_info.nv_contents(),
39 | "The NvCertifyInfo converted from TPMS_NV_CERTIFY_INFO did not contain correct value for 'nv contents'",
40 | );
41 |
42 | let actual_tpms_nv_certify_info: TPMS_NV_CERTIFY_INFO = nv_certify_info.into();
43 |
44 | crate::common::ensure_tpms_nv_certify_info_equality(
45 | &expected_tpms_nv_certify_info,
46 | &actual_tpms_nv_certify_info,
47 | );
48 | }
49 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/pcr_tests/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod pcr_select_size_tests;
4 | mod pcr_select_tests;
5 | mod pcr_selection_tests;
6 | mod pcr_slot_tests;
7 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/quote_info_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use std::convert::TryFrom;
5 | use tss_esapi::{
6 | interface_types::algorithm::HashingAlgorithm,
7 | structures::{Digest, PcrSelectionListBuilder, PcrSlot, QuoteInfo},
8 | tss2_esys::TPMS_QUOTE_INFO,
9 | };
10 |
11 | #[test]
12 | fn test_conversion() {
13 | let expected_pcr_selection = PcrSelectionListBuilder::new()
14 | .with_selection(
15 | HashingAlgorithm::Sha256,
16 | &[
17 | PcrSlot::Slot1,
18 | PcrSlot::Slot2,
19 | PcrSlot::Slot3,
20 | PcrSlot::Slot4,
21 | ],
22 | )
23 | .build()
24 | .expect("Failed to pcr selection list");
25 | let expected_pcr_digest = Digest::try_from(vec![0xffu8; 32]).expect("Failed to create digest");
26 | let expected_tpms_quote_info = TPMS_QUOTE_INFO {
27 | pcrSelect: expected_pcr_selection.clone().into(),
28 | pcrDigest: expected_pcr_digest.clone().into(),
29 | };
30 | let quote_info = QuoteInfo::try_from(expected_tpms_quote_info)
31 | .expect("Failed to create QuoteInfo from TPMS_QUOTE_INFO");
32 |
33 | assert_eq!(
34 | &expected_pcr_selection,
35 | quote_info.pcr_selection(),
36 | "The QuoteInfo converted from TPMS_QUOTE_INFO did not contain the expected PCR selection"
37 | );
38 | assert_eq!(
39 | &expected_pcr_digest,
40 | quote_info.pcr_digest(),
41 | "The QuoteInfo converted from TPMS_QUOTE_INFO did not contain the expected PCR digest"
42 | );
43 |
44 | let actual_tpms_quote_info: TPMS_QUOTE_INFO = quote_info.into();
45 |
46 | crate::common::ensure_tpms_quote_info_equality(
47 | &expected_tpms_quote_info,
48 | &actual_tpms_quote_info,
49 | );
50 | }
51 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/session_audit_info_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use std::convert::TryFrom;
5 | use tss_esapi::{
6 | interface_types::YesNo,
7 | structures::{Digest, SessionAuditInfo},
8 | tss2_esys::TPMS_SESSION_AUDIT_INFO,
9 | };
10 |
11 | #[test]
12 | fn test_conversion() {
13 | let expected_exclusive_session = YesNo::Yes;
14 | let expected_session_digest =
15 | Digest::try_from(vec![0xffu8; 32]).expect("Failed to session digest");
16 | let expected_tpms_session_audit_info = TPMS_SESSION_AUDIT_INFO {
17 | exclusiveSession: expected_exclusive_session.into(),
18 | sessionDigest: expected_session_digest.clone().into(),
19 | };
20 |
21 | let session_audit_info = SessionAuditInfo::try_from(expected_tpms_session_audit_info)
22 | .expect("Unable to convert TPMS_SESSION_AUDIT_INFO into SessionAuditInfo");
23 |
24 | assert_eq!(
25 | bool::from(expected_exclusive_session),
26 | session_audit_info.exlusive_session(),
27 | "The SessionAuditInfo that was converted from TPMS_SESSION_AUDIT_INFO, did not contain the expected value for 'exclusive session'",
28 | );
29 |
30 | assert_eq!(
31 | &expected_session_digest,
32 | session_audit_info.session_digest(),
33 | "The SessionAuditInfo that was converted from TPMS_SESSION_AUDIT_INFO, did not contain the expected value for 'session digest'",
34 | );
35 |
36 | let actual_tpms_session_audit_info: TPMS_SESSION_AUDIT_INFO = session_audit_info.into();
37 |
38 | crate::common::ensure_tpms_session_audit_info_equality(
39 | &expected_tpms_session_audit_info,
40 | &actual_tpms_session_audit_info,
41 | );
42 | }
43 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/tagged_pcr_select_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use std::convert::TryInto;
4 | use tss_esapi::{
5 | constants::PcrPropertyTag,
6 | structures::{PcrSelectSize, PcrSlot, TaggedPcrSelect},
7 | tss2_esys::TPMS_TAGGED_PCR_SELECT,
8 | };
9 |
10 | #[test]
11 | fn test_conversions() {
12 | let expected_pcr_property_tag = PcrPropertyTag::ExtendL0;
13 | let expected_size_of_select = PcrSelectSize::ThreeOctets;
14 | let expected_pcr_slots = vec![
15 | PcrSlot::Slot1,
16 | PcrSlot::Slot8,
17 | PcrSlot::Slot16,
18 | PcrSlot::Slot17,
19 | ]; // [2, 1, 3, X], X doesn't matter because size of select is three octets
20 |
21 | let expected_tpms_tagged_pcr_select = TPMS_TAGGED_PCR_SELECT {
22 | tag: expected_pcr_property_tag.into(),
23 | sizeofSelect: expected_size_of_select.as_u8(),
24 | pcrSelect: [2, 1, 3, 0],
25 | };
26 |
27 | let tagged_pcr_select: TaggedPcrSelect = expected_tpms_tagged_pcr_select
28 | .try_into()
29 | .expect("Failed to convert TPMS_TAGGED_PCR_SELECT into TaggedPcrSelect");
30 |
31 | assert_eq!(
32 | expected_pcr_property_tag,
33 | tagged_pcr_select.pcr_property_tag(),
34 | "Converted TaggedPcrSelect did not contain the expected pcr property tag value"
35 | );
36 |
37 | assert_eq!(
38 | expected_size_of_select,
39 | tagged_pcr_select.size_of_select(),
40 | "Converted TaggedPcrSelect did not contain the expected size of select value"
41 | );
42 |
43 | assert_eq!(
44 | expected_pcr_slots,
45 | tagged_pcr_select.selected_pcrs(),
46 | "Converted TaggedPcrSelect did not contain the expected PCR slot values"
47 | );
48 |
49 | let actual_tpms_tagged_pcr_select: TPMS_TAGGED_PCR_SELECT = tagged_pcr_select.into();
50 |
51 | crate::common::ensure_tpms_tagged_pcr_select_equality(
52 | &expected_tpms_tagged_pcr_select,
53 | &actual_tpms_tagged_pcr_select,
54 | );
55 | }
56 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/tagged_property_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use tss_esapi::{
4 | constants::PropertyTag, structures::TaggedProperty, tss2_esys::TPMS_TAGGED_PROPERTY,
5 | };
6 |
7 | use std::convert::TryInto;
8 |
9 | #[test]
10 | fn test_conversions() {
11 | let expected_property = PropertyTag::AlgorithmSet;
12 | let expected_value = 1u32;
13 |
14 | let expected_tpms_tagged_property = TPMS_TAGGED_PROPERTY {
15 | property: expected_property.into(),
16 | value: expected_value,
17 | };
18 |
19 | let tagged_property: TaggedProperty = expected_tpms_tagged_property
20 | .try_into()
21 | .expect("Failed to convert TPMS_TAGGED_PROPERTY");
22 |
23 | assert_eq!(
24 | tagged_property.property(),
25 | expected_property,
26 | "Converted TaggedProperty did not contain the expected property value"
27 | );
28 |
29 | assert_eq!(
30 | tagged_property.value(),
31 | expected_value,
32 | "Converted TaggedProperty did not contain expected value in the value field",
33 | );
34 |
35 | let actual_tpms_tagged_property: TPMS_TAGGED_PROPERTY = tagged_property.into();
36 |
37 | crate::common::ensure_tpms_tagged_property_equality(
38 | &expected_tpms_tagged_property,
39 | &actual_tpms_tagged_property,
40 | );
41 | }
42 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/tagged_tests/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod parameters_tests;
4 | mod public;
5 | mod public_ecc_parameters_tests;
6 | mod public_rsa_exponent_tests;
7 | mod public_rsa_parameters_tests;
8 | mod sensitive;
9 | mod signature;
10 | mod symmetric_definition_object_tests;
11 | mod symmetric_definition_tests;
12 | mod tagged_ecc_scheme_tests;
13 | mod tagged_key_derivation_function_scheme_tests;
14 | mod tagged_keyed_hash_scheme_tests;
15 | mod tagged_rsa_decryption_scheme_tests;
16 | mod tagged_rsa_scheme_tests;
17 | mod tagged_signature_scheme_tests;
18 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/tagged_tests/public.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use std::convert::TryFrom;
5 | use tss_esapi::{
6 | structures::{Public, PublicBuffer},
7 | tss2_esys::TPM2B_PUBLIC,
8 | };
9 |
10 | #[test]
11 | fn marshall_unmarshall() {
12 | crate::common::publics()
13 | .iter()
14 | .for_each(crate::common::check_marshall_unmarshall);
15 | }
16 |
17 | #[test]
18 | #[cfg(feature = "serde")]
19 | fn serialise_deserialise() {
20 | crate::common::publics()
21 | .iter()
22 | .for_each(crate::common::check_serialise_deserialise);
23 | }
24 |
25 | #[test]
26 | fn tpm2b_conversion() {
27 | crate::common::publics().iter().for_each(|public| {
28 | let public = public.clone();
29 | let tpm2b = TPM2B_PUBLIC::try_from(public.clone())
30 | .expect("Failed to convert from Public to TPM2B_PUBLIC");
31 | let buf = PublicBuffer::try_from(public.clone())
32 | .expect("Failed to convert from Public to PublicBuffer");
33 | assert_eq!(
34 | buf,
35 | PublicBuffer::try_from(tpm2b)
36 | .expect("Failed to convert from PublicBuffer to TPM2B_PUBLIC")
37 | );
38 | assert_eq!(
39 | public,
40 | Public::try_from(buf).expect("Failed to convert from PublicBuffer to Public")
41 | );
42 | assert_eq!(
43 | public,
44 | Public::try_from(tpm2b).expect("Failed to convert from TPM2B_PUBLIC to Public")
45 | )
46 | });
47 | }
48 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/tagged_tests/public_rsa_exponent_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use tss_esapi::structures::RsaExponent;
4 |
5 | #[test]
6 | fn rsa_exponent_value_test() {
7 | let expected_value = 97;
8 |
9 | let rsa_exponent = RsaExponent::create(expected_value).unwrap_or_else(|_| {
10 | panic!(
11 | "Failed to create a RsaExponent from the value {}",
12 | expected_value
13 | )
14 | });
15 |
16 | assert_eq!(expected_value, rsa_exponent.value());
17 | }
18 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/tagged_tests/public_rsa_parameters_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use tss_esapi::interface_types::key_bits::RsaKeyBits;
5 | use tss_esapi::structures::*;
6 | use tss_esapi::Error;
7 | use tss_esapi::WrapperErrorKind;
8 |
9 | #[test]
10 | fn test_restricted_decryption_with_default_symmetric() {
11 | assert!(matches!(
12 | PublicRsaParametersBuilder::new()
13 | .with_restricted(true)
14 | .with_is_decryption_key(true)
15 | .with_scheme(RsaScheme::Null)
16 | .with_key_bits(RsaKeyBits::Rsa1024)
17 | .build(),
18 | Err(Error::WrapperError(WrapperErrorKind::ParamsMissing))
19 | ));
20 | }
21 |
22 | #[test]
23 | fn test_restricted_decryption_with_null_symmetric() {
24 | assert!(matches!(
25 | PublicRsaParametersBuilder::new()
26 | .with_restricted(true)
27 | .with_is_decryption_key(true)
28 | .with_scheme(RsaScheme::Null)
29 | .with_symmetric(SymmetricDefinitionObject::Null)
30 | .with_key_bits(RsaKeyBits::Rsa1024)
31 | .build(),
32 | Err(Error::WrapperError(WrapperErrorKind::InconsistentParams))
33 | ));
34 | }
35 |
36 | #[test]
37 | fn test_restricted_decryption_with_wrong_symmetric() {
38 | assert!(PublicRsaParametersBuilder::new()
39 | .with_restricted(true)
40 | .with_is_decryption_key(true)
41 | .with_scheme(RsaScheme::Null)
42 | .with_symmetric(SymmetricDefinitionObject::AES_128_CFB)
43 | .with_key_bits(RsaKeyBits::Rsa1024)
44 | .build()
45 | .is_ok());
46 | }
47 |
48 | #[test]
49 | fn test_signing_with_default_symmetric() {
50 | assert!(PublicRsaParametersBuilder::new()
51 | .with_restricted(false)
52 | .with_is_decryption_key(false)
53 | .with_is_signing_key(true)
54 | .with_scheme(RsaScheme::Null)
55 | .with_symmetric(SymmetricDefinitionObject::Null)
56 | .with_key_bits(RsaKeyBits::Rsa1024)
57 | .build()
58 | .is_ok());
59 | }
60 |
61 | #[test]
62 | fn test_signing_with_wrong_symmetric() {
63 | assert!(matches!(
64 | PublicRsaParametersBuilder::new()
65 | .with_restricted(false)
66 | .with_is_decryption_key(false)
67 | .with_is_signing_key(true)
68 | .with_scheme(RsaScheme::Null)
69 | .with_symmetric(SymmetricDefinitionObject::AES_128_CFB)
70 | .with_key_bits(RsaKeyBits::Rsa1024)
71 | .build(),
72 | Err(Error::WrapperError(WrapperErrorKind::InconsistentParams))
73 | ));
74 | }
75 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/tagged_tests/sensitive.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use std::convert::TryFrom;
5 | use tss_esapi::{
6 | structures::{Sensitive, SensitiveBuffer},
7 | tss2_esys::TPM2B_SENSITIVE,
8 | };
9 |
10 | #[test]
11 | fn marshall_unmarshall() {
12 | crate::common::sensitives()
13 | .iter()
14 | .for_each(crate::common::check_marshall_unmarshall);
15 | }
16 |
17 | #[test]
18 | fn tpm2b_conversion() {
19 | crate::common::sensitives().iter().for_each(|sensitive| {
20 | let sensitive = sensitive.clone();
21 | let tpm2b = TPM2B_SENSITIVE::try_from(sensitive.clone())
22 | .expect("Failed to convert from Sensitive to TPM2B_SENSITIVE");
23 | let buf = SensitiveBuffer::try_from(sensitive.clone())
24 | .expect("Failed to convert from Sensitive to SensitiveBuffer");
25 | assert_eq!(
26 | buf,
27 | SensitiveBuffer::try_from(tpm2b)
28 | .expect("Failed to convert from SensitiveBuffer to TPM2B_SENSITIVE")
29 | );
30 | assert_eq!(
31 | sensitive,
32 | Sensitive::try_from(buf).expect("Failed to convert from SensitiveBuffer to Sensitive")
33 | );
34 | assert_eq!(
35 | sensitive,
36 | Sensitive::try_from(tpm2b)
37 | .expect("Failed to convert from TPM2B_SENSITIVE to Sensitive")
38 | )
39 | });
40 | }
41 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/tagged_tests/signature.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use std::convert::TryFrom;
5 | use tss_esapi::{structures::Signature, tss2_esys::TPMT_SIGNATURE};
6 |
7 | #[test]
8 | fn marshall_unmarshall() {
9 | crate::common::signatures()
10 | .iter()
11 | .for_each(crate::common::check_marshall_unmarshall);
12 | }
13 |
14 | #[test]
15 | fn tpmt_conversion() {
16 | crate::common::signatures().iter().for_each(|signature| {
17 | let signature = signature.clone();
18 | let tpmt = TPMT_SIGNATURE::try_from(signature.clone())
19 | .expect("Failed conversion to TPMT_SIGNATURE");
20 | assert_eq!(
21 | signature,
22 | Signature::try_from(tpmt).expect("Failed conversion from TPMT_SIGNATURE")
23 | );
24 | });
25 | }
26 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/time_attest_info_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use std::convert::TryFrom;
5 | use tss_esapi::{
6 | interface_types::YesNo,
7 | structures::{TimeAttestInfo, TimeInfo},
8 | tss2_esys::{TPMS_CLOCK_INFO, TPMS_TIME_ATTEST_INFO, TPMS_TIME_INFO},
9 | };
10 |
11 | #[test]
12 | fn test_conversion() {
13 | let expected_time_info = TimeInfo::try_from(TPMS_TIME_INFO {
14 | time: 12u64,
15 | clockInfo: TPMS_CLOCK_INFO {
16 | clock: 1u64,
17 | resetCount: 2u32,
18 | restartCount: 3u32,
19 | safe: YesNo::Yes.into(),
20 | },
21 | })
22 | .expect("Failed to convert TPMS_TIME_INFO into TimeInfo");
23 | let expected_firmware_version = 0xfffffu64;
24 | let expected_tpms_time_attest_info = TPMS_TIME_ATTEST_INFO {
25 | time: expected_time_info.into(),
26 | firmwareVersion: expected_firmware_version,
27 | };
28 |
29 | let time_attest_info = TimeAttestInfo::try_from(expected_tpms_time_attest_info)
30 | .expect("Unable to convert TPMS_TIME_ATTEST_INFO into TimeAttestInfo");
31 |
32 | assert_eq!(
33 | &expected_time_info,
34 | time_attest_info.time_info(),
35 | "The TimeAttestInfo that was converted from TPMS_TIME_ATTEST_INFO, did not contain the expected value for 'time info'",
36 | );
37 | assert_eq!(
38 | expected_firmware_version,
39 | time_attest_info.firmware_version(),
40 | "The TimeAttestInfo that was converted from TPMS_TIME_ATTEST_INFO, did not contain the expected value for 'firmware version'",
41 | );
42 |
43 | let actual_tpms_time_attest_info: TPMS_TIME_ATTEST_INFO = time_attest_info.into();
44 |
45 | crate::common::ensure_tpms_time_attest_info_equality(
46 | &expected_tpms_time_attest_info,
47 | &actual_tpms_time_attest_info,
48 | );
49 | }
50 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/time_info_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use tss_esapi::{
5 | interface_types::YesNo,
6 | structures::{ClockInfo, TimeInfo},
7 | tss2_esys::{TPMS_CLOCK_INFO, TPMS_TIME_INFO},
8 | };
9 |
10 | use std::convert::TryFrom;
11 |
12 | #[test]
13 | fn test_conversion() {
14 | let expected_time = 1u64;
15 | let expected_clock_info = ClockInfo::try_from(TPMS_CLOCK_INFO {
16 | clock: 1u64,
17 | resetCount: 2u32,
18 | restartCount: 3u32,
19 | safe: YesNo::Yes.into(),
20 | })
21 | .expect("Failed to create ClockInfo");
22 | let expected_tpms_time_info = TPMS_TIME_INFO {
23 | time: expected_time,
24 | clockInfo: expected_clock_info.into(),
25 | };
26 |
27 | let time_info = TimeInfo::try_from(expected_tpms_time_info)
28 | .expect("Failed to convert TPMS_TIME_INFO into TimeInfo");
29 |
30 | assert_eq!(
31 | expected_time,
32 | time_info.time(),
33 | "The TimeInfo that was converted from TPMS_TIME_INFO, did not contain the expected value for time",
34 | );
35 | assert_eq!(
36 | &expected_clock_info,
37 | time_info.clock_info(),
38 | "The TimeInfo that was converted from TPMS_TIME_INFO, did not contain the expected value for 'clock info'",
39 | );
40 |
41 | let actual_tpms_time_info = time_info.into();
42 | crate::common::ensure_tpms_time_info_equality(&expected_tpms_time_info, &actual_tpms_time_info);
43 | }
44 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/structures_tests/tpm_context_tests.rs:
--------------------------------------------------------------------------------
1 | use std::convert::TryFrom;
2 | use tss_esapi::{
3 | handles::TpmHandle,
4 | interface_types::{data_handles::Saved, reserved_handles::Hierarchy},
5 | structures::{SavedTpmContext, TpmContextData},
6 | tss2_esys::TPMS_CONTEXT,
7 | };
8 |
9 | #[test]
10 | fn test_valid_conversions() {
11 | let expected_sequence = 13243546576879u64;
12 | let expected_saved_handle = Saved::Transient;
13 | let expected_hierarchy = Hierarchy::Owner;
14 | let expected_context_blob =
15 | TpmContextData::try_from(vec![1u8, 2u8, 12u8, 23u8, 45u8, 56u8, 98u8])
16 | .expect("It should be possible to create TpmContextData buffer type from bytes.");
17 | let expected_tpms_context = TPMS_CONTEXT {
18 | sequence: expected_sequence,
19 | savedHandle: expected_saved_handle.into(),
20 | hierarchy: TpmHandle::from(expected_hierarchy).into(),
21 | contextBlob: expected_context_blob.clone().into(),
22 | };
23 | // Conversion TPMS_CONTEXT -> SavedTpmContext
24 | let actual_saved_tpm_context = SavedTpmContext::try_from(expected_tpms_context).expect(
25 | "It should be possible to convert a valid TPMS_CONTEXT structure into a SavedTpmContext",
26 | );
27 | assert_eq!(expected_sequence, actual_saved_tpm_context.sequence());
28 | assert_eq!(
29 | expected_saved_handle,
30 | actual_saved_tpm_context.saved_handle()
31 | );
32 | assert_eq!(expected_hierarchy, actual_saved_tpm_context.hierarchy());
33 | assert_eq!(
34 | expected_context_blob,
35 | *actual_saved_tpm_context.context_blob()
36 | );
37 | // SavedTpmContext -> TPMS_CONTEXT
38 | let actual_tpms_context = TPMS_CONTEXT::from(actual_saved_tpm_context);
39 | crate::common::ensure_tpms_context_equality(&expected_tpms_context, &actual_tpms_context);
40 | }
41 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/tcti_ldr_tests/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use std::env;
5 | use std::str::FromStr;
6 | use tss_esapi::tcti_ldr::TctiNameConf;
7 |
8 | #[allow(dead_code)]
9 | pub fn name_conf() -> TctiNameConf {
10 | match env::var("TEST_TCTI") {
11 | Err(_) => TctiNameConf::Mssim(Default::default()),
12 | Ok(tctistr) => TctiNameConf::from_str(&tctistr).expect("Error parsing TEST_TCTI"),
13 | }
14 | }
15 |
16 | mod tcti_context_tests;
17 | mod tcti_info_tests;
18 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/tcti_ldr_tests/tcti_context_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use tss_esapi::tcti_ldr::TctiContext;
4 |
5 | #[test]
6 | fn new_context() {
7 | let _context = TctiContext::initialize(crate::tcti_ldr_tests::name_conf()).unwrap();
8 | }
9 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/tcti_ldr_tests/tcti_info_tests.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | use tss_esapi::tcti_ldr::TctiInfo;
4 |
5 | #[test]
6 | fn new_info() {
7 | let info = TctiInfo::get_info(crate::tcti_ldr_tests::name_conf()).unwrap();
8 | let _version = info.version();
9 | let _name = info.name();
10 | let _description = info.description();
11 | let _config_help = info.config_help();
12 | }
13 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/traits.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2023 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | #[test]
5 | fn test_u32_marshall_unmarshall() {
6 | let val = 0xdeadbeef_u32;
7 | crate::common::check_marshall_unmarshall(&val);
8 | crate::common::check_marshall_unmarshall_offset(&val);
9 | }
10 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/utils_tests/get_tpm_vendor_test.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 |
4 | use tss_esapi::utils;
5 |
6 | // Copyright 2021 Contributors to the Parsec project.
7 | // SPDX-License-Identifier: Apache-2.0
8 | use crate::common::create_ctx_without_session;
9 |
10 | #[test]
11 | fn get_tpm_vendor() {
12 | let mut context = create_ctx_without_session();
13 |
14 | utils::get_tpm_vendor(&mut context).unwrap();
15 | }
16 |
--------------------------------------------------------------------------------
/tss-esapi/tests/integration_tests/utils_tests/mod.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2021 Contributors to the Parsec project.
2 | // SPDX-License-Identifier: Apache-2.0
3 | mod get_tpm_vendor_test;
4 |
--------------------------------------------------------------------------------
/tss-esapi/tests/lint-checks.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2023 Contributors to the Parsec project.
4 | # SPDX-License-Identifier: Apache-2.0
5 |
6 | # This script executes static checks for the tss-esapi crate.
7 |
8 | set -euf -o pipefail
9 |
10 | #################################################
11 | # Change rust toolchain version
12 | #################################################
13 | if [[ ! -z ${RUST_TOOLCHAIN_VERSION:+x} ]]; then
14 | rustup override set ${RUST_TOOLCHAIN_VERSION}
15 | # Use the frozen Cargo lock to prevent any drift from MSRV being upgraded
16 | # underneath our feet.
17 | cp tests/Cargo.lock.frozen ../Cargo.lock
18 | fi
19 |
20 | ##################
21 | # Execute clippy #
22 | ##################
23 | cargo clippy --all-targets --all-features -- -D clippy::all -D clippy::cargo
--------------------------------------------------------------------------------
/tss-esapi/tests/pkg-config:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | export PKG_CONFIG_PATH=
4 | export PKG_CONFIG_LIBDIR=${SYSROOT}/usr/lib/pkgconfig:${SYSROOT}/usr/share/pkgconfig:$(SYSROOT)/usr/local/lib/pkgconfig
5 | export PKG_CONFIG_SYSROOT_DIR=${SYSROOT}
6 |
7 | exec pkg-config "$@"
8 |
--------------------------------------------------------------------------------
/tss-esapi/tests/valgrind.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2022 Contributors to the Parsec project.
4 | # SPDX-License-Identifier: Apache-2.0
5 |
6 | # Script for running valgrind against the set of tests
7 | # Intended for running in the Ubuntu container
8 |
9 | set -euf -o pipefail
10 |
11 | if [[ ! -z ${RUST_TOOLCHAIN_VERSION:+x} ]]; then
12 | rustup override set ${RUST_TOOLCHAIN_VERSION}
13 | fi
14 |
15 | #################################
16 | # Run the TPM simulation server #
17 | #################################
18 | tpm_server &
19 | sleep 5
20 | tpm2_startup -c -T mssim
21 |
22 | ##########################
23 | # Install cargo-valgrind #
24 | ##########################
25 | apt update
26 | apt install -y valgrind
27 | cargo install cargo-valgrind
28 |
29 | #################
30 | # Run the tests #
31 | #################
32 | TEST_TCTI=mssim: RUST_BACKTRACE=1 RUST_LOG=info cargo valgrind test -- --test-threads=1 --nocapture
33 |
--------------------------------------------------------------------------------