├── .cargo └── config.toml ├── .github ├── dependabot.yml └── workflows │ ├── codeql.yml │ ├── deny.yml │ ├── format.yml │ ├── integration.yml │ ├── main.yml │ ├── oss-fuzz.yml │ ├── scorecard.yml │ └── unittest.yml ├── .gitignore ├── .gitmodules ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Cargo.lock ├── Cargo.toml ├── Dockerfile ├── README.md ├── config ├── intel_root_sbx.der ├── manifest_info.json ├── metadata.json └── shim_layout.json ├── deps └── rust-tpm-20-ref │ ├── Cargo.toml │ ├── openssl-stubs │ ├── CrtLibSupport.h │ ├── arch │ │ └── x86_64 │ │ │ └── base.h │ ├── openssl-how-to.md │ ├── openssl_sources.rs.template │ ├── process_openssl.pl │ ├── rand_pool.c │ └── std-include │ │ ├── arpa │ │ ├── inet.h │ │ └── nameser.h │ │ ├── assert.h │ │ ├── crypto │ │ └── dso_conf.h │ │ ├── ctype.h │ │ ├── errno.h │ │ ├── fcntl.h │ │ ├── internal │ │ └── dso_conf.h │ │ ├── limits.h │ │ ├── memory.h │ │ ├── netinet │ │ └── in.h │ │ ├── stdarg.h │ │ ├── stddef.h │ │ ├── stdio.h │ │ ├── stdlib.h │ │ ├── string.h │ │ ├── strings.h │ │ ├── sys │ │ ├── param.h │ │ ├── shm.h │ │ ├── socket.h │ │ ├── stat.h │ │ ├── syscall.h │ │ ├── time.h │ │ ├── types.h │ │ └── utsname.h │ │ ├── syslog.h │ │ ├── time.h │ │ └── unistd.h │ ├── patches │ ├── BaseTypes.diff │ ├── nv.diff │ └── openssl3.1.1.diff │ ├── sh_script │ ├── build.sh │ ├── pre-build.sh │ └── rename_smallc_symbols │ ├── smallc │ ├── Makefile │ ├── config.mak │ ├── include │ │ └── .gitignore │ └── src │ │ ├── exit │ │ ├── abort.c │ │ └── assert.c │ │ ├── legacy │ │ └── err.c │ │ ├── malloc │ │ ├── free.c │ │ ├── lite_malloc.c │ │ ├── mallocng │ │ │ ├── free.c │ │ │ └── malloc.c │ │ └── realloc.c │ │ ├── prng │ │ └── rand.c │ │ ├── stdio │ │ ├── printf.c │ │ └── vsnprintf.c │ │ ├── stdlib │ │ └── qsort_nr.c │ │ └── time │ │ └── time.c │ ├── src │ └── lib.rs │ └── tpm │ ├── Makefile │ ├── arch │ └── x86_64 │ │ └── base.h │ ├── include │ └── TpmProfile.h │ └── platform │ ├── include │ ├── Platform.h │ ├── PlatformACT.h │ ├── PlatformClock.h │ ├── PlatformData.h │ └── prototypes │ │ └── Platform_fp.h │ └── src │ ├── Cancel.c │ ├── Clock.c │ ├── DebugHelpers.c │ ├── Entropy.c │ ├── LocalityPlat.c │ ├── NVMem.c │ ├── PPPlat.c │ ├── PlatformACT.c │ ├── PlatformData.c │ ├── PowerPlat.c │ ├── RunCommand.c │ └── Unique.c ├── doc ├── Intel TD based virtual TPM Design Guide Rev 0.7.8.pdf ├── integration-test.md ├── tpm2_pcrread.png ├── verify-vtpm-features.md └── vtpm-overview.png ├── license.md ├── rust-toolchain ├── security.md ├── sh_script ├── build.sh ├── conf │ └── pyproject.toml ├── docker.sh ├── ek_cert.sh ├── fuzzing.sh ├── integration_test.py ├── launch_user_td.sh ├── launch_vtpm_td.sh ├── pre-build.sh ├── pytest.ini ├── secure_boot │ ├── FB_NO_REBOOT.bin │ ├── SecureBootEnable.bin │ ├── key_gen.sh │ ├── secure_boot.py │ └── var_enroll.py ├── unit_test.sh └── utils.py └── src ├── attestation ├── Cargo.toml ├── build.rs └── src │ ├── attest.rs │ ├── binding.rs │ ├── ghci.rs │ ├── lib.rs │ ├── null.rs │ └── root_ca.rs ├── crypto ├── Cargo.toml ├── fuzz │ ├── Cargo.toml │ ├── fuzz_targets │ │ ├── afl_certchain.rs │ │ └── certchain.rs │ └── seeds │ │ └── certchain │ │ └── cert_chain └── src │ ├── ek_cert.rs │ ├── lib.rs │ ├── resolve.rs │ ├── td_report.rs │ └── x509.rs ├── eventlog ├── Cargo.toml └── src │ ├── eventlog.rs │ └── lib.rs ├── global ├── Cargo.toml └── src │ ├── lib.rs │ ├── spdm.rs │ └── tpm.rs ├── protocol ├── Cargo.toml └── src │ ├── lib.rs │ ├── report_status │ ├── command.rs │ ├── mod.rs │ └── response.rs │ ├── service │ ├── command.rs │ ├── mod.rs │ └── response.rs │ └── wait_for_request │ ├── command.rs │ ├── mod.rs │ └── response.rs ├── spdm ├── Cargo.toml └── src │ ├── crypto_callback.rs │ ├── lib.rs │ ├── vtpm_io_transport.rs │ └── vtpm_transport_encap.rs ├── tdtunnel ├── Cargo.toml └── src │ ├── interrupt.rs │ ├── lib.rs │ └── td_tunnel.rs ├── tpm ├── Cargo.toml ├── build.rs └── src │ ├── cty.rs │ ├── lib.rs │ ├── rtc.rs │ ├── std_lib.rs │ ├── tpm2_ca_cert.rs │ ├── tpm2_cmd_rsp │ ├── command.rs │ ├── getcaps.rs │ ├── mod.rs │ ├── response.rs │ ├── shutdown.rs │ └── startup.rs │ ├── tpm2_digests.rs │ ├── tpm2_provision.rs │ └── tpm2_sys.rs └── vtpmtd ├── .gitignore ├── Cargo.toml └── src ├── main.rs └── vtpm ├── mod.rs ├── spdm_cbs.rs ├── spdm_connection.rs └── spdm_server.rs /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [target.'cfg(target_os = "none")'] 2 | runner = "cargo run --package test-runner-server --" 3 | 4 | [alias] 5 | kbuild = "build --target x86_64-custom.json -Zbuild-std=core -Zbuild-std-features=compiler-builtins-mem" 6 | kimage = "run --target x86_64-custom.json -Zbuild-std=core -Zbuild-std-features=compiler-builtins-mem -- --no-run" 7 | krun = "run --target x86_64-custom.json -Zbuild-std=core -Zbuild-std-features=compiler-builtins-mem" 8 | ktest = "xtest --target x86_64-custom.json" 9 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | 4 | - package-ecosystem: "cargo" 5 | directory: "/" 6 | schedule: 7 | # Check for updates to cargo dependencies every week 8 | interval: "weekly" 9 | open-pull-requests-limit: 1 10 | allow: 11 | - dependency-type: direct 12 | - dependency-type: indirect 13 | 14 | - package-ecosystem: "github-actions" 15 | directory: "/" 16 | schedule: 17 | # Check for updates to GitHub Actions every week 18 | interval: "weekly" 19 | 20 | - package-ecosystem: docker 21 | directory: / 22 | schedule: 23 | interval: daily 24 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: ["main"] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: ["main"] 20 | schedule: 21 | - cron: "0 0 * * 1" 22 | 23 | permissions: 24 | contents: read 25 | 26 | jobs: 27 | analyze: 28 | name: Analyze 29 | runs-on: ubuntu-latest 30 | permissions: 31 | actions: read 32 | contents: read 33 | security-events: write 34 | 35 | strategy: 36 | fail-fast: false 37 | matrix: 38 | language: ["python"] 39 | # CodeQL supports [ $supported-codeql-languages ] 40 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support 41 | 42 | steps: 43 | - name: Harden Runner 44 | uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0 45 | with: 46 | egress-policy: audit 47 | 48 | - name: Checkout repository 49 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 50 | 51 | # Initializes the CodeQL tools for scanning. 52 | - name: Initialize CodeQL 53 | uses: github/codeql-action/init@28deaeda66b76a05916b6923827895f2b14ab387 # v3.28.16 54 | with: 55 | languages: ${{ matrix.language }} 56 | # If you wish to specify custom queries, you can do so here or in a config file. 57 | # By default, queries listed here will override any specified in a config file. 58 | # Prefix the list here with "+" to use these queries and those in the config file. 59 | 60 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 61 | # If this step fails, then you should remove it and run the build manually (see below) 62 | - name: Autobuild 63 | uses: github/codeql-action/autobuild@28deaeda66b76a05916b6923827895f2b14ab387 # v3.28.16 64 | 65 | # ℹ️ Command-line programs to run using the OS shell. 66 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun 67 | 68 | # If the Autobuild fails above, remove it and uncomment the following three lines. 69 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. 70 | 71 | # - run: | 72 | # echo "Run, Build Application using script" 73 | # ./location_of_script_within_repo/buildscript.sh 74 | 75 | - name: Perform CodeQL Analysis 76 | uses: github/codeql-action/analyze@28deaeda66b76a05916b6923827895f2b14ab387 # v3.28.16 77 | with: 78 | category: "/language:${{matrix.language}}" 79 | -------------------------------------------------------------------------------- /.github/workflows/deny.yml: -------------------------------------------------------------------------------- 1 | name: cargo-deny 2 | on: 3 | push: 4 | paths-ignore: 5 | - "**.md" 6 | pull_request: 7 | paths-ignore: 8 | - "**.md" 9 | schedule: 10 | - cron: '0 0 * * *' 11 | 12 | permissions: 13 | contents: read 14 | 15 | jobs: 16 | cargo-deny: 17 | runs-on: ubuntu-latest 18 | strategy: 19 | matrix: 20 | checks: 21 | - advisories 22 | - sources 23 | - bans 24 | 25 | # Prevent sudden announcement of a new advisory from failing ci: 26 | continue-on-error: ${{ matrix.checks == 'sources' }} 27 | 28 | steps: 29 | - name: Harden Runner 30 | uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0 31 | with: 32 | egress-policy: audit 33 | 34 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 35 | - run: git config --global http.postBuffer 524288000 36 | - run: git config --global http.sslVerify "false" 37 | - run: git submodule update --init --recursive --depth 1 38 | - run: bash sh_script/pre-build.sh 39 | - uses: EmbarkStudios/cargo-deny-action@34899fc7ba81ca6268d5947a7a16b4649013fea1 # v2.0.11 40 | with: 41 | command: check ${{ matrix.checks }} -------------------------------------------------------------------------------- /.github/workflows/format.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | paths-ignore: 4 | - "**.md" 5 | pull_request: 6 | paths-ignore: 7 | - "**.md" 8 | 9 | name: Format and Clippy 10 | 11 | env: 12 | AS: nasm 13 | AR: llvm-ar 14 | CC: clang 15 | 16 | permissions: 17 | contents: read 18 | 19 | jobs: 20 | clippy: 21 | name: Clippy 22 | runs-on: ubuntu-22.04 23 | steps: 24 | - name: Harden Runner 25 | uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0 26 | with: 27 | egress-policy: audit 28 | 29 | - name: Checkout sources 30 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 31 | 32 | - name: Initialize and update submodules 33 | run: | 34 | git config --global http.postBuffer 524288000 35 | git config --global http.sslVerify "false" 36 | git submodule update --init --recursive --depth 1 37 | 38 | # Install first since it's needed to build NASM 39 | - name: Install LLVM and Clang 40 | uses: KyleMayes/install-llvm-action@6ba6e2cd3813def9879be378609d87cb3ef3bac3 # v2.0.6 41 | with: 42 | version: "10.0" 43 | directory: ${{ runner.temp }}/llvm 44 | 45 | - name: Install libtinfo5 46 | run: sudo apt-get update -y && sudo apt-get install libtinfo5 -y 47 | 48 | - name: install NASM 49 | uses: ilammy/setup-nasm@72793074d3c8cdda771dba85f6deafe00623038b # v1.5.2 50 | 51 | - name: Install toolchain with clippy available 52 | uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af # v1.0.7 53 | with: 54 | profile: minimal 55 | toolchain: nightly-2023-12-31 56 | override: true 57 | components: clippy 58 | 59 | - name: Preparation Work 60 | run: bash sh_script/pre-build.sh 61 | 62 | - name: Run cargo clippy 63 | run: cargo clippy -- -A clippy::redundant_field_names 64 | 65 | rustfmt: 66 | name: Format 67 | runs-on: ubuntu-22.04 68 | steps: 69 | 70 | # Install first since it's needed to build NASM 71 | - name: Harden Runner 72 | uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0 73 | with: 74 | egress-policy: audit 75 | 76 | - name: Install LLVM and Clang 77 | uses: KyleMayes/install-llvm-action@6ba6e2cd3813def9879be378609d87cb3ef3bac3 # v2.0.6 78 | with: 79 | version: "10.0" 80 | directory: ${{ runner.temp }}/llvm 81 | 82 | - name: Install libtinfo5 83 | run: sudo apt-get update -y && sudo apt-get install libtinfo5 -y 84 | 85 | - name: install NASM 86 | uses: ilammy/setup-nasm@72793074d3c8cdda771dba85f6deafe00623038b # v1.5.2 87 | 88 | - name: Checkout sources 89 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 90 | 91 | - name: Initialize and update submodules 92 | run: | 93 | git config --global http.postBuffer 524288000 94 | git config --global http.sslVerify "false" 95 | git submodule update --init --recursive --depth 1 96 | 97 | - name: Install toolchain with rustfmt available 98 | uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af # v1.0.7 99 | with: 100 | profile: minimal 101 | toolchain: nightly-2023-12-31 102 | override: true 103 | components: rustfmt 104 | 105 | - name: Preparation Work 106 | run: bash sh_script/pre-build.sh 107 | 108 | - name: Run cargo check 109 | uses: actions-rs/cargo@844f36862e911db73fe0815f00a4a2602c279505 # v1.0.3 110 | with: 111 | command: check 112 | 113 | - name: Run cargo fmt 114 | uses: actions-rs/cargo@844f36862e911db73fe0815f00a4a2602c279505 # v1.0.3 115 | with: 116 | command: fmt 117 | args: -- --check -------------------------------------------------------------------------------- /.github/workflows/integration.yml: -------------------------------------------------------------------------------- 1 | name: vTPM Integration Test on TDX server 2 | on: 3 | push: 4 | paths-ignore: 5 | - "**.md" 6 | pull_request: 7 | paths-ignore: 8 | - "**.md" 9 | 10 | env: 11 | AS: nasm 12 | RUST_TOOLCHAIN: nightly-2023-12-31 13 | TOOLCHAIN_PROFILE: minimal 14 | LIBGUESTFS_BACKEND: direct 15 | 16 | permissions: 17 | contents: read 18 | 19 | jobs: 20 | integration: 21 | name: Run vTPM Integration Test 22 | runs-on: [self-hosted, vtpm] 23 | 24 | steps: 25 | - name: Harden Runner 26 | uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0 27 | with: 28 | egress-policy: audit 29 | 30 | - name: Checkout sources - vTpm 31 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 32 | 33 | - name: Initialize and update submodules 34 | run: | 35 | git config --global http.postBuffer 524288000 36 | git config --global http.sslVerify "false" 37 | git submodule update --init --recursive --depth 1 38 | 39 | - name: Checkout sources - TDVF 40 | run: | 41 | rm -rf ../vtpm-tdvf 42 | git clone --recursive --single-branch -b TDVF-vTPM-TD https://github.com/tianocore/edk2-staging ../vtpm-tdvf 43 | 44 | - name: Build vTPM td 45 | run: | 46 | rm -rf ../run-vtpm-td 47 | mkdir ../run-vtpm-td 48 | git submodule update --init --recursive 49 | bash sh_script/pre-build.sh 50 | bash sh_script/build.sh 51 | cp target/x86_64-unknown-none/release/vtpmtd.bin ../run-vtpm-td 52 | 53 | - name: Build config-A TDVF 54 | run: | 55 | pushd ../vtpm-tdvf 56 | make -C BaseTools 57 | source edksetup.sh 58 | rm -rf ../run-user-td 59 | mkdir ../run-user-td 60 | build -p OvmfPkg/OvmfPkgX64.dsc -t GCC5 -a X64 -D TPM2_ENABLE=TRUE -D VTPM_ENABLE=TRUE -b RELEASE 61 | cp Build/OvmfX64/RELEASE_GCC5/FV/OVMF.fd ../run-user-td/ 62 | popd 63 | 64 | - name: Run test - Config A 65 | run: | 66 | pushd sh_script 67 | python -m pytest -k "config_A" 68 | popd 69 | 70 | - name: Run test - Config A + Tpm cmd 71 | run: | 72 | pushd sh_script 73 | python -m pytest -k "tpm_cmd" 74 | popd 75 | 76 | - name: Build Config-B TDVF without secure boot 77 | run: | 78 | pushd ../vtpm-tdvf 79 | make -C BaseTools 80 | source edksetup.sh 81 | rm -rf ../run-user-td 82 | mkdir ../run-user-td 83 | build -p OvmfPkg/IntelTdx/IntelTdxX64.dsc -t GCC5 -a X64 -b RELEASE 84 | cp Build/IntelTdx/RELEASE_GCC5/FV/OVMF.fd ../run-user-td/ 85 | popd 86 | 87 | - name: Run test - Config B + no secure boot 88 | run: | 89 | pushd sh_script 90 | python -m pytest -k "config_B_no_sb" 91 | popd 92 | 93 | - name: Run test - Config B + no secure boot + Tpm cmd 94 | run: | 95 | pushd sh_script 96 | python -m pytest -k "tpm_cmd" 97 | popd 98 | 99 | - name: Build Config-B TDVF with secure boot 100 | run: | 101 | pushd ../vtpm-tdvf 102 | make -C BaseTools 103 | source edksetup.sh 104 | rm -rf ../run-user-td 105 | mkdir ../run-user-td 106 | build -p OvmfPkg/IntelTdx/IntelTdxX64.dsc -D SECURE_BOOT_ENABLE=TRUE -t GCC5 -a X64 -b RELEASE 107 | cp Build/IntelTdx/RELEASE_GCC5/FV/OVMF.fd ../run-user-td/ 108 | popd 109 | 110 | - name: Enroll OVMF.fd 111 | run: | 112 | SECURE_BOOT="/home/env/secure_boot" 113 | GUID=`cat ${SECURE_BOOT}/myGUID.txt` 114 | python sh_script/secure_boot/secure_boot.py -fd ../run-user-td/OVMF.fd -pk ${GUID} ${SECURE_BOOT}/PK.cer -kek ${GUID} ${SECURE_BOOT}/KEK.cer -db ${GUID} ${SECURE_BOOT}/DB.cer 115 | python sh_script/secure_boot/var_enroll.py --fd ../run-user-td/OVMF.sb.fd -op add -n FB_NO_REBOOT -g 605dab50-e046-4300-abb6-3dd810dd8b23 -a 0x7 -d sh_script/secure_boot/FB_NO_REBOOT.bin -o ../run-user-td/OVMF.fd 116 | 117 | - name: Run test - Config B + secure boot 118 | run: | 119 | pushd sh_script 120 | python -m pytest -k "config_B_sb_create_destroy_instance" 121 | popd -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | permissions: 2 | contents: read 3 | 4 | on: 5 | push: 6 | paths-ignore: 7 | - "**.md" 8 | pull_request: 9 | paths-ignore: 10 | - "**.md" 11 | 12 | name: Build binary 13 | 14 | env: 15 | AS: nasm 16 | RUST_TOOLCHAIN: nightly-2023-12-31 17 | TOOLCHAIN_PROFILE: minimal 18 | 19 | jobs: 20 | system_compile: 21 | name: Compile the vtpmtd.bin file 22 | runs-on: ubuntu-22.04 23 | timeout-minutes: 30 24 | 25 | steps: 26 | - name: Harden Runner 27 | uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0 28 | with: 29 | egress-policy: audit 30 | 31 | - name: Checkout vTPM-Td Sources 32 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 33 | 34 | - name: Initialize and update submodules 35 | run: | 36 | git config --global http.postBuffer 524288000 37 | git config --global http.sslVerify "false" 38 | git submodule update --init --recursive --depth 1 39 | 40 | - name: Install LLVM and Clang 41 | uses: KyleMayes/install-llvm-action@6ba6e2cd3813def9879be378609d87cb3ef3bac3 # v2.0.6 42 | with: 43 | version: "10.0" 44 | directory: ${{ runner.temp }}/llvm 45 | 46 | - name: Install libtinfo5 47 | run: sudo apt-get update -y && sudo apt-get install libtinfo5 -y 48 | 49 | - name: install NASM 50 | uses: ilammy/setup-nasm@72793074d3c8cdda771dba85f6deafe00623038b # v1.5.2 51 | 52 | - name: Install tools for tpm-ref build 53 | run: | 54 | sudo apt-get autoclean 55 | sudo apt-get update 56 | sudo apt-get upgrade 57 | sudo apt-get install autoconf-archive pkg-config build-essential automake gcc libssl-dev ocaml ocamlbuild autoconf libtool wget python-is-python3 cmake perl gcc-multilib 58 | 59 | - name: Install toolchain 60 | uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af # v1.0.7 61 | with: 62 | profile: ${{ env.TOOLCHAIN_PROFILE }} 63 | toolchain: ${{ env.RUST_TOOLCHAIN }} 64 | override: true 65 | components: rust-src 66 | 67 | - name: Run cargo install cargo-xbuild 68 | uses: actions-rs/cargo@844f36862e911db73fe0815f00a4a2602c279505 # v1.0.3 69 | with: 70 | command: install 71 | args: cargo-xbuild 72 | 73 | - name: Preparation Work 74 | run: bash sh_script/pre-build.sh 75 | 76 | - name: Run cargo check 77 | run: | 78 | cargo check 79 | 80 | - name: Build vTPM-TD 81 | env: 82 | CC: clang 83 | AR: llvm-ar 84 | run: bash sh_script/build.sh -------------------------------------------------------------------------------- /.github/workflows/oss-fuzz.yml: -------------------------------------------------------------------------------- 1 | name: oss-fuzz 2 | on: [pull_request] 3 | 4 | permissions: 5 | contents: read 6 | 7 | jobs: 8 | Fuzzing: 9 | runs-on: ubuntu-latest 10 | permissions: 11 | security-events: write 12 | steps: 13 | - name: Harden Runner 14 | uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0 15 | with: 16 | egress-policy: audit 17 | 18 | - name: Build Fuzzers 19 | id: build 20 | uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@c0c4b5402db632b5dbdb57831b7b357e14033ba1 # master 21 | with: 22 | oss-fuzz-project-name: 'vtpm-td' 23 | language: rust 24 | - name: Run Fuzzers 25 | uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@c0c4b5402db632b5dbdb57831b7b357e14033ba1 # master 26 | with: 27 | oss-fuzz-project-name: 'vtpm-td' 28 | language: rust 29 | fuzz-seconds: 600 30 | output-sarif: true 31 | - name: Upload Crash 32 | uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 33 | if: failure() && steps.build.outcome == 'success' 34 | with: 35 | name: artifacts 36 | path: ./out/artifacts 37 | - name: Upload Sarif 38 | if: always() && steps.build.outcome == 'success' 39 | uses: github/codeql-action/upload-sarif@28deaeda66b76a05916b6923827895f2b14ab387 # v3.28.16 40 | with: 41 | # Path to SARIF file relative to the root of the repository 42 | sarif_file: cifuzz-sarif/results.sarif 43 | checkout_path: cifuzz-sarif -------------------------------------------------------------------------------- /.github/workflows/scorecard.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. They are provided 2 | # by a third-party and are governed by separate terms of service, privacy 3 | # policy, and support documentation. 4 | 5 | name: Scorecard supply-chain security 6 | on: 7 | # For Branch-Protection check. Only the default branch is supported. See 8 | # https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection 9 | branch_protection_rule: 10 | # To guarantee Maintained check is occasionally updated. See 11 | # https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained 12 | schedule: 13 | - cron: '21 18 * * 3' 14 | push: 15 | branches: [ "main" ] 16 | 17 | # Declare default permissions as read only. 18 | permissions: read 19 | 20 | jobs: 21 | analysis: 22 | name: Scorecard analysis 23 | runs-on: ubuntu-latest 24 | permissions: 25 | # Needed to upload the results to code-scanning dashboard. 26 | security-events: write 27 | # Needed to publish results and get a badge (see publish_results below). 28 | id-token: write 29 | # Uncomment the permissions below if installing in a private repository. 30 | # contents: read 31 | # actions: read 32 | 33 | steps: 34 | - name: Harden Runner 35 | uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0 36 | with: 37 | egress-policy: audit 38 | 39 | - name: "Checkout code" 40 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 41 | with: 42 | persist-credentials: false 43 | 44 | - name: "Run analysis" 45 | uses: ossf/scorecard-action@f49aabe0b5af0936a0987cfb85d86b75731b0186 # v2.4.1 46 | with: 47 | results_file: results.sarif 48 | results_format: sarif 49 | # (Optional) "write" PAT token. Uncomment the `repo_token` line below if: 50 | # - you want to enable the Branch-Protection check on a *public* repository, or 51 | # - you are installing Scorecard on a *private* repository 52 | # To create the PAT, follow the steps in https://github.com/ossf/scorecard-action#authentication-with-pat. 53 | # repo_token: ${{ secrets.SCORECARD_TOKEN }} 54 | 55 | # Public repositories: 56 | # - Publish results to OpenSSF REST API for easy access by consumers 57 | # - Allows the repository to include the Scorecard badge. 58 | # - See https://github.com/ossf/scorecard-action#publishing-results. 59 | # For private repositories: 60 | # - `publish_results` will always be set to `false`, regardless 61 | # of the value entered here. 62 | publish_results: true 63 | 64 | # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF 65 | # format to the repository Actions tab. 66 | - name: "Upload artifact" 67 | uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 68 | with: 69 | name: SARIF file 70 | path: results.sarif 71 | retention-days: 5 72 | 73 | # Upload the results to GitHub's code scanning dashboard. 74 | - name: "Upload to code-scanning" 75 | uses: github/codeql-action/upload-sarif@28deaeda66b76a05916b6923827895f2b14ab387 # v3.28.16 76 | with: 77 | sarif_file: results.sarif 78 | -------------------------------------------------------------------------------- /.github/workflows/unittest.yml: -------------------------------------------------------------------------------- 1 | permissions: 2 | contents: read 3 | 4 | on: 5 | push: 6 | paths-ignore: 7 | - "**.md" 8 | pull_request: 9 | paths-ignore: 10 | - "**.md" 11 | workflow_dispatch: 12 | 13 | name: Library Crates Unit Test 14 | 15 | env: 16 | AS: nasm 17 | AR: llvm-ar 18 | CC: clang 19 | NIGHTLY_RUST_TOOLCHAIN: nightly-2023-12-31 20 | TOOLCHAIN_PROFILE: minimal 21 | 22 | jobs: 23 | lib-test: 24 | name: Build Library Crates 25 | runs-on: ubuntu-22.04 26 | timeout-minutes: 30 27 | 28 | steps: 29 | - name: Harden Runner 30 | uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0 31 | with: 32 | egress-policy: audit 33 | 34 | - name: Checkout sources 35 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 36 | 37 | - name: Initialize and update submodules 38 | run: | 39 | git config --global http.postBuffer 524288000 40 | git config --global http.sslVerify "false" 41 | git submodule update --init --recursive --depth 1 42 | 43 | # Install first since it's needed to build NASM 44 | - name: Install LLVM and Clang 45 | uses: KyleMayes/install-llvm-action@6ba6e2cd3813def9879be378609d87cb3ef3bac3 # v2.0.6 46 | with: 47 | version: "10.0" 48 | directory: ${{ runner.temp }}/llvm 49 | 50 | - name: Install libtinfo5 51 | run: sudo apt-get update -y && sudo apt-get install libtinfo5 -y 52 | 53 | - name: install NASM 54 | uses: ilammy/setup-nasm@72793074d3c8cdda771dba85f6deafe00623038b # v1.5.2 55 | 56 | - name: Install nightly toolchain 57 | uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af # v1.0.7 58 | with: 59 | profile: ${{ env.TOOLCHAIN_PROFILE }} 60 | toolchain: ${{ env.NIGHTLY_RUST_TOOLCHAIN }} 61 | override: true 62 | 63 | - name: Preparation Work 64 | run: bash sh_script/pre-build.sh 65 | 66 | - name: Unit Test for src/protocol 67 | run: | 68 | pushd src/protocol 69 | cargo test 70 | popd 71 | 72 | - name: Unit Test for src/global 73 | run: | 74 | pushd src/global 75 | cargo test 76 | popd 77 | 78 | - name: Unit Test for src/spdm 79 | run: | 80 | pushd src/spdm 81 | cargo test 82 | popd -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | 3 | # Cargo Junk 4 | target/ 5 | *.bin 6 | # afl fuzz 7 | out 8 | *.profraw 9 | # Intellj working directory 10 | .idea 11 | 12 | ## Generated by Cargo 13 | ## will have compiled files and executables 14 | debug/ 15 | 16 | # These are backup files generated by rustfmt 17 | **/*.rs.bk 18 | 19 | # C 20 | 21 | ## Object files 22 | *.o 23 | *.obj 24 | 25 | ## Linker output 26 | *.ilk 27 | *.map 28 | *.exp 29 | 30 | # Libraries 31 | *.lib 32 | *.a 33 | 34 | # Executables 35 | *.out 36 | 37 | # Build file 38 | deps/rust-tpm-20-ref/openssl-stubs/Makefile.in 39 | deps/rust-tpm-20-ref/openssl-stubs/Makefile 40 | deps/rust-tpm-20-ref/openssl-stubs/configdata.pm 41 | deps/rust-tpm-20-ref/openssl-stubs/openssl_sources.rs 42 | 43 | # Build folder 44 | deps/rust-tpm-20-ref/openssl-stubs/crypto/ 45 | deps/rust-tpm-20-ref/openssl-stubs/include/ 46 | deps/rust-tpm-20-ref/openssl-stubs/providers/ 47 | deps/rust-tpm-20-ref/openssl-stubs/conf-include/ 48 | 49 | #smallc objecs 50 | deps/rust-tpm-20-ref/smallc/obj/ 51 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "deps/td-shim"] 2 | path = deps/td-shim 3 | url = https://github.com/confidential-containers/td-shim 4 | [submodule "deps/rust-tpm-20-ref/ms-tpm-20-ref"] 5 | path = deps/rust-tpm-20-ref/ms-tpm-20-ref 6 | url = https://github.com/microsoft/ms-tpm-20-ref.git 7 | [submodule "deps/rust-tpm-20-ref/openssl"] 8 | path = deps/rust-tpm-20-ref/openssl 9 | url = https://github.com/openssl/openssl.git 10 | [submodule "deps/rust-tpm-20-ref/smallc/musl"] 11 | path = deps/rust-tpm-20-ref/smallc/musl 12 | url = https://git.musl-libc.org/git/musl 13 | [submodule "deps/linux-sgx"] 14 | path = deps/linux-sgx 15 | url = https://github.com/intel/linux-sgx.git 16 | [submodule "deps/spdm-rs"] 17 | path = deps/spdm-rs 18 | url = https://github.com/ccc-spdm-tools/spdm-rs.git 19 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ### License 4 | 5 | is licensed under the terms in [LICENSE]. By contributing to the project, you agree to the license and copyright terms therein and release your contribution under these terms. 6 | 7 | ### Sign your work 8 | 9 | Please use the sign-off line at the end of the patch. Your signature certifies that you wrote the patch or otherwise have the right to pass it on as an open-source patch. The rules are pretty simple: if you can certify 10 | the below (from [developercertificate.org](http://developercertificate.org/)): 11 | 12 | ``` 13 | Developer Certificate of Origin 14 | Version 1.1 15 | 16 | Copyright (C) 2004, 2006 The Linux Foundation and its contributors. 17 | 660 York Street, Suite 102, 18 | San Francisco, CA 94110 USA 19 | 20 | Everyone is permitted to copy and distribute verbatim copies of this 21 | license document, but changing it is not allowed. 22 | 23 | Developer's Certificate of Origin 1.1 24 | 25 | By making a contribution to this project, I certify that: 26 | 27 | (a) The contribution was created in whole or in part by me and I 28 | have the right to submit it under the open source license 29 | indicated in the file; or 30 | 31 | (b) The contribution is based upon previous work that, to the best 32 | of my knowledge, is covered under an appropriate open source 33 | license and I have the right under that license to submit that 34 | work with modifications, whether created in whole or in part 35 | by me, under the same open source license (unless I am 36 | permitted to submit under a different license), as indicated 37 | in the file; or 38 | 39 | (c) The contribution was provided directly to me by some other 40 | person who certified (a), (b) or (c) and I have not modified 41 | it. 42 | 43 | (d) I understand and agree that this project and the contribution 44 | are public and that a record of the contribution (including all 45 | personal information I submit with it, including my sign-off) is 46 | maintained indefinitely and may be redistributed consistent with 47 | this project or the open source license(s) involved. 48 | ``` 49 | 50 | Then you just add a line to every git commit message: 51 | 52 | Signed-off-by: Joe Smith 53 | 54 | Use your real name (sorry, no pseudonyms or anonymous contributions.) 55 | 56 | If you set your `user.name` and `user.email` git configs, you can sign your 57 | commit automatically with `git commit -s`. 58 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | resolver = "2" 3 | 4 | default-members = [ 5 | "src/vtpmtd", 6 | ] 7 | members = [ 8 | "src/attestation", 9 | "src/eventlog", 10 | "src/global", 11 | "src/crypto", 12 | "src/protocol", 13 | "src/spdm", 14 | "src/tdtunnel", 15 | "src/tpm", 16 | "src/vtpmtd", 17 | ] 18 | 19 | exclude = [ 20 | "deps/td-shim", 21 | "deps/spdm-rs", 22 | "deps/ring", 23 | "deps/webpki", 24 | ] 25 | 26 | # the profile used for `cargo build` 27 | [profile.dev] 28 | panic = "abort" # disable stack unwinding on panic 29 | 30 | # the profile used for `cargo build --release` 31 | [profile.release] 32 | panic = "abort" # disable stack unwinding on panic 33 | lto = true # Link-time optimization 34 | 35 | [patch.crates-io] 36 | ring = { path = "deps/spdm-rs/external/ring" } 37 | webpki = { path = "deps/spdm-rs/external/webpki" } 38 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:24.04@sha256:1e622c5f073b4f6bfad6632f2616c7f59ef256e96fe78bf6a595d1dc4376ac02 2 | 3 | # Adding rust binaries to PATH. 4 | ENV PATH="$PATH:/root/.cargo/bin" 5 | WORKDIR /root 6 | 7 | # Install all required packages in one go to optimize the image 8 | # https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#run 9 | # DEBIAN_FRONTEND is set for tzdata. 10 | RUN apt-get update && \ 11 | DEBIAN_FRONTEND="noninteractive" apt-get install --no-install-recommends -y \ 12 | build-essential unzip ca-certificates curl gcc git libssl-dev pkg-config ssh \ 13 | clang llvm nasm \ 14 | ocaml ocamlbuild wget pkg-config libtool autoconf autotools-dev automake \ 15 | screen expect \ 16 | # cleanup 17 | && apt-get clean && rm -rf /var/lib/apt/lists/* 18 | 19 | # Install rustup and a fixed version of Rust. 20 | RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain nightly-2023-12-31 21 | RUN rustup component add rust-src 22 | RUN cargo install cargo-xbuild 23 | 24 | RUN git clone --recursive https://github.com/intel/vtpm-td.git 25 | -------------------------------------------------------------------------------- /config/intel_root_sbx.der: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intel/vtpm-td/00a2f8619661a4a7ee26efd47fbb4c5efbcab869/config/intel_root_sbx.der -------------------------------------------------------------------------------- /config/manifest_info.json: -------------------------------------------------------------------------------- 1 | { 2 | "attributes": "0000000000000000", 3 | "xfam": "e71a060000000000", 4 | "mrconfigid": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 5 | "mrowner": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 6 | "mrownerconfig": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" 7 | } -------------------------------------------------------------------------------- /config/metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "Sections": [ 3 | { 4 | "DataOffset": "0x81000", 5 | "RawDataSize": "0xF7F000", 6 | "MemoryAddress": "0xFF081000", 7 | "MemoryDataSize": "0xF7F000", 8 | "Type": "BFV", 9 | "Attributes": "0x1" 10 | }, 11 | { 12 | "DataOffset": "0x0", 13 | "RawDataSize": "0x40000", 14 | "MemoryAddress": "0xFF000000", 15 | "MemoryDataSize": "0x40000", 16 | "Type": "CFV", 17 | "Attributes": "0x0" 18 | }, 19 | { 20 | "DataOffset": "0x0", 21 | "RawDataSize": "0x0", 22 | "MemoryAddress": "0xFF041000", 23 | "MemoryDataSize": "0x20000", 24 | "Type": "TempMem", 25 | "Attributes": "0x0" 26 | }, 27 | { 28 | "DataOffset": "0x0", 29 | "RawDataSize": "0x0", 30 | "MemoryAddress": "0xFF061000", 31 | "MemoryDataSize": "0x20000", 32 | "Type": "TempMem", 33 | "Attributes": "0x0" 34 | }, 35 | { 36 | "DataOffset": "0x0", 37 | "RawDataSize": "0x0", 38 | "MemoryAddress": "0x0", 39 | "MemoryDataSize": "0x2000000", 40 | "Type": "PermMem", 41 | "Attributes": "0x2" 42 | }, 43 | { 44 | "DataOffset": "0x0", 45 | "RawDataSize": "0x0", 46 | "MemoryAddress": "0xFF040000", 47 | "MemoryDataSize": "0x1000", 48 | "Type": "TempMem", 49 | "Attributes": "0x0" 50 | } 51 | ] 52 | } -------------------------------------------------------------------------------- /config/shim_layout.json: -------------------------------------------------------------------------------- 1 | { 2 | "memory_regions": [ 3 | { 4 | "name": "Bootloader", 5 | "size": "0x800000", 6 | "type": "Memory" 7 | }, 8 | { 9 | "name": "TdHob", 10 | "size": "0x20000", 11 | "type": "Memory" 12 | }, 13 | { 14 | "name": "EventLog", 15 | "size": "0x100000", 16 | "type": "Nvs" 17 | }, 18 | { 19 | "name": "RelocatedMailbox", 20 | "size": "0x2000", 21 | "type": "Nvs" 22 | }, 23 | { 24 | "name": "PayloadPageTable", 25 | "size": "0x20000", 26 | "type": "Reserved" 27 | }, 28 | { 29 | "name": "Payload", 30 | "size": "0x1000000", 31 | "type": "Reserved" 32 | }, 33 | { 34 | "name": "Acpi", 35 | "size": "0x100000", 36 | "type": "Acpi" 37 | } 38 | ] 39 | } -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rust-tpm-20-ref" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | log = "0.4.13" -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/arch/x86_64/base.h: -------------------------------------------------------------------------------- 1 | #ifndef __BASE_H_ 2 | #define __BASE_H_ 3 | 4 | 5 | /// 6 | /// 8-byte unsigned value 7 | /// 8 | typedef unsigned long long UINT64; 9 | /// 10 | /// 8-byte signed value 11 | /// 12 | typedef long long INT64; 13 | /// 14 | /// 4-byte unsigned value 15 | /// 16 | typedef unsigned int UINT32; 17 | /// 18 | /// 4-byte signed value 19 | /// 20 | typedef int INT32; 21 | /// 22 | /// 2-byte unsigned value 23 | /// 24 | typedef unsigned short UINT16; 25 | /// 26 | /// 2-byte Character. Unless otherwise specified all strings are stored in the 27 | /// UTF-16 encoding format as defined by Unicode 2.1 and ISO/IEC 10646 standards. 28 | /// 29 | typedef unsigned short CHAR16; 30 | /// 31 | /// 2-byte signed value 32 | /// 33 | typedef short INT16; 34 | /// 35 | /// Logical Boolean. 1-byte value containing 0 for FALSE or a 1 for TRUE. Other 36 | /// values are undefined. 37 | /// 38 | typedef unsigned char BOOLEAN; 39 | /// 40 | /// 1-byte unsigned value 41 | /// 42 | typedef unsigned char UINT8; 43 | /// 44 | /// 1-byte Character 45 | /// 46 | typedef char CHAR8; 47 | /// 48 | /// 1-byte signed value 49 | /// 50 | typedef signed char INT8; 51 | 52 | 53 | typedef UINT64 UINTN; 54 | typedef INT64 INTN; 55 | 56 | /// 57 | /// Maximum legal x64 INTN and UINTN values. 58 | /// 59 | #define MAX_INTN ((INTN)0x7FFFFFFFFFFFFFFFULL) 60 | #define MAX_UINTN ((UINTN)0xFFFFFFFFFFFFFFFFULL) 61 | 62 | /// 63 | /// Minimum legal x64 INTN value. 64 | /// 65 | #define MIN_INTN (((INTN)-9223372036854775807LL) - 1) 66 | 67 | #endif -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/openssl-how-to.md: -------------------------------------------------------------------------------- 1 | 2 | ## Run ```process_openssl.pl``` 3 | 4 | when update opensslversion 5 | 6 | mkdir -p conf-include/openssl; 7 | mkdir -p conf-include/crypto; 8 | CC=clang AR=llvm-ar CFLAGS="-Wall -Werror -Wno-format -target x86_64-unknown-none -fPIC -nostdlib -nostdlibinc -ffreestanding -Istd-include -Iconf-include -Iarch/x86_64 -I../openssl-stubs -include CrtLibSupport.h -std=c99" ./process_openssl.pl 9 | 10 | make -j$(nproc) libcrypto.a 11 | cp libcrypto.a crypto.lib 12 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/openssl_sources.rs.template: -------------------------------------------------------------------------------- 1 | 2 | 3 | pub const OPENSSL_CRYPTO_SRCS: &[&str] = &[ 4 | // GENERATE_START 5 | // GENERATE_END 6 | ]; -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/rand_pool.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef void RAND_POOL; 5 | 6 | int ossl_rand_pool_add(RAND_POOL *pool, 7 | const unsigned char *buffer, size_t len, size_t entropy); 8 | unsigned char *ossl_rand_pool_add_begin(RAND_POOL *pool, size_t len); 9 | int ossl_rand_pool_add_end(RAND_POOL *pool, size_t len, size_t entropy); 10 | size_t ossl_rand_pool_bytes_needed(RAND_POOL *pool, unsigned int entropy_factor); 11 | size_t ossl_rand_pool_entropy_available(RAND_POOL *pool); 12 | 13 | extern uint32_t __fw_rdrand32(void); 14 | 15 | static uint32_t 16 | rand32( 17 | void) 18 | { 19 | return __fw_rdrand32(); 20 | } 21 | 22 | static size_t ossl_rand_get_bytes(size_t amount, unsigned char *entropy) 23 | { 24 | uint32_t left, multi4_total; 25 | uint32_t tmp_value; 26 | if (amount == 0) 27 | { 28 | return 0; 29 | } 30 | left = amount % 4; 31 | multi4_total = amount - left; 32 | if (multi4_total != 0) 33 | { 34 | for (uint32_t index = 0; index < multi4_total; index += 4) 35 | { 36 | *(uint32_t *)(entropy + index) = rand32(); 37 | } 38 | } 39 | if (left != 0) 40 | { 41 | tmp_value = rand32(); 42 | for (uint32_t index = 0; index < left; index++) 43 | { 44 | *(entropy + multi4_total + index) = *((unsigned char *)&tmp_value + index); 45 | } 46 | } 47 | 48 | return amount; 49 | } 50 | 51 | /* 52 | * Add random bytes to the pool to acquire requested amount of entropy 53 | * 54 | * This function is platform specific and tries to acquire the requested 55 | * amount of entropy by polling platform specific entropy sources. 56 | * 57 | * This is OpenSSL required interface. 58 | */ 59 | size_t 60 | ossl_pool_acquire_entropy( 61 | RAND_POOL *pool) 62 | { 63 | size_t Bytes_needed; 64 | unsigned char *Buffer; 65 | size_t ret_bytes; 66 | 67 | Bytes_needed = ossl_rand_pool_bytes_needed(pool, 1 /*entropy_factor*/); 68 | if (Bytes_needed > 0) 69 | { 70 | Buffer = ossl_rand_pool_add_begin(pool, Bytes_needed); 71 | 72 | if (Buffer != NULL) 73 | { 74 | ret_bytes = ossl_rand_get_bytes(Bytes_needed, Buffer); 75 | if (ret_bytes < Bytes_needed) 76 | { 77 | ossl_rand_pool_add_end(pool, 0, 0); 78 | } 79 | else 80 | { 81 | ossl_rand_pool_add_end(pool, Bytes_needed, 8 * Bytes_needed); 82 | } 83 | } 84 | } 85 | 86 | return ossl_rand_pool_entropy_available(pool); 87 | } 88 | 89 | /* 90 | * Implementation for UEFI 91 | * 92 | * This is OpenSSL required interface. 93 | */ 94 | int ossl_pool_add_nonce_data( 95 | RAND_POOL *pool) 96 | { 97 | uint8_t data[16]; 98 | ossl_rand_get_bytes(sizeof(data), data); 99 | 100 | return ossl_rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0); 101 | } 102 | 103 | /* 104 | * Implementation for UEFI 105 | * 106 | * This is OpenSSL required interface. 107 | */ 108 | int ossl_rand_pool_add_additional_data( 109 | RAND_POOL *pool) 110 | { 111 | uint8_t data[16]; 112 | ossl_rand_get_bytes(sizeof(data), data); 113 | 114 | return ossl_rand_pool_add(pool, (unsigned char *)&data, sizeof(data), 0); 115 | } 116 | 117 | /* 118 | * Dummy Implementation for UEFI 119 | * 120 | * This is OpenSSL required interface. 121 | */ 122 | int ossl_rand_pool_init( 123 | void) 124 | { 125 | return 1; 126 | } 127 | 128 | /* 129 | * Dummy Implementation for UEFI 130 | * 131 | * This is OpenSSL required interface. 132 | */ 133 | void ossl_rand_pool_cleanup( 134 | void) 135 | { 136 | } 137 | 138 | /* 139 | * Dummy Implementation for UEFI 140 | * 141 | * This is OpenSSL required interface. 142 | */ 143 | void ossl_rand_pool_keep_random_devices_open( 144 | int keep) 145 | { 146 | } 147 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/arpa/inet.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building third-party standard C / BSD sockets code. 3 | 4 | Copyright (C) 2019, Red Hat, Inc. 5 | 6 | SPDX-License-Identifier: BSD-2-Clause-Patent 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/arpa/nameser.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building third-party standard C / BSD sockets code. 3 | 4 | Copyright (C) 2019, Red Hat, Inc. 5 | 6 | SPDX-License-Identifier: BSD-2-Clause-Patent 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/assert.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/crypto/dso_conf.h: -------------------------------------------------------------------------------- 1 | /* WARNING: do not edit! */ 2 | /* Generated from ../openssl/include/crypto/dso_conf.h.in */ 3 | /* 4 | * Copyright 2016-2019 The OpenSSL Project Authors. All Rights Reserved. 5 | * 6 | * Licensed under the OpenSSL license (the "License"). You may not use 7 | * this file except in compliance with the License. You can obtain a copy 8 | * in the file LICENSE in the source distribution or at 9 | * https://www.openssl.org/source/license.html 10 | */ 11 | 12 | #ifndef OSSL_CRYPTO_DSO_CONF_H 13 | # define OSSL_CRYPTO_DSO_CONF_H 14 | # define DSO_NONE 15 | # define DSO_EXTENSION ".so" 16 | #endif 17 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/ctype.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/errno.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/fcntl.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/internal/dso_conf.h: -------------------------------------------------------------------------------- 1 | /* WARNING: do not edit! */ 2 | /* Generated from crypto/include/internal/dso_conf.h.in */ 3 | /* 4 | * Copyright 2016-2019 The OpenSSL Project Authors. All Rights Reserved. 5 | * 6 | * Licensed under the OpenSSL license (the "License"). You may not use 7 | * this file except in compliance with the License. You can obtain a copy 8 | * in the file LICENSE in the source distribution or at 9 | * https://www.openssl.org/source/license.html 10 | */ 11 | 12 | #ifndef HEADER_DSO_CONF_H 13 | # define HEADER_DSO_CONF_H 14 | # define DSO_NONE 15 | # define DSO_EXTENSION ".so" 16 | #endif 17 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/limits.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/memory.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/netinet/in.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building third-party standard C / BSD sockets code. 3 | 4 | Copyright (C) 2019, Red Hat, Inc. 5 | 6 | SPDX-License-Identifier: BSD-2-Clause-Patent 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/stdarg.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/stddef.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/stdio.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/stdlib.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/string.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/strings.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/sys/param.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building third-party standard C / BSD sockets code. 3 | 4 | Copyright (C) 2019, Red Hat, Inc. 5 | 6 | SPDX-License-Identifier: BSD-2-Clause-Patent 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/sys/shm.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2019, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/sys/socket.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building third-party standard C / BSD sockets code. 3 | 4 | Copyright (C) 2019, Red Hat, Inc. 5 | 6 | SPDX-License-Identifier: BSD-2-Clause-Patent 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/sys/stat.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/sys/syscall.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | Copyright (c) 2019, Red Hat, Inc. 6 | SPDX-License-Identifier: BSD-2-Clause-Patent 7 | 8 | **/ 9 | 10 | #include 11 | 12 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/sys/time.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/sys/types.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/sys/utsname.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2019, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/syslog.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/time.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/openssl-stubs/std-include/unistd.h: -------------------------------------------------------------------------------- 1 | /** @file 2 | Include file to support building the third-party cryptographic library. 3 | 4 | Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
5 | SPDX-License-Identifier: BSD-2-Clause-Patent 6 | 7 | **/ 8 | 9 | #include 10 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/patches/BaseTypes.diff: -------------------------------------------------------------------------------- 1 | diff --git a/TPMCmd/tpm/include/BaseTypes.h b/TPMCmd/tpm/include/BaseTypes.h 2 | index afcfef9..bf589f0 100644 3 | --- a/TPMCmd/tpm/include/BaseTypes.h 4 | +++ b/TPMCmd/tpm/include/BaseTypes.h 5 | @@ -40,11 +40,6 @@ 6 | #ifndef _BASE_TYPES_H_ 7 | #define _BASE_TYPES_H_ 8 | 9 | -// NULL definition 10 | -#ifndef NULL 11 | -#define NULL (0) 12 | -#endif 13 | - 14 | typedef uint8_t UINT8; 15 | typedef uint8_t BYTE; 16 | typedef int8_t INT8; 17 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/patches/nv.diff: -------------------------------------------------------------------------------- 1 | diff --git a/TPMCmd/tpm/src/support/Manufacture.c b/TPMCmd/tpm/src/support/Manufacture.c 2 | index 1c6f736..d95879a 100644 3 | --- a/TPMCmd/tpm/src/support/Manufacture.c 4 | +++ b/TPMCmd/tpm/src/support/Manufacture.c 5 | @@ -82,7 +82,8 @@ TPM_Manufacture( 6 | s_DAPendingOnNV = FALSE; 7 | 8 | // initialize NV 9 | - NvManufacture(); 10 | + if (_plat__NVNeedsManufacture()) 11 | + NvManufacture(); 12 | 13 | // Clear the magic value in the DRBG state 14 | go.drbgState.magic = 0; 15 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/patches/openssl3.1.1.diff: -------------------------------------------------------------------------------- 1 | diff --git a/TPMCmd/configure.ac b/TPMCmd/configure.ac 2 | index 58a74b4..4ff3253 100644 3 | --- a/TPMCmd/configure.ac 4 | +++ b/TPMCmd/configure.ac 5 | @@ -51,7 +51,10 @@ AC_ARG_ENABLE(usedeviceid, 6 | AS_HELP_STRING([--enable-usedeviceid], 7 | [tpm simulator get seeds derived from hardware parameters. Seeds are not derived from secure hardware source.])) 8 | 9 | -PKG_CHECK_MODULES([LIBCRYPTO], [libcrypto]) 10 | +PKG_CHECK_MODULES([LIBCRYPTO], [libcrypto >= 3.0], 11 | + [AC_DEFINE([OPENSSL_API_COMPAT], [10101])], 12 | + [PKG_CHECK_MODULES([LIBCRYPTO], [libcrypto])]) 13 | + 14 | AS_IF([test "x$enable_usedeviceid" = "xyes"], [ 15 | PKG_CHECK_MODULES([LIBUDEV], [libudev]) 16 | [ADDITIONAL_LIBS="-ludev"] 17 | diff --git a/TPMCmd/tpm/include/Ossl/TpmToOsslMath.h b/TPMCmd/tpm/include/Ossl/TpmToOsslMath.h 18 | index 9836a3d..0cf9fea 100644 19 | --- a/TPMCmd/tpm/include/Ossl/TpmToOsslMath.h 20 | +++ b/TPMCmd/tpm/include/Ossl/TpmToOsslMath.h 21 | @@ -49,11 +49,11 @@ 22 | 23 | #define SYMMETRIC_ALIGNMENT RADIX_BYTES 24 | 25 | -#if OPENSSL_VERSION_NUMBER >= 0x10200000L 26 | +#if OPENSSL_VERSION_NUMBER >= 0x30200000L 27 | // Check the bignum_st definition in crypto/bn/bn_lcl.h and either update the 28 | // version check or provide the new definition for this version. 29 | # error Untested OpenSSL version 30 | -#elif OPENSSL_VERSION_NUMBER >= 0x10100000L 31 | +#elif OPENSSL_VERSION_NUMBER >= 0x30000000L 32 | // from crypto/bn/bn_lcl.h 33 | struct bignum_st { 34 | BN_ULONG *d; /* Pointer to an array of 'BN_BITS2' bit 35 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/sh_script/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | SHA256="ALG_NO" 4 | SHA384="ALG_NO" 5 | SHA512="ALG_NO" 6 | BUILD_OPT="build" 7 | RENAME_SYMBOL=0 8 | 9 | function clean() { 10 | pushd smallc 11 | pushd musl 12 | git clean -f -d 13 | popd 14 | make clean 15 | popd 16 | 17 | pushd openssl-stubs 18 | make clean 19 | popd 20 | 21 | pushd tpm 22 | make clean 23 | popd 24 | 25 | cargo clean 26 | } 27 | 28 | function build() { 29 | pushd smallc 30 | make init 31 | make all 32 | make install 33 | [[ ${RENAME_SYMBOL} == 1 ]] && objcopy --redefine-syms=../sh_script/rename_smallc_symbols lib/libsmallc.a 34 | popd 35 | 36 | pushd openssl-stubs 37 | 38 | [[ ! -d "conf-include/openssl" ]] && mkdir -p conf-include/openssl 39 | [[ ! -d "conf-include/crypto" ]] && mkdir -p conf-include/crypto 40 | 41 | CC=clang AR=llvm-ar \ 42 | CFLAGS="-Wall -Werror -Wno-format -target x86_64-unknown-none -fPIC \ 43 | -nostdlib -nostdlibinc -ffreestanding -Istd-include -Iconf-include \ 44 | -Iarch/x86_64 -I../openssl-stubs -include CrtLibSupport.h -std=c99" \ 45 | ./process_openssl.pl 46 | 47 | make -j$(nproc) libcrypto.a 48 | cp libcrypto.a crypto.lib 49 | popd 50 | 51 | pushd tpm 52 | CC=clang AR=llvm-ar make ALG_SHA256=${SHA256} ALG_SHA384=${SHA384} ALG_SHA512=${SHA512} 53 | popd 54 | } 55 | 56 | while [[ $# -gt 0 ]]; do 57 | case "$1" in 58 | -algo) 59 | # Split the comma-separated list of algorithms 60 | IFS=',' read -ra algorithms <<< "$2" 61 | for algorithm in "${algorithms[@]}"; do 62 | # Set variables based on specified algorithms 63 | case "$algorithm" in 64 | sha256) 65 | SHA256="ALG_YES" 66 | ;; 67 | sha384) 68 | SHA384="ALG_YES" 69 | ;; 70 | sha512) 71 | SHA512="ALG_YES" 72 | ;; 73 | *) 74 | echo "Unknown algorithm: $algorithm" 75 | ;; 76 | esac 77 | done 78 | shift 79 | ;; 80 | -rename_symbol) 81 | RENAME_SYMBOL=1 82 | shift 83 | ;; 84 | -clean) 85 | BUILD_OPT="clean" 86 | shift 87 | ;; 88 | *) 89 | echo "Unknown option: $1" 90 | ;; 91 | esac 92 | shift 93 | done 94 | 95 | case "${BUILD_OPT}" in 96 | clean) clean ;; 97 | build) build ;; 98 | *) echo "unknown build option - ${BUILD_OPT}" ;; 99 | esac 100 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/sh_script/pre-build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | patch_mstpm20ref() { 4 | # apply the patch set for ms-tpm-20-ref 5 | pushd ms-tpm-20-ref 6 | git reset --hard d638536 7 | git clean -f -d 8 | patch -p 1 -i ../patches/nv.diff 9 | patch -p 1 -i ../patches/openssl3.1.1.diff 10 | patch -p 1 -i ../patches/BaseTypes.diff 11 | popd 12 | } 13 | 14 | patch_mstpm20ref 15 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/sh_script/rename_smallc_symbols: -------------------------------------------------------------------------------- 1 | memset smallc_memset 2 | abort smallc_abort 3 | __stack_chk_guard smallc__stack_chk_guard 4 | __stack_chk_fail smallc__stack_chk_fail -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/smallc/config.mak: -------------------------------------------------------------------------------- 1 | AR = llvm-ar 2 | RANLIB = ranlib 3 | ARCH = x86_64 4 | SUBARCH = 5 | ASMSUBARCH = 6 | srcdir = ./musl 7 | includedir = ./include 8 | syslibdir = /lib 9 | CC = clang 10 | CFLAGS = -fPIC 11 | CFLAGS_AUTO = -Os -pipe -fomit-frame-pointer -fno-unwind-tables -fno-asynchronous-unwind-tables -ffunction-sections -fdata-sections -w -Wno-pointer-to-int-cast -Werror=implicit-function-declaration -Werror=implicit-int -Werror=pointer-sign -Werror=pointer-arith -Werror=int-conversion -Werror=incompatible-pointer-types -Qunused-arguments -Waddress -Warray-bounds -Wchar-subscripts -Wduplicate-decl-specifier -Winit-self -Wreturn-type -Wsequence-point -Wstrict-aliasing -Wunused-function -Wunused-label -Wunused-variable 12 | CFLAGS_C99FSE = -std=c99 -nostdinc -ffreestanding -frounding-math -fno-strict-aliasing -Wa,--noexecstack 13 | CFLAGS_MEMOPS = 14 | CFLAGS_NOSSP = -fno-stack-protector 15 | CPPFLAGS = 16 | LDFLAGS = 17 | LDFLAGS_AUTO = -Wl,--sort-section,alignment -Wl,--sort-common -Wl,--gc-sections -Wl,--hash-style=both -Wl,--no-undefined -Wl,--exclude-libs=ALL -Wl,--dynamic-list=./dynamic.list 18 | CROSS_COMPILE = x86_64- 19 | LIBCC = -lgcc -lgcc_eh 20 | OPTIMIZE_GLOBS = internal/*.c malloc/*.c string/*.c 21 | ALL_TOOLS = obj/musl-clang obj/ld.musl-clang 22 | TOOL_LIBS = 23 | ADD_CFI = no 24 | MALLOC_DIR = mallocng 25 | WRAPCC_CLANG = $(CC) 26 | AOBJS = $(LOBJS) 27 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/smallc/include/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything in this directory 2 | * 3 | # Except this file 4 | !.gitignore 5 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/smallc/src/exit/abort.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 - 2023 Intel Corporation 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | #include 7 | 8 | extern void __fw_abort(); 9 | 10 | void abort(void) 11 | { 12 | __fw_abort(); 13 | } -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/smallc/src/exit/assert.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 - 2023 Intel Corporation 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | #include 7 | #include 8 | 9 | void __assert_fail(const char *expr, const char *file, int line, const char *func) 10 | { 11 | printf("Assertion failed: %s (%s: %s: %d)\n", expr, file, func, line); 12 | abort(); 13 | } 14 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/smallc/src/legacy/err.c: -------------------------------------------------------------------------------- 1 | /* Copyright (C) 2011 by Valentin Ochs 2 | * 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy 4 | * of this software and associated documentation files (the "Software"), to 5 | * deal in the Software without restriction, including without limitation the 6 | * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 7 | * sell copies of the Software, and to permit persons to whom the Software is 8 | * furnished to do so, subject to the following conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in 11 | * all copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 19 | * IN THE SOFTWARE. 20 | */ 21 | 22 | /* 23 | Copyright (c) 2022 - 2023 Intel Corporation 24 | SPDX-License-Identifier: Apache-2.0 25 | */ 26 | 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | extern char *__progname; 33 | 34 | int errno = 0; 35 | 36 | void vwarn(const char *fmt, va_list ap) 37 | { 38 | printf ("%s: ", __progname); 39 | if (fmt) { 40 | printf(fmt, ap); 41 | } 42 | } 43 | 44 | void vwarnx(const char *fmt, va_list ap) 45 | { 46 | printf ("%s: ", __progname); 47 | if (fmt) printf(fmt, ap); 48 | } 49 | 50 | _Noreturn void verr(int status, const char *fmt, va_list ap) 51 | { 52 | vwarn(fmt, ap); 53 | } 54 | 55 | _Noreturn void verrx(int status, const char *fmt, va_list ap) 56 | { 57 | vwarnx(fmt, ap); 58 | } 59 | 60 | void warn(const char *fmt, ...) 61 | { 62 | va_list ap; 63 | va_start(ap, fmt); 64 | vwarn(fmt, ap); 65 | va_end(ap); 66 | } 67 | 68 | void warnx(const char *fmt, ...) 69 | { 70 | va_list ap; 71 | va_start(ap, fmt); 72 | vwarnx(fmt, ap); 73 | va_end(ap); 74 | } 75 | 76 | _Noreturn void err(int status, const char *fmt, ...) 77 | { 78 | va_list ap; 79 | va_start(ap, fmt); 80 | verr(status, fmt, ap); 81 | va_end(ap); 82 | } 83 | 84 | _Noreturn void errx(int status, const char *fmt, ...) 85 | { 86 | va_list ap; 87 | va_start(ap, fmt); 88 | verrx(status, fmt, ap); 89 | va_end(ap); 90 | } 91 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/smallc/src/malloc/free.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 - 2023 Intel Corporation 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | #include 7 | 8 | extern void __fw_free(void *p); 9 | 10 | void free(void *p) 11 | { 12 | __fw_free(p); 13 | } 14 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/smallc/src/malloc/lite_malloc.c: -------------------------------------------------------------------------------- 1 | /* Copyright (C) 2011 by Valentin Ochs 2 | * 3 | * Permission is hereby granted, free of charge, to any person obtaining a copy 4 | * of this software and associated documentation files (the "Software"), to 5 | * deal in the Software without restriction, including without limitation the 6 | * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 7 | * sell copies of the Software, and to permit persons to whom the Software is 8 | * furnished to do so, subject to the following conditions: 9 | * 10 | * The above copyright notice and this permission notice shall be included in 11 | * all copies or substantial portions of the Software. 12 | * 13 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 19 | * IN THE SOFTWARE. 20 | */ 21 | 22 | /* 23 | Copyright (c) 2022 - 2023 Intel Corporation 24 | SPDX-License-Identifier: Apache-2.0 25 | */ 26 | 27 | #include 28 | #include 29 | #include 30 | 31 | extern void *__fw_malloc(size_t n); 32 | static void *__simple_malloc(size_t n) 33 | { 34 | return __fw_malloc(n); 35 | } 36 | 37 | weak_alias(__simple_malloc, __libc_malloc_impl); 38 | 39 | void *__libc_malloc(size_t n) 40 | { 41 | return __libc_malloc_impl(n); 42 | } 43 | 44 | static void *default_malloc(size_t n) 45 | { 46 | return __libc_malloc_impl(n); 47 | } 48 | 49 | weak_alias(default_malloc, malloc); 50 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/smallc/src/malloc/mallocng/free.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 - 2023 Intel Corporation 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | #include 7 | 8 | extern __fw_free(void *p); 9 | 10 | void free(void *p) 11 | { 12 | __fw_free(p); 13 | } 14 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/smallc/src/malloc/mallocng/malloc.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 - 2023 Intel Corporation 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | #include 7 | 8 | extern void *__fw_malloc(size_t n); 9 | 10 | void *malloc(size_t n) 11 | { 12 | return __fw_malloc(n); 13 | } 14 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/smallc/src/malloc/realloc.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 - 2023 Intel Corporation 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | #include 7 | 8 | extern void *__fw_realloc(void *p, size_t n); 9 | 10 | void *realloc(void *p, size_t n) 11 | { 12 | return __fw_realloc(p, n); 13 | } 14 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/smallc/src/prng/rand.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 - 2023 Intel Corporation 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | #include 7 | #include 8 | 9 | extern uint32_t __fw_rdrand32(void); 10 | 11 | void srand(unsigned s) 12 | { 13 | } 14 | 15 | int rand(void) 16 | { 17 | return (int)__fw_rdrand32(); 18 | } 19 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/smallc/src/stdio/printf.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 - 2023 Intel Corporation 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | #include 7 | #include 8 | 9 | extern void __fw_debug_msg(char *, int); 10 | 11 | int printf(const char *restrict fmt, ...) 12 | { 13 | #ifndef _PRINTF_BUF_SIZE_ 14 | #define _PRINTF_BUF_SIZE_ 512 15 | #endif 16 | char buf[_PRINTF_BUF_SIZE_] = {0}; 17 | int len = 0; 18 | va_list args; 19 | va_start(args, fmt); 20 | len = vsnprintf(buf, _PRINTF_BUF_SIZE_, fmt, args); 21 | va_end(args); 22 | __fw_debug_msg(buf, len); 23 | return len; 24 | #undef _PRINTF_BUF_SIZE_ 25 | } 26 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/smallc/src/time/time.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 - 2023 Intel Corporation 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | #include 7 | 8 | extern time_t __fw_sys_time(); 9 | 10 | time_t time(time_t *t) 11 | { 12 | 13 | time_t current_time = 0; 14 | current_time = __fw_sys_time(); 15 | if (t != NULL) 16 | { 17 | *t = current_time; 18 | } 19 | return current_time; 20 | } 21 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | #![no_std] 6 | #![feature(naked_functions)] 7 | 8 | extern crate alloc; 9 | use core::arch::asm; 10 | #[naked] 11 | #[no_mangle] 12 | /// # Safety 13 | /// 14 | /// This function is unsafe 15 | pub unsafe extern "C" fn ___chkstk_ms() { 16 | asm!( 17 | "push %rcx", 18 | "push %rax", 19 | "cmp $0x1000,%rax", 20 | "lea 24(%rsp),%rcx", 21 | "jb 1f", 22 | "2:", 23 | "sub $0x1000,%rcx", 24 | "test %rcx,(%rcx)", 25 | "sub $0x1000,%rax", 26 | "cmp $0x1000,%rax", 27 | "ja 2b", 28 | "1:", 29 | "sub %rax,%rcx", 30 | "test %rcx,(%rcx)", 31 | "pop %rax", 32 | "pop %rcx", 33 | "ret", 34 | options(noreturn, att_syntax) 35 | ); 36 | } 37 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/tpm/Makefile: -------------------------------------------------------------------------------- 1 | LIBC_INC = -I../smallc/include 2 | OPENSSL_INC = -I../openssl/include \ 3 | -I../openssl-stubs/conf-include 4 | 5 | DEFINED = 6 | LLVM_TARGET_ARCH = -target x86_64-unknown-none 7 | CFLAGS += ${LLVM_TARGET_ARCH} ${DEFINED} ${INCLUDES} \ 8 | -g -Wall -Werror -Wno-empty-body -std=c11 -fPIC \ 9 | -nostdlib -nostdlibinc -ffreestanding \ 10 | -mno-red-zone -mcmodel=small \ 11 | -fno-builtin -fno-stack-protector 12 | 13 | PLATFORM_C := $(wildcard platform/src/*.c) $(wildcard ../openssl-stubs/rand_pool.c) 14 | PLATFORM_H := $(wildcard platform/include/*.h) $(wildcard platform/include/**/*.h) 15 | PLATFORM_OBJ = $(PLATFORM_C:.c=.o) 16 | PLATFORM_INC = -Iplatform/include \ 17 | -Iplatform/include/prototypes 18 | PLATFORM_TARGET = libplatform.a platform.lib 19 | PLATFORM_CFLAGS = 20 | 21 | TPM_C := $(wildcard ../ms-tpm-20-ref/TPMCmd/tpm/src/**/*.c) $(wildcard ../ms-tpm-20-ref/TPMCmd/tpm/src/**/**/*.c) 22 | TPM_H := $(wildcard ../ms-tpm-20-ref/TPMCmd/tpm/include/*.h) $(wildcard ../ms-tpm-20-ref/TPMCmd/tpm/include/**/*.h) 23 | TPM_OBJ = $(TPM_C:.c=.o) 24 | TPM_INC = -I../ms-tpm-20-ref/TPMCmd/tpm/include \ 25 | -I../ms-tpm-20-ref/TPMCmd/tpm/include/prototypes 26 | TPM_CONFIG_INCLUDE = -include ./include/TpmProfile.h 27 | TPM_TARGET = libtpm.a tpm.lib 28 | TPM_DEFINED = -DTHIRTY_TWO_BIT -DRADIX_BITS=32 -DCERTIFYX509_DEBUG=NO -DSIMULATION=NO -DMEM_BACKED_NV -DOPENSSL_API_COMPAT=10101 29 | 30 | ALG_SHA1 ?= ALG_NO 31 | ALG_SHA256 ?= ALG_NO 32 | ALG_SHA384 ?= ALG_YES 33 | ALG_SHA512 ?= ALG_NO 34 | TPM_ALG_DEFINED = -DALG_SHA1=$(ALG_SHA1) -DALG_SHA256=$(ALG_SHA256) -DALG_SHA384=$(ALG_SHA384) -DALG_SHA512=$(ALG_SHA512) 35 | 36 | all: $(PLATFORM_TARGET) $(TPM_TARGET) 37 | 38 | $(PLATFORM_TARGET): $(PLATFORM_OBJ) 39 | $(RM) $@ 40 | $(AR) ru $@ $^ 41 | 42 | $(PLATFORM_OBJ): %.o: %.c $(PLATFORM_H) 43 | $(CC) $(TPM_CONFIG_INCLUDE) $(LIBC_INC) $(PLATFORM_INC) $(TPM_INC) $(OPENSSL_INC) $(TPM_DEFINED) $(TPM_ALG_DEFINED) $(PLATFORM_CFLAGS) $(CFLAGS) -c -o $@ $< 44 | 45 | $(TPM_TARGET): $(TPM_OBJ) 46 | $(RM) $@ 47 | $(AR) ru $@ $^ 48 | 49 | $(TPM_OBJ): %.o: %.c $(TPM_H) 50 | $(CC) $(TPM_CONFIG_INCLUDE) $(LIBC_INC) $(TPM_INC) $(PLATFORM_INC) $(OPENSSL_INC) $(TPM_DEFINED) $(TPM_ALG_DEFINED) $(CFLAGS) -c -o $@ $< 51 | 52 | clean: clean_platform clean_tpm 53 | 54 | clean_platform: 55 | $(RM) $(PLATFORM_OBJ) $(PLATFORM_TARGET) 56 | clean_tpm: 57 | $(RM) $(TPM_OBJ) $(TPM_TARGET) 58 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/tpm/arch/x86_64/base.h: -------------------------------------------------------------------------------- 1 | #ifndef _BASE_H 2 | #define _BASE_H 3 | /// 4 | /// 8-byte unsigned value 5 | /// 6 | typedef unsigned long long UINT64; 7 | /// 8 | /// 8-byte signed value 9 | /// 10 | typedef long long INT64; 11 | /// 12 | /// 4-byte unsigned value 13 | /// 14 | typedef unsigned int UINT32; 15 | /// 16 | /// 4-byte signed value 17 | /// 18 | typedef int INT32; 19 | /// 20 | /// 2-byte unsigned value 21 | /// 22 | typedef unsigned short UINT16; 23 | /// 24 | /// 2-byte Character. Unless otherwise specified all strings are stored in the 25 | /// UTF-16 encoding format as defined by Unicode 2.1 and ISO/IEC 10646 standards. 26 | /// 27 | typedef unsigned short CHAR16; 28 | /// 29 | /// 2-byte signed value 30 | /// 31 | typedef short INT16; 32 | /// 33 | /// Logical Boolean. 1-byte value containing 0 for FALSE or a 1 for TRUE. Other 34 | /// values are undefined. 35 | /// 36 | typedef unsigned char BOOLEAN; 37 | /// 38 | /// 1-byte unsigned value 39 | /// 40 | typedef unsigned char UINT8; 41 | /// 42 | /// 1-byte Character 43 | /// 44 | typedef char CHAR8; 45 | /// 46 | /// 1-byte signed value 47 | /// 48 | typedef signed char INT8; 49 | 50 | 51 | typedef UINT64 UINTN; 52 | typedef INT64 INTN; 53 | 54 | #endif 55 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/tpm/platform/include/Platform.h: -------------------------------------------------------------------------------- 1 | /* Microsoft Reference Implementation for TPM 2.0 2 | * 3 | * The copyright in this software is being made available under the BSD License, 4 | * included below. This software may be subject to other third party and 5 | * contributor rights, including patent rights, and no such rights are granted 6 | * under this license. 7 | * 8 | * Copyright (c) Microsoft Corporation 9 | * 10 | * All rights reserved. 11 | * 12 | * BSD License 13 | * 14 | * Redistribution and use in source and binary forms, with or without modification, 15 | * are permitted provided that the following conditions are met: 16 | * 17 | * Redistributions of source code must retain the above copyright notice, this list 18 | * of conditions and the following disclaimer. 19 | * 20 | * Redistributions in binary form must reproduce the above copyright notice, this 21 | * list of conditions and the following disclaimer in the documentation and/or 22 | * other materials provided with the distribution. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" 25 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 28 | * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 30 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 31 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 33 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | */ 35 | 36 | #ifndef _PLATFORM_H_ 37 | #define _PLATFORM_H_ 38 | 39 | #include "TpmBuildSwitches.h" 40 | #include "BaseTypes.h" 41 | #include "TPMB.h" 42 | #include "MinMax.h" 43 | 44 | #include "TpmProfile.h" 45 | 46 | #include "PlatformACT.h" 47 | #include "PlatformClock.h" 48 | #include "PlatformData.h" 49 | #include "Platform_fp.h" 50 | 51 | 52 | #endif // _PLATFORM_H_ 53 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/tpm/platform/include/PlatformClock.h: -------------------------------------------------------------------------------- 1 | /* Microsoft Reference Implementation for TPM 2.0 2 | * 3 | * The copyright in this software is being made available under the BSD License, 4 | * included below. This software may be subject to other third party and 5 | * contributor rights, including patent rights, and no such rights are granted 6 | * under this license. 7 | * 8 | * Copyright (c) Microsoft Corporation 9 | * 10 | * All rights reserved. 11 | * 12 | * BSD License 13 | * 14 | * Redistribution and use in source and binary forms, with or without modification, 15 | * are permitted provided that the following conditions are met: 16 | * 17 | * Redistributions of source code must retain the above copyright notice, this list 18 | * of conditions and the following disclaimer. 19 | * 20 | * Redistributions in binary form must reproduce the above copyright notice, this 21 | * list of conditions and the following disclaimer in the documentation and/or 22 | * other materials provided with the distribution. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" 25 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 28 | * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 30 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 31 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 33 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | */ 35 | // This file contains the instance data for the Platform module. It is collected 36 | // in this file so that the state of the module is easier to manage. 37 | 38 | #ifndef _PLATFORM_CLOCK_H_ 39 | #define _PLATFORM_CLOCK_H_ 40 | 41 | #ifndef _ARM_ 42 | #ifdef _MSC_VER 43 | #include 44 | #include 45 | #else 46 | // #include 47 | #include 48 | #endif 49 | #endif 50 | // CLOCK_NOMINAL is the number of hardware ticks per mS. A value of 300000 means 51 | // that the nominal clock rate used to drive the hardware clock is 30 MHz. The 52 | // adjustment rates are used to determine the conversion of the hardware ticks to 53 | // internal hardware clock value. In practice, we would expect that there would be 54 | // a hardware register will accumulated mS. It would be incremented by the output 55 | // of a pre-scaler. The pre-scaler would divide the ticks from the clock by some 56 | // value that would compensate for the difference between clock time and real time. 57 | // The code in Clock does the emulation of this function. 58 | #define CLOCK_NOMINAL 30000 59 | // A 1% change in rate is 300 counts 60 | #define CLOCK_ADJUST_COARSE 300 61 | // A 0.1% change in rate is 30 counts 62 | #define CLOCK_ADJUST_MEDIUM 30 63 | // A minimum change in rate is 1 count 64 | #define CLOCK_ADJUST_FINE 1 65 | // The clock tolerance is +/-15% (4500 counts) 66 | // Allow some guard band (16.7%) 67 | #define CLOCK_ADJUST_LIMIT 5000 68 | 69 | #endif // _PLATFORM_CLOCK_H_ 70 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/tpm/platform/src/Cancel.c: -------------------------------------------------------------------------------- 1 | /* Microsoft Reference Implementation for TPM 2.0 2 | * 3 | * The copyright in this software is being made available under the BSD License, 4 | * included below. This software may be subject to other third party and 5 | * contributor rights, including patent rights, and no such rights are granted 6 | * under this license. 7 | * 8 | * Copyright (c) Microsoft Corporation 9 | * 10 | * All rights reserved. 11 | * 12 | * BSD License 13 | * 14 | * Redistribution and use in source and binary forms, with or without modification, 15 | * are permitted provided that the following conditions are met: 16 | * 17 | * Redistributions of source code must retain the above copyright notice, this list 18 | * of conditions and the following disclaimer. 19 | * 20 | * Redistributions in binary form must reproduce the above copyright notice, this 21 | * list of conditions and the following disclaimer in the documentation and/or 22 | * other materials provided with the distribution. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" 25 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 28 | * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 30 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 31 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 33 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | */ 35 | //** Description 36 | // 37 | // This module simulates the cancel pins on the TPM. 38 | // 39 | //** Includes, Typedefs, Structures, and Defines 40 | #include "Platform.h" 41 | 42 | //** Functions 43 | 44 | //***_plat__IsCanceled() 45 | // Check if the cancel flag is set 46 | // Return Type: int 47 | // TRUE(1) if cancel flag is set 48 | // FALSE(0) if cancel flag is not set 49 | LIB_EXPORT int 50 | _plat__IsCanceled( 51 | void 52 | ) 53 | { 54 | // return cancel flag 55 | return s_isCanceled; 56 | } 57 | 58 | //***_plat__SetCancel() 59 | 60 | // Set cancel flag. 61 | LIB_EXPORT void 62 | _plat__SetCancel( 63 | void 64 | ) 65 | { 66 | s_isCanceled = TRUE; 67 | return; 68 | } 69 | 70 | //***_plat__ClearCancel() 71 | // Clear cancel flag 72 | LIB_EXPORT void 73 | _plat__ClearCancel( 74 | void 75 | ) 76 | { 77 | s_isCanceled = FALSE; 78 | return; 79 | } -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/tpm/platform/src/DebugHelpers.c: -------------------------------------------------------------------------------- 1 | /* Microsoft Reference Implementation for TPM 2.0 2 | * 3 | * The copyright in this software is being made available under the BSD License, 4 | * included below. This software may be subject to other third party and 5 | * contributor rights, including patent rights, and no such rights are granted 6 | * under this license. 7 | * 8 | * Copyright (c) Microsoft Corporation 9 | * 10 | * All rights reserved. 11 | * 12 | * BSD License 13 | * 14 | * Redistribution and use in source and binary forms, with or without modification, 15 | * are permitted provided that the following conditions are met: 16 | * 17 | * Redistributions of source code must retain the above copyright notice, this list 18 | * of conditions and the following disclaimer. 19 | * 20 | * Redistributions in binary form must reproduce the above copyright notice, this 21 | * list of conditions and the following disclaimer in the documentation and/or 22 | * other materials provided with the distribution. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" 25 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 28 | * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 30 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 31 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 33 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | */ 35 | //** Description 36 | // 37 | // This file contains the NV read and write access methods. This implementation 38 | // uses RAM/file and does not manage the RAM/file as NV blocks. 39 | // The implementation may become more sophisticated over time. 40 | // 41 | 42 | //** Includes and Local 43 | #include 44 | #include 45 | #include "Platform.h" 46 | 47 | #if CERTIFYX509_DEBUG 48 | 49 | const char *debugFileName = "DebugFile.txt"; 50 | 51 | //*** fileOpen() 52 | // This exists to allow use of the 'safe' version of fopen() with a MS runtime. 53 | static FILE * 54 | fileOpen( 55 | const char *fn, 56 | const char *mode 57 | ) 58 | { 59 | FILE *f; 60 | # if defined _MSC_VER 61 | if(fopen_s(&f, fn, mode) != 0) 62 | f = NULL; 63 | # else 64 | f = fopen(fn, mode); 65 | # endif 66 | return f; 67 | } 68 | 69 | //*** DebugFileInit() 70 | // This function initializes the file containing the debug data with the time of the 71 | // file creation. 72 | // Return Type: int 73 | // 0 success 74 | // != 0 error 75 | int 76 | DebugFileInit( 77 | void 78 | ) 79 | { 80 | FILE *f = NULL; 81 | time_t t = time(NULL); 82 | // 83 | // Get current date and time. 84 | # if defined _MSC_VER 85 | char timeString[100]; 86 | ctime_s(timeString, (size_t)sizeof(timeString), &t); 87 | # else 88 | char *timeString; 89 | timeString = ctime(&t); 90 | # endif 91 | // Try to open the debug file 92 | f = fileOpen(debugFileName, "w"); 93 | if(f) 94 | { 95 | // Initialize the contents with the time. 96 | fprintf(f, "%s\n", timeString); 97 | fclose(f); 98 | return 0; 99 | } 100 | return -1; 101 | } 102 | 103 | //*** DebugDumpBuffer() 104 | void 105 | DebugDumpBuffer( 106 | int size, 107 | unsigned char *buf, 108 | const char *identifier 109 | ) 110 | { 111 | int i; 112 | // 113 | FILE *f = fileOpen(debugFileName, "a"); 114 | if(!f) 115 | return; 116 | if(identifier) 117 | fprintf(f, "%s\n", identifier); 118 | if(buf) 119 | { 120 | for(i = 0; i < size; i++) 121 | { 122 | if(((i % 16) == 0) && (i)) 123 | fprintf(f, "\n"); 124 | fprintf(f, " %02X", buf[i]); 125 | } 126 | if((size % 16) != 0) 127 | fprintf(f, "\n"); 128 | } 129 | fclose(f); 130 | } 131 | 132 | #endif // CERTIFYX509_DEBUG 133 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/tpm/platform/src/Entropy.c: -------------------------------------------------------------------------------- 1 | /* Microsoft Reference Implementation for TPM 2.0 2 | * 3 | * The copyright in this software is being made available under the BSD License, 4 | * included below. This software may be subject to other third party and 5 | * contributor rights, including patent rights, and no such rights are granted 6 | * under this license. 7 | * 8 | * Copyright (c) Microsoft Corporation 9 | * 10 | * All rights reserved. 11 | * 12 | * BSD License 13 | * 14 | * Redistribution and use in source and binary forms, with or without modification, 15 | * are permitted provided that the following conditions are met: 16 | * 17 | * Redistributions of source code must retain the above copyright notice, this list 18 | * of conditions and the following disclaimer. 19 | * 20 | * Redistributions in binary form must reproduce the above copyright notice, this 21 | * list of conditions and the following disclaimer in the documentation and/or 22 | * other materials provided with the distribution. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" 25 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 28 | * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 30 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 31 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 33 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | */ 35 | //** Includes and Local Values 36 | 37 | #define _CRT_RAND_S 38 | #include 39 | #include 40 | #include "Platform.h" 41 | 42 | #ifdef _MSC_VER 43 | #include 44 | #else 45 | // #include 46 | #endif 47 | 48 | // This is the last 32-bits of hardware entropy produced. We have to check to 49 | // see that two consecutive 32-bit values are not the same because 50 | // according to FIPS 140-2, annex C: 51 | // 52 | // "If each call to an RNG produces blocks of n bits (where n > 15), the first 53 | // n-bit block generated after power-up, initialization, or reset shall not be 54 | // used, but shall be saved for comparison with the next n-bit block to be 55 | // generated. Each subsequent generation of an n-bit block shall be compared with 56 | // the previously generated block. The test shall fail if any two compared n-bit 57 | // blocks are equal." 58 | extern uint32_t lastEntropy; 59 | 60 | //** Functions 61 | 62 | //*** rand32() 63 | // Local function to get a 32-bit random number 64 | static uint32_t 65 | rand32( 66 | void 67 | ) 68 | { 69 | extern uint32_t __fw_rdrand32(void); 70 | return __fw_rdrand32(); 71 | } 72 | 73 | //*** _plat__GetEntropy() 74 | // This function is used to get available hardware entropy. In a hardware 75 | // implementation of this function, there would be no call to the system 76 | // to get entropy. 77 | // Return Type: int32_t 78 | // < 0 hardware failure of the entropy generator, this is sticky 79 | // >= 0 the returned amount of entropy (bytes) 80 | // 81 | LIB_EXPORT int32_t 82 | _plat__GetEntropy( 83 | unsigned char *entropy, // output buffer 84 | uint32_t amount // amount requested 85 | ) 86 | { 87 | uint32_t left, multi4_total; 88 | uint32_t tmp_value; 89 | if (amount == 0) { 90 | return 0; 91 | } 92 | left = amount % 4; 93 | multi4_total = amount - left; 94 | if (multi4_total != 0) { 95 | for(uint32_t index = 0; index < multi4_total; index += 4) { 96 | *(uint32_t*)(entropy+index) = rand32(); 97 | } 98 | } 99 | if (left != 0) { 100 | tmp_value = rand32(); 101 | for (uint32_t index = 0; index < left; index++ ) { 102 | *(entropy + multi4_total + index) = *((unsigned char*)&tmp_value + index); 103 | } 104 | } 105 | 106 | return amount; 107 | } -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/tpm/platform/src/LocalityPlat.c: -------------------------------------------------------------------------------- 1 | /* Microsoft Reference Implementation for TPM 2.0 2 | * 3 | * The copyright in this software is being made available under the BSD License, 4 | * included below. This software may be subject to other third party and 5 | * contributor rights, including patent rights, and no such rights are granted 6 | * under this license. 7 | * 8 | * Copyright (c) Microsoft Corporation 9 | * 10 | * All rights reserved. 11 | * 12 | * BSD License 13 | * 14 | * Redistribution and use in source and binary forms, with or without modification, 15 | * are permitted provided that the following conditions are met: 16 | * 17 | * Redistributions of source code must retain the above copyright notice, this list 18 | * of conditions and the following disclaimer. 19 | * 20 | * Redistributions in binary form must reproduce the above copyright notice, this 21 | * list of conditions and the following disclaimer in the documentation and/or 22 | * other materials provided with the distribution. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" 25 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 28 | * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 30 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 31 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 33 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | */ 35 | //** Includes 36 | #include "Platform.h" 37 | 38 | //** Functions 39 | 40 | //***_plat__LocalityGet() 41 | // Get the most recent command locality in locality value form. 42 | // This is an integer value for locality and not a locality structure 43 | // The locality can be 0-4 or 32-255. 5-31 is not allowed. 44 | LIB_EXPORT unsigned char 45 | _plat__LocalityGet( 46 | void 47 | ) 48 | { 49 | return s_locality; 50 | } 51 | 52 | //***_plat__LocalitySet() 53 | // Set the most recent command locality in locality value form 54 | LIB_EXPORT void 55 | _plat__LocalitySet( 56 | unsigned char locality 57 | ) 58 | { 59 | if(locality > 4 && locality < 32) 60 | locality = 0; 61 | s_locality = locality; 62 | return; 63 | } -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/tpm/platform/src/PPPlat.c: -------------------------------------------------------------------------------- 1 | /* Microsoft Reference Implementation for TPM 2.0 2 | * 3 | * The copyright in this software is being made available under the BSD License, 4 | * included below. This software may be subject to other third party and 5 | * contributor rights, including patent rights, and no such rights are granted 6 | * under this license. 7 | * 8 | * Copyright (c) Microsoft Corporation 9 | * 10 | * All rights reserved. 11 | * 12 | * BSD License 13 | * 14 | * Redistribution and use in source and binary forms, with or without modification, 15 | * are permitted provided that the following conditions are met: 16 | * 17 | * Redistributions of source code must retain the above copyright notice, this list 18 | * of conditions and the following disclaimer. 19 | * 20 | * Redistributions in binary form must reproduce the above copyright notice, this 21 | * list of conditions and the following disclaimer in the documentation and/or 22 | * other materials provided with the distribution. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" 25 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 28 | * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 30 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 31 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 33 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | */ 35 | //** Description 36 | 37 | // This module simulates the physical presence interface pins on the TPM. 38 | 39 | //** Includes 40 | #include "Platform.h" 41 | 42 | //** Functions 43 | 44 | //***_plat__PhysicalPresenceAsserted() 45 | // Check if physical presence is signaled 46 | // Return Type: int 47 | // TRUE(1) if physical presence is signaled 48 | // FALSE(0) if physical presence is not signaled 49 | LIB_EXPORT int 50 | _plat__PhysicalPresenceAsserted( 51 | void 52 | ) 53 | { 54 | // Do not know how to check physical presence without real hardware. 55 | // so always return TRUE; 56 | return s_physicalPresence; 57 | } 58 | 59 | //***_plat__Signal_PhysicalPresenceOn() 60 | // Signal physical presence on 61 | LIB_EXPORT void 62 | _plat__Signal_PhysicalPresenceOn( 63 | void 64 | ) 65 | { 66 | s_physicalPresence = TRUE; 67 | return; 68 | } 69 | 70 | //***_plat__Signal_PhysicalPresenceOff() 71 | // Signal physical presence off 72 | LIB_EXPORT void 73 | _plat__Signal_PhysicalPresenceOff( 74 | void 75 | ) 76 | { 77 | s_physicalPresence = FALSE; 78 | return; 79 | } -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/tpm/platform/src/PlatformData.c: -------------------------------------------------------------------------------- 1 | /* Microsoft Reference Implementation for TPM 2.0 2 | * 3 | * The copyright in this software is being made available under the BSD License, 4 | * included below. This software may be subject to other third party and 5 | * contributor rights, including patent rights, and no such rights are granted 6 | * under this license. 7 | * 8 | * Copyright (c) Microsoft Corporation 9 | * 10 | * All rights reserved. 11 | * 12 | * BSD License 13 | * 14 | * Redistribution and use in source and binary forms, with or without modification, 15 | * are permitted provided that the following conditions are met: 16 | * 17 | * Redistributions of source code must retain the above copyright notice, this list 18 | * of conditions and the following disclaimer. 19 | * 20 | * Redistributions in binary form must reproduce the above copyright notice, this 21 | * list of conditions and the following disclaimer in the documentation and/or 22 | * other materials provided with the distribution. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" 25 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 28 | * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 30 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 31 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 33 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | */ 35 | //** Description 36 | // This file will instance the TPM variables that are not stack allocated. The 37 | // descriptions for these variables are in Global.h for this project. 38 | 39 | //** Includes 40 | #define _PLATFORM_DATA_C_ 41 | #include "Platform.h" 42 | -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/tpm/platform/src/PowerPlat.c: -------------------------------------------------------------------------------- 1 | /* Microsoft Reference Implementation for TPM 2.0 2 | * 3 | * The copyright in this software is being made available under the BSD License, 4 | * included below. This software may be subject to other third party and 5 | * contributor rights, including patent rights, and no such rights are granted 6 | * under this license. 7 | * 8 | * Copyright (c) Microsoft Corporation 9 | * 10 | * All rights reserved. 11 | * 12 | * BSD License 13 | * 14 | * Redistribution and use in source and binary forms, with or without modification, 15 | * are permitted provided that the following conditions are met: 16 | * 17 | * Redistributions of source code must retain the above copyright notice, this list 18 | * of conditions and the following disclaimer. 19 | * 20 | * Redistributions in binary form must reproduce the above copyright notice, this 21 | * list of conditions and the following disclaimer in the documentation and/or 22 | * other materials provided with the distribution. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" 25 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 28 | * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 30 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 31 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 33 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | */ 35 | //** Includes and Function Prototypes 36 | 37 | #include "Platform.h" 38 | #include "_TPM_Init_fp.h" 39 | 40 | //** Functions 41 | 42 | //***_plat__Signal_PowerOn() 43 | // Signal platform power on 44 | LIB_EXPORT int 45 | _plat__Signal_PowerOn( 46 | void 47 | ) 48 | { 49 | // Reset the timer 50 | _plat__TimerReset(); 51 | 52 | // Need to indicate that we lost power 53 | s_powerLost = TRUE; 54 | 55 | return 0; 56 | } 57 | 58 | //*** _plat__WasPowerLost() 59 | // Test whether power was lost before a _TPM_Init. 60 | // 61 | // This function will clear the "hardware" indication of power loss before return. 62 | // This means that there can only be one spot in the TPM code where this value 63 | // gets read. This method is used here as it is the most difficult to manage in the 64 | // TPM code and, if the hardware actually works this way, it is hard to make it 65 | // look like anything else. So, the burden is placed on the TPM code rather than the 66 | // platform code 67 | // Return Type: int 68 | // TRUE(1) power was lost 69 | // FALSE(0) power was not lost 70 | LIB_EXPORT int 71 | _plat__WasPowerLost( 72 | void 73 | ) 74 | { 75 | int retVal = s_powerLost; 76 | s_powerLost = FALSE; 77 | return retVal; 78 | } 79 | 80 | //*** _plat_Signal_Reset() 81 | // This a TPM reset without a power loss. 82 | LIB_EXPORT int 83 | _plat__Signal_Reset( 84 | void 85 | ) 86 | { 87 | // Initialize locality 88 | s_locality = 0; 89 | 90 | // Command cancel 91 | s_isCanceled = FALSE; 92 | 93 | _TPM_Init(); 94 | 95 | // if we are doing reset but did not have a power failure, then we should 96 | // not need to reload NV ... 97 | 98 | return 0; 99 | } 100 | 101 | //***_plat__Signal_PowerOff() 102 | // Signal platform power off 103 | LIB_EXPORT void 104 | _plat__Signal_PowerOff( 105 | void 106 | ) 107 | { 108 | // Prepare NV memory for power off 109 | _plat__NVDisable(0); 110 | 111 | // Disable tick ACT tick processing 112 | _plat__ACT_EnableTicks(FALSE); 113 | 114 | return; 115 | } -------------------------------------------------------------------------------- /deps/rust-tpm-20-ref/tpm/platform/src/Unique.c: -------------------------------------------------------------------------------- 1 | /* Microsoft Reference Implementation for TPM 2.0 2 | * 3 | * The copyright in this software is being made available under the BSD License, 4 | * included below. This software may be subject to other third party and 5 | * contributor rights, including patent rights, and no such rights are granted 6 | * under this license. 7 | * 8 | * Copyright (c) Microsoft Corporation 9 | * 10 | * All rights reserved. 11 | * 12 | * BSD License 13 | * 14 | * Redistribution and use in source and binary forms, with or without modification, 15 | * are permitted provided that the following conditions are met: 16 | * 17 | * Redistributions of source code must retain the above copyright notice, this list 18 | * of conditions and the following disclaimer. 19 | * 20 | * Redistributions in binary form must reproduce the above copyright notice, this 21 | * list of conditions and the following disclaimer in the documentation and/or 22 | * other materials provided with the distribution. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" 25 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 28 | * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 30 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 31 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 33 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | */ 35 | //** Introduction 36 | // In some implementations of the TPM, the hardware can provide a secret 37 | // value to the TPM. This secret value is statistically unique to the 38 | // instance of the TPM. Typical uses of this value are to provide 39 | // personalization to the random number generation and as a shared secret 40 | // between the TPM and the manufacturer. 41 | 42 | //** Includes 43 | #include "Platform.h" 44 | 45 | const char notReallyUnique[] = 46 | "This is not really a unique value. A real unique value should" 47 | " be generated by the platform."; 48 | 49 | //** _plat__GetUnique() 50 | // This function is used to access the platform-specific unique value. 51 | // This function places the unique value in the provided buffer ('b') 52 | // and returns the number of bytes transferred. The function will not 53 | // copy more data than 'bSize'. 54 | // NOTE: If a platform unique value has unequal distribution of uniqueness 55 | // and 'bSize' is smaller than the size of the unique value, the 'bSize' 56 | // portion with the most uniqueness should be returned. 57 | LIB_EXPORT uint32_t 58 | _plat__GetUnique( 59 | uint32_t which, // authorities (0) or details 60 | uint32_t bSize, // size of the buffer 61 | unsigned char *b // output buffer 62 | ) 63 | { 64 | const char *from = notReallyUnique; 65 | uint32_t retVal = 0; 66 | 67 | if(which == 0) // the authorities value 68 | { 69 | for(retVal = 0; 70 | *from != 0 && retVal < bSize; 71 | retVal++) 72 | { 73 | *b++ = *from++; 74 | } 75 | } 76 | else 77 | { 78 | #define uSize sizeof(notReallyUnique) 79 | b = &b[((bSize < uSize) ? bSize : uSize) - 1]; 80 | for(retVal = 0; 81 | *from != 0 && retVal < bSize; 82 | retVal++) 83 | { 84 | *b-- = *from++; 85 | } 86 | } 87 | return retVal; 88 | } -------------------------------------------------------------------------------- /doc/Intel TD based virtual TPM Design Guide Rev 0.7.8.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intel/vtpm-td/00a2f8619661a4a7ee26efd47fbb4c5efbcab869/doc/Intel TD based virtual TPM Design Guide Rev 0.7.8.pdf -------------------------------------------------------------------------------- /doc/integration-test.md: -------------------------------------------------------------------------------- 1 | # vtpm-td integration test 2 | ## Pre-condition 3 | Current vtpm-td works with [Linux TDX Stack](https://github.com/intel/tdx-tools/releases/tag/2023ww27). Please follow the [readme](https://github.com/intel/tdx-tools/blob/2023ww27/README.md) to prepare TDX environment. 4 | - Install host kernel 5 | - Install QEMU 6 | - Setup attestion environment 7 | - Create guest kernel Image 8 | 9 | ## Run intergation test 10 | #### Preparation 11 | Build Test Images 12 | - Build [TDVF](https://github.com/tianocore/edk2-staging/tree/TDVF) follow [readme](https://github.com/tianocore/edk2-staging/blob/TDVF/OvmfPkg/IntelTdx/README) 13 | - Build vTPM TD follow [readme](../README.md) 14 | 15 | Download test script: 16 | ``` 17 | git clone https://github.com/intel/vtpm-td.git 18 | ``` 19 | Go to script folder: 20 | ``` 21 | cd sh_script 22 | ``` 23 | Config [test configration file](../sh_script/conf/pyproject.toml), for example: 24 | ``` 25 | [vtpm.config] 26 | qemu="/usr/mvp/bin/qemu-system-x86_64" 27 | vtpm_td_script = "launch_vtpm_td.sh" 28 | user_td_script = "launch_user_td.sh" 29 | vtpm_td_bios_img = "../../run-vtpm-td/vtpmtd.bin" 30 | user_td_bios_img = "../../run-user-td/OVMF.fd" 31 | kernel_img = "/home/env/vtpm/vmlinuz-jammy" 32 | guest_img = "/home/env/vtpm/td-guest-ubuntu-22.04-test.qcow2" 33 | guest_username = "root" 34 | guest_password = "123456" 35 | vtpm_test_img = "/home/env/vtpm/vtpm.img" 36 | vtpm_test_img_mount_path = "/media/vtpm" 37 | default_user_id = "aabbccdd-2012-2022-1234-123456789123" 38 | default_startup_cmds = [ 39 | "fs0:", 40 | ] 41 | stress_test_cycles = 1000 42 | ``` 43 | 44 | #### Setup pytest environment 45 | Please use recommend configuration in [integration_test.py](../sh_script/integration_test.py). 46 | 47 | #### Run test with TDVF config-A 48 | ``` 49 | pytest -k "config_A" 50 | ``` 51 | 52 | #### Run test with TDVF config-B 53 | ``` 54 | pytest -k "config_B_no_sb" 55 | ``` 56 | 57 | #### Run test with TDVF config-B + Secure Boot 58 | ``` 59 | pytest -k "config_B_sb" 60 | ``` 61 | 62 | #### Run stress test with TDVF config-B 63 | ``` 64 | pytest -k "stress" 65 | ``` 66 | 67 | #### Run all tpm commands with tpm2_tools 68 | ``` 69 | pytest -k "test_tpm_cmd_with_vtpm" 70 | ``` -------------------------------------------------------------------------------- /doc/tpm2_pcrread.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intel/vtpm-td/00a2f8619661a4a7ee26efd47fbb4c5efbcab869/doc/tpm2_pcrread.png -------------------------------------------------------------------------------- /doc/verify-vtpm-features.md: -------------------------------------------------------------------------------- 1 | # Verify vTPM features 2 | After booting up to TD guest OS, vTPM features can be used as normal TPM. It can be verified by: 3 | * [tpm2-tools](#tpm2-tools) 4 | * [LinuxIMA (Integrity Measurement Architecture)](#linux-ima) 5 | * [Keylime](#keylime) 6 | ## tpm2-tools 7 | It’s recommended to build and install tpm2-tools in TD guest image. 8 | Please install the following dependencies before building and installing tpm2-tools. 9 | ``` 10 | $ sudo apt-get -y install \ 11 | autoconf-archive libcmocka0 libcmocka-dev procps iproute2 \ 12 | build-essential git pkg-config gcc libtool automake libssl-dev \ 13 | uthash-dev autoconf doxygen libjson-c-dev libini-config-dev \ 14 | libcurl4-openssl-dev uuid-dev libltdl-dev libusb-1.0-0-dev \ 15 | libarchive-dev clang libglib2.0-dev 16 | ``` 17 | Follow document: https://tpm2-tools.readthedocs.io/en/latest/INSTALL/ to build and install tpm2-tools. 18 | 19 | Run [tpm2_pcrread](https://tpm2-tools.readthedocs.io/en/latest/man/tpm2_pcrread.1/) to read the PCR registers. 20 | ![TPM2_PCRREAD](tpm2_pcrread.png) 21 | 22 | ## Linux IMA 23 | Linux IMA (Integrity Measurement Architecture) is enabled by extending IMA measurement 24 | to RTMR and vTPM PCRs, which enables user space application runtime measurement. 25 | Runtime measurements within TD guest can avoid being compromised and use to attest to 26 | the system's runtime integrity. 27 | 28 | ## Keylime 29 | vTPM can be used for [Keylime](https://github.com/keylime/rust-keylime) to do remote attestation 30 | with Linux IMA enabled. Keylime verifier will do continually remote attestation with Linux IMA 31 | measurement records protected with vTPM from Keylime agent deployed inside TDVM and compare against 32 | know good values provided by trusted admin or third parties. 33 | 34 | Note: Keylime must include the patch#88e033c3a which fixes the SHA1 issue for TPM PCR16. 35 | 36 | ## Quote Verification 37 | ### Precondition 38 | Refer to [Whitepaper: Linux* Stacks for Intel® Trust Domain Extension 1.0](https://www.intel.com/content/www/us/en/content-details/783067/whitepaper-linux-stacks-for-intel-trust-domain-extension-1-0.html) to set up Attestation environment. 39 | - Follow chapter 4.3.2 to "Set Up DCAP Repo(Host)" 40 | - Follow chapter 4.3.3 to "Set Up PCCS" 41 | - Follow chapter 4.3.4 to "Set Up DCAP on Host" 42 | - Follow chapter 4.3.6 to build quote verification sample application 43 | 44 | ### Export CA certificate from vTPM NV 45 | Run below script on guest OS to export CA. 46 | ``` 47 | #!/bin/bash 48 | 49 | rm -rf ca_cert* 50 | NVINFO=`tpm2_nvreadpublic` 51 | 52 | for i in {0..5}; do 53 | INDEX=0x1c0010$i 54 | if [[ $NVINFO == *"$INDEX"* ]] 55 | then 56 | NV_SIZE=`tpm2_nvreadpublic $INDEX | grep size | awk '{print $2}'` 57 | tpm2_nvread --hierarchy owner --size $NV_SIZE --output ca_cert$i.bin $INDEX 58 | cat ca_cert$i.bin >> ca_cert.bin 59 | fi 60 | done 61 | ``` 62 | ### Convert CA certificate format from der to pem 63 | Run below script on guest OS to export CA. 64 | ``` 65 | openssl x509 -inform DER -in ca_cert.bin -outform PEM -out ca_cert.pem 66 | ``` 67 | ### Export quote data from CA with python script 68 | Run below python script to export quote.data from CA. 69 | ``` 70 | // pip install pyopenssl 71 | import OpenSSL 72 | 73 | quote_extension_index=2 74 | 75 | cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, open("ca_cert.pem").read()) 76 | certIssue = cert.get_issuer() 77 | 78 | with open("quote.data", "wb") as fp: 79 | fp.write(cert.get_extension(quote_extension_index).get_data()) 80 | print("quote data export successfully: quote.data") 81 | ``` 82 | ### Copy quote.date from guest OS to host 83 | ``` 84 | virt-copy-out -a 85 | 86 | ``` 87 | ### Verify quote date with sample application 88 | ``` 89 | ./app -quote /quote.data 90 | ``` -------------------------------------------------------------------------------- /doc/vtpm-overview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intel/vtpm-td/00a2f8619661a4a7ee26efd47fbb4c5efbcab869/doc/vtpm-overview.png -------------------------------------------------------------------------------- /license.md: -------------------------------------------------------------------------------- 1 | This project uses Apache License 2.0. 2 | 3 | [SPDX-License-Identifier](https://spdx.org/licenses/):[Apache-2.0](https://spdx.org/licenses/Apache-2.0.html). 4 | 5 | ``` 6 | Copyright (c) 2021-2023, Intel Corporation. All rights reserved. 7 | 8 | SPDX-License-Identifier: Apache License 2.0 9 | ``` 10 | 11 | Some of the files are derived from [td-shim](https://github.com/confidential-containers/td-shim) project. 12 | They reuse [td-shim license](https://github.com/confidential-containers/td-shim/blob/main/LICENSE) - [BSD-2-Clause-Patent](https://spdx.org/licenses/BSD-2-Clause-Patent.html). 13 | 14 | Some of the files are derived from [rust-hypervisor-firmware](https://github.com/cloud-hypervisor/rust-hypervisor-firmware) project. 15 | They reuse [rust-hypervisor-firmware license](https://github.com/cloud-hypervisor/rust-hypervisor-firmware/blob/master/LICENSE) - [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html). 16 | 17 | Some of the files are derived from [ms-tpm-20-ref](https://github.com/Microsoft/ms-tpm-20-ref/) project. 18 | They reuse [ms-tpm-20-ref license](https://github.com/microsoft/ms-tpm-20-ref/blob/main/LICENSE). 19 | -------------------------------------------------------------------------------- /rust-toolchain: -------------------------------------------------------------------------------- 1 | nightly-2023-12-31 2 | -------------------------------------------------------------------------------- /security.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | Intel is committed to rapidly addressing security vulnerabilities affecting our customers and providing clear guidance on the solution, impact, severity and mitigation. 3 | 4 | ## Reporting a Vulnerability 5 | Please report any security vulnerabilities in this project utilizing the guidelines [here](https://www.intel.com/content/www/us/en/security-center/vulnerability-handling-guidelines.html). 6 | -------------------------------------------------------------------------------- /sh_script/build.sh: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2022 - 2023 Intel Corporation 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | 5 | #!/bin/bash 6 | 7 | ALGO="sha256,sha384" 8 | BUILD_OPT="build" 9 | ENABLE_BENCHMARK=0 10 | REMOTE_ATTESTATION="on" 11 | 12 | usage() { 13 | echo "$0 [options]" 14 | echo "Available :" 15 | echo " -algo [sha256,sha384,sha512] Supported hash algorithm. (Default supported algorithms are sha256 and sha384)" 16 | echo " -clean Clean the build objects" 17 | echo " -bench Enable benchmark. (Default is disabled.)" 18 | echo " -attest [on|off] Enable remote attestation. (Default is on.)" 19 | exit 1 20 | } 21 | 22 | function clean() { 23 | pushd deps/rust-tpm-20-ref 24 | /bin/bash sh_script/build.sh -clean 25 | popd 26 | 27 | pushd deps/td-shim 28 | cargo clean 29 | popd 30 | 31 | pushd deps/spdm-rs 32 | cargo clean 33 | popd 34 | 35 | cargo clean 36 | } 37 | 38 | function build() { 39 | VTPM_FEATURES="td-logger/tdx" 40 | RENAME_SYMBOL_FLAG="" 41 | 42 | [[ "${ALGO}" != "" ]] && VTPM_FEATURES+=",${ALGO}" 43 | 44 | [[ ${ENABLE_BENCHMARK} == 1 ]] && VTPM_FEATURES+=",test_heap_size,test_stack_size" 45 | 46 | if [ "${REMOTE_ATTESTATION}" == "on" ]; then 47 | VTPM_FEATURES+=",remote-attestation" 48 | RENAME_SYMBOL_FLAG="-rename_symbol" 49 | fi 50 | 51 | pushd deps/rust-tpm-20-ref 52 | /bin/bash sh_script/build.sh -algo ${ALGO} ${RENAME_SYMBOL_FLAG} 53 | popd 54 | 55 | pushd deps/td-shim/devtools/td-layout-config 56 | cargo run -- -t memory ../../../../config/shim_layout.json -o ../../td-layout/src/runtime/exec.rs 57 | popd 58 | 59 | pushd deps/td-shim 60 | cargo xbuild -p td-shim \ 61 | --target x86_64-unknown-none \ 62 | --release --features=main,tdx \ 63 | --no-default-features 64 | popd 65 | 66 | cargo xbuild \ 67 | --target x86_64-unknown-none \ 68 | --features=${VTPM_FEATURES} \ 69 | -p vtpmtd --release 70 | 71 | pushd deps/td-shim 72 | cargo run -p td-shim-tools \ 73 | --bin td-shim-ld --features=linker \ 74 | --no-default-features \ 75 | -- target/x86_64-unknown-none/release/ResetVector.bin target/x86_64-unknown-none/release/td-shim \ 76 | -p ../../target/x86_64-unknown-none/release/vtpmtd \ 77 | -t executable \ 78 | -m ../../config/metadata.json \ 79 | -o target/x86_64-unknown-none/release/vtpmtd.bin 80 | 81 | cargo run -p td-shim-tools --features=enroller \ 82 | --bin td-shim-enroll target/x86_64-unknown-none/release/vtpmtd.bin \ 83 | -f 4fd44f20-0ee5-4362-9414-a04b32469bc9 ../../config/intel_root_sbx.der \ 84 | -o ../../target/x86_64-unknown-none/release/vtpmtd.bin 85 | popd 86 | } 87 | 88 | while [[ $1 != "" ]]; do 89 | case "$1" in 90 | -algo) 91 | ALGO=$2 92 | shift 93 | ;; 94 | -clean) 95 | BUILD_OPT="clean" 96 | shift 97 | ;; 98 | -attest) 99 | REMOTE_ATTESTATION=$2 100 | shift 101 | ;; 102 | -bench) 103 | ENABLE_BENCHMARK=1 104 | shift 105 | ;; 106 | *) usage;; 107 | esac 108 | shift 109 | done 110 | 111 | set -ex 112 | 113 | export CC=clang 114 | export AR=llvm-ar 115 | 116 | case "${BUILD_OPT}" in 117 | clean) clean ;; 118 | build) build ;; 119 | 120 | *) echo "unknown build option - ${BUILD_OPT}" ;; 121 | esac 122 | -------------------------------------------------------------------------------- /sh_script/conf/pyproject.toml: -------------------------------------------------------------------------------- 1 | [vtpm.config] 2 | qemu="/usr/mvp/bin/qemu-system-x86_64" 3 | vtpm_td_script = "launch_vtpm_td.sh" 4 | user_td_script = "launch_user_td.sh" 5 | vtpm_td_bios_img = "../../run-vtpm-td/vtpmtd.bin" 6 | user_td_bios_img = "../../run-user-td/OVMF.fd" 7 | kernel_img = "/home/env/vtpm/vmlinuz-jammy" 8 | guest_img = "/home/env/vtpm/td-guest-ubuntu-22.04-test.qcow2" 9 | guest_username = "root" 10 | guest_password = "123456" 11 | vtpm_test_img = "/home/env/vtpm/vtpm.img" 12 | vtpm_test_img_mount_path = "/media/vtpm" 13 | quote_verification_sample_path = "/home/env/dcap/linux-sgx/external/dcap_source/SampleCode/QuoteVerificationSample" 14 | stress_test_cycles = 1000 15 | default_user_id = "aabbccdd-2012-2022-1234-123456789123" 16 | default_startup_cmds = [ 17 | "fs0:", 18 | ] 19 | -------------------------------------------------------------------------------- /sh_script/docker.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | FOLDER="" 5 | 6 | usage() { 7 | cat << EOM 8 | Usage: $(basename "$0") [OPTION]... 9 | -d Path of Dockerfile. 10 | EOM 11 | } 12 | 13 | error() { 14 | echo -e "\e[1;31mERROR: $*\e[0;0m" 15 | exit 1 16 | } 17 | 18 | process_args() { 19 | while getopts ":f:h" option; do 20 | case "$option" in 21 | f) FOLDER=$OPTARG;; 22 | h) usage 23 | exit 0 24 | ;; 25 | *) 26 | echo "Invalid option '-$OPTARG'" 27 | usage 28 | exit 1 29 | ;; 30 | esac 31 | done 32 | 33 | if [[ -z ${FOLDER} ]]; then 34 | error "Please specify the folder of where the Dockerfile is located through -f." 35 | fi 36 | 37 | if [[ ! -f "${FOLDER}/Dockerfile" ]]; then 38 | error "Dockerfile does not exist." 39 | fi 40 | } 41 | 42 | process_args $@ 43 | 44 | pushd ${FOLDER} 45 | 46 | # If the docker image does not exist, build the docker image 47 | set +e && docker image inspect vtpmtd.build.env:latest > /dev/null 2>&1 && set -e 48 | if [ $? != 0 ]; then 49 | docker build -t vtpmtd.build.env \ 50 | --build-arg https_proxy=$https_proxy \ 51 | --build-arg http_proxy=$http_proxy \ 52 | . 53 | fi 54 | 55 | popd 56 | 57 | # Run the docker image 58 | docker run -it --rm vtpmtd.build.env 59 | -------------------------------------------------------------------------------- /sh_script/ek_cert.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | CURR_DIR=$(readlink -f "$(dirname "$0")") 5 | 6 | CREATEEK="tpm2_createek" 7 | NVDEFINE="tpm2_nvdefine" 8 | NVWRITE="tpm2_nvwrite" 9 | OPENSSL="openssl" 10 | 11 | EKALG="ecc384" 12 | EKAUTH="" 13 | OWAUTH="" 14 | EKCTX="" 15 | CA="" 16 | CAKEY="" 17 | CAPSW="" 18 | SUBJ="" 19 | 20 | EK_CMD="${CREATEEK}" 21 | GENERATE_CMD="${OPENSSL} x509 -new" 22 | 23 | EK_NV_INDEX="0x01c00002" 24 | EK_NV_ATTR="ownerread|policyread|policywrite|ownerwrite|authread|authwrite" 25 | EK_PUB="ek.pub" 26 | EK_CERT="ek.crt" 27 | 28 | usage() { 29 | cat << EOM 30 | Usage: $(basename "$0") [OPTION]... 31 | -g Default is ecc384, supported values: [rsa/rsa2048/rsa3072/ecc/ecc256/ecc384] 32 | -a The authorization value for the endorsement hierarchy, default is empty 33 | -w The authorization value for the owner hierarchy, default is empty 34 | -t Either a file path or a persistent handle value to save the endorsement key. 35 | -k CA signing key file name 36 | -c CA certficate file name 37 | -p The password for the CA key, default is empty 38 | -j Set the subject name of EK certificate to the given value when it is created. 39 | EOM 40 | } 41 | 42 | error() { 43 | echo -e "\e[1;31mERROR: $*\e[0;0m" 44 | exit 1 45 | } 46 | 47 | warn() { 48 | echo -e "\e[1;33mWARN: $*\e[0;0m" 49 | } 50 | 51 | process_args() { 52 | while getopts ":g:a:w:t:k:c:p:j:h:" option; do 53 | case "$option" in 54 | g) EKALG=$OPTARG;; 55 | a) EKAUTH=$OPTARG;; 56 | w) OWAUTH=$OPTARG;; 57 | t) EKCTX=$OPTARG;; 58 | k) CAKEY=$OPTARG;; 59 | c) CA=$OPTARG;; 60 | p) CAPSW=$OPTARG;; 61 | j) SUBJ=$OPTARG;; 62 | h) usage 63 | exit 0 64 | ;; 65 | *) 66 | echo "Invalid option '-$OPTARG'" 67 | usage 68 | exit 1 69 | ;; 70 | esac 71 | done 72 | 73 | if [[ -z ${EKCTX} ]]; then 74 | error "Please specify the endorsement key context through -t." 75 | fi 76 | 77 | if [[ -z ${CA} ]]; then 78 | error "Please specify the CA file through -c." 79 | fi 80 | 81 | if [[ ! -f ${CA} ]]; then 82 | error "CA file ${CA} does not exist." 83 | fi 84 | 85 | if [[ -z ${CAKEY} ]]; then 86 | error "Please specify the CA key file through -k." 87 | fi 88 | 89 | if [[ ! -f ${CAKEY} ]]; then 90 | error "CA key file ${CAKEY} does not exist." 91 | fi 92 | 93 | if [[ -z ${SUBJ} ]]; then 94 | error "Please specify the subject name of EK certificate through -j." 95 | fi 96 | 97 | case "${EKALG}" in 98 | rsa|rsa2048|rsa3072) echo "";; 99 | ecc|ecc256|ecc384) echo "";; 100 | *) die "Unspported ek algorithm: ${type}";; 101 | esac 102 | 103 | if [[ ! -z ${EKAUTH} ]]; then 104 | EK_CMD+="-P ${EKAUTH}" 105 | fi 106 | if [[ ! -z ${OWAUTH} ]]; then 107 | EK_CMD+="-w ${OWAUTH}" 108 | fi 109 | EK_CMD+=" -c ${EKCTX} -G ${EKALG} -u ${EK_PUB} -f pem" 110 | 111 | GENERATE_CMD+=" -force_pubkey ${EK_PUB} -subj ${SUBJ} -CA ${CA} -CAkey ${CAKEY} -out ${EK_CERT}" 112 | } 113 | 114 | set_ek_cert() { 115 | DEFINE="${NVDEFINE} ${EK_NV_INDEX} -C o -a ${EK_NV_ATTR}" 116 | echo "Run: ${DEFINE}" 117 | ${DEFINE} 118 | 119 | WRITE="${NVWRITE} ${EK_NV_INDEX} -C o -i ${EK_CERT}" 120 | echo "Run: ${WRITE}" 121 | ${WRITE} 122 | } 123 | 124 | ek_cert() { 125 | echo "Creating endorsement key... ${EK_CMD}" 126 | ${EK_CMD} 127 | echo "Generating EK certificate... ${GENERATE_CMD}" 128 | ${GENERATE_CMD} 129 | echo "Provisioning EK certificate to TPM... ${PROVISION_CMD}" 130 | set_ek_cert 131 | } 132 | 133 | process_args "$@" 134 | ek_cert 135 | -------------------------------------------------------------------------------- /sh_script/launch_vtpm_td.sh: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2022 - 2023 Intel Corporation 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | 5 | #!/bin/bash 6 | 7 | QEMU=/usr/local/bin/qemu-system-x86_64 8 | BIOS= 9 | USERTD_ID=aabbccdd-2012-2022-1234-123456789123 10 | MEM=32M 11 | 12 | now=$(date +"%m%d_%H%M%S") 13 | LOGDIR=log_vtpmtd 14 | LOGFILE=${LOGDIR}/vtpmtd.${now}.log 15 | 16 | usage() { 17 | cat << EOM 18 | Usage: $(basename "$0") [OPTION]... 19 | -f Firmware image file 20 | -q QEMU path 21 | -u User TD ID - GUID 22 | -h Show this help 23 | EOM 24 | } 25 | 26 | process_args() { 27 | while getopts "f:q:u:h" option; do 28 | case "${option}" in 29 | f) BIOS=$OPTARG;; 30 | q) QEMU=$OPTARG;; 31 | u) USERTD_ID=$OPTARG;; 32 | h) usage 33 | exit 0 34 | ;; 35 | *) 36 | echo "Invalid option '-$OPTARG'" 37 | usage 38 | exit 1 39 | ;; 40 | esac 41 | done 42 | 43 | if [[ ! -f ${BIOS} ]]; then 44 | usage 45 | echo "vTPM image file ${BIOS} not exist, Please specify via option \"-f\"" 46 | exit 1 47 | fi 48 | 49 | if [[ ! -f ${QEMU} ]]; then 50 | usage 51 | echo "QEMU ${QEMU} is not exist, Please specify via option \"-q\"" 52 | exit 1 53 | fi 54 | 55 | QEMU_CMD="$QEMU \ 56 | -accel kvm \ 57 | -name debug-threads=on,process=vtpm-td-ci \ 58 | -cpu host,host-phys-bits,-kvm-steal-time,-arch-lbr \ 59 | -smp 1 -m ${MEM} \ 60 | -object tdx-guest,id=tdx,vtpm-type=server,quote-generation-service=vsock:1:4050,vtpm-userid=${USERTD_ID},vtpm-path=unix:/tmp/vtpm-server-${USERTD_ID}.sock \ 61 | -qmp unix:/tmp/qmp-sock-vtpm-${USERTD_ID},server,nowait \ 62 | -object memory-backend-memfd-private,id=vtpm-ram1-${USERTD_ID},size=${MEM} \ 63 | -machine q35,kernel_irqchip=split,confidential-guest-support=tdx,memory-backend=vtpm-ram1-${USERTD_ID} \ 64 | -bios ${BIOS} \ 65 | -nographic \ 66 | -vga none \ 67 | -no-hpet \ 68 | -nodefaults \ 69 | -chardev stdio,id=mux,mux=on,signal=off,logfile=${LOGFILE} \ 70 | -device virtio-serial,romfile= \ 71 | -device virtconsole,chardev=mux -serial chardev:mux -monitor chardev:mux \ 72 | -d int -no-reboot" 73 | } 74 | 75 | create_log_dir() { 76 | if [[ ! -d ${LOGDIR} ]]; then 77 | echo "Create log folder: ${LOGDIR}" 78 | mkdir ${LOGDIR} 79 | fi 80 | } 81 | 82 | launch_vtpm_td() { 83 | create_log_dir 84 | echo ${QEMU_CMD} 85 | eval $QEMU_CMD 86 | } 87 | 88 | process_args "$@" 89 | launch_vtpm_td -------------------------------------------------------------------------------- /sh_script/pre-build.sh: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2022 - 2023 Intel Corporation 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | 5 | #!/bin/sh 6 | 7 | function patch_tdshim() { 8 | pushd deps/td-shim 9 | sh_script/preparation.sh 10 | popd 11 | } 12 | 13 | function patch_rustspdm() { 14 | pushd deps/spdm-rs 15 | sh_script/pre-build.sh 16 | popd 17 | } 18 | 19 | function patch_mstpm20ref() { 20 | pushd deps/rust-tpm-20-ref 21 | sh_script/pre-build.sh 22 | popd 23 | } 24 | 25 | patch_tdshim 26 | patch_rustspdm 27 | patch_mstpm20ref -------------------------------------------------------------------------------- /sh_script/pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | addopts=-v -s -p no:warnings 3 | log_cli = False 4 | log_cli_level = ERROR 5 | log_cli_format = %(asctime)s [%(levelname)s] | %(filename)s:%(lineno)s | %(message)s 6 | log_cli_date_format = %Y-%m-%d %H:%M:%S -------------------------------------------------------------------------------- /sh_script/secure_boot/FB_NO_REBOOT.bin: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /sh_script/secure_boot/SecureBootEnable.bin: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /sh_script/secure_boot/key_gen.sh: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2022 - 2023 Intel Corporation 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | 5 | #!/bin/bash 6 | openssl req -new -x509 -newkey rsa:2048 -subj "/CN=$NAME PK/" -keyout PK.key \ 7 | -out PK.crt -days 3650 -nodes -sha256 8 | openssl req -new -x509 -newkey rsa:2048 -subj "/CN=$NAME KEK/" -keyout KEK.key \ 9 | -out KEK.crt -days 3650 -nodes -sha256 10 | openssl req -new -x509 -newkey rsa:2048 -subj "/CN=$NAME DB/" -keyout DB.key \ 11 | -out DB.crt -days 3650 -nodes -sha256 12 | openssl x509 -in PK.crt -out PK.cer -outform DER 13 | openssl x509 -in KEK.crt -out KEK.cer -outform DER 14 | openssl x509 -in DB.crt -out DB.cer -outform DER 15 | GUID=$(python3 -c 'import uuid; print(str(uuid.uuid1()))') 16 | echo $GUID > myGUID.txt 17 | chmod 0600 *.key -------------------------------------------------------------------------------- /sh_script/unit_test.sh: -------------------------------------------------------------------------------- 1 | readonly script_name=${0##*/} 2 | 3 | unit_test_folder=( 4 | "src/protocol" 5 | ) 6 | 7 | export RUSTFLAGS="-Cinstrument-coverage" 8 | export LLVM_PROFILE_FILE="unittest-%p-%m.profraw" 9 | 10 | find . -name "*.profraw" | xargs rm -rf 11 | 12 | for path in ${unit_test_folder[@]}; do 13 | pushd $path 14 | cargo test 15 | grcov . --binary-path ../../target/debug/ -s . -t html --branch --ignore-not-existing -o unit_test_coverage 16 | popd 17 | done 18 | 19 | unset RUSTFLAGS 20 | unset LLVM_PROFILE_FILE -------------------------------------------------------------------------------- /src/attestation/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "attestation" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | crypto = { path = "../crypto" } 10 | der = { version = "0.7.9", features = ["oid", "alloc", "derive"] } 11 | spin = "0.9.2" 12 | tdx-tdcall = { path = "../../deps/td-shim/tdx-tdcall"} 13 | td-payload = { path = "../../deps/td-shim/td-payload", features = ["tdx"] } 14 | 15 | [features] 16 | default = ["remote-attestation"] 17 | remote-attestation = [] 18 | test = [] 19 | -------------------------------------------------------------------------------- /src/attestation/build.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: BSD-2-Clause-Patent 4 | 5 | use std::env; 6 | use std::process::Command; 7 | 8 | fn main() { 9 | // Skip the compilation of attestation library when the remote attestation is not enabled or 10 | // running unit test. 11 | if cfg!(any(not(feature = "remote-attestation"), feature = "test")) { 12 | return; 13 | } 14 | 15 | // Always use release build of attestation library. 16 | // Cargo will set the "DEBUG" variable to "false" if the profile is release, but it will 17 | // affect the behavior of the make of attestation lib. Remove the "DEBUG" variable if its 18 | // value is "false". 19 | let _ = env::var("DEBUG").ok().map(|_| env::remove_var("DEBUG")); 20 | 21 | // Unset the CC and AR variable 22 | let _ = env::var("CC").ok().map(|_| env::remove_var("CC")); 23 | let _ = env::var("AR").ok().map(|_| env::remove_var("AR")); 24 | 25 | let crate_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); 26 | let lib_path = crate_path 27 | .join("../../deps/linux-sgx") 28 | .display() 29 | .to_string(); 30 | 31 | // make td_migration_preparation 32 | Command::new("make") 33 | .args(["-C", &lib_path, "td_migration_preparation"]) 34 | .status() 35 | .expect("failed to run make td_migration_preparation for attestation library!"); 36 | 37 | // make td_migration 38 | Command::new("make") 39 | .args(["-C", &lib_path, "td_migration"]) 40 | .status() 41 | .expect("failed to run make td_migration for attestation library!"); 42 | 43 | let search_dir = format!( 44 | "{}/external/dcap_source/QuoteGeneration/quote_wrapper/td_migration/linux", 45 | &lib_path 46 | ); 47 | 48 | println!("cargo:rustc-link-search=native={}", search_dir); 49 | println!("cargo:rustc-link-lib=static=migtd_attest"); 50 | } 51 | -------------------------------------------------------------------------------- /src/attestation/src/attest.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: BSD-2-Clause-Patent 4 | 5 | use crate::{ 6 | binding::get_quote as get_quote_inner, binding::init_heap, binding::verify_quote_integrity, 7 | binding::AttestLibError, root_ca::ROOT_CA, Error, 8 | }; 9 | use alloc::{vec, vec::Vec}; 10 | use core::{alloc::Layout, ffi::c_void}; 11 | use tdx_tdcall::tdreport::*; 12 | 13 | const TD_QUOTE_SIZE: usize = 0x2000; 14 | const TD_REPORT_VERIFY_SIZE: usize = 1024; 15 | const ATTEST_HEAP_SIZE: usize = 0x80000; 16 | const TD_VERIFIED_REPORT_SIZE: usize = 584; 17 | 18 | pub fn attest_init_heap() -> Option { 19 | unsafe { 20 | let heap_base = 21 | alloc::alloc::alloc_zeroed(Layout::from_size_align(ATTEST_HEAP_SIZE, 0x1000).ok()?); 22 | 23 | init_heap(heap_base as *mut c_void, ATTEST_HEAP_SIZE as u32); 24 | } 25 | 26 | Some(ATTEST_HEAP_SIZE) 27 | } 28 | 29 | pub fn get_quote(td_report: &[u8]) -> Result, Error> { 30 | let mut quote = vec![0u8; TD_QUOTE_SIZE]; 31 | let mut quote_size = TD_QUOTE_SIZE as u32; 32 | unsafe { 33 | let result = get_quote_inner( 34 | td_report.as_ptr() as *const c_void, 35 | TD_REPORT_SIZE as u32, 36 | quote.as_mut_ptr() as *mut c_void, 37 | &mut quote_size as *mut u32, 38 | ); 39 | if result != AttestLibError::AttestSuccess { 40 | return Err(Error::GetQuote); 41 | } 42 | } 43 | quote.truncate(quote_size as usize); 44 | Ok(quote) 45 | } 46 | 47 | pub fn verify_quote(quote: &[u8]) -> Result, Error> { 48 | let mut td_report_verify = vec![0u8; TD_REPORT_VERIFY_SIZE]; 49 | let mut report_verify_size = TD_REPORT_VERIFY_SIZE as u32; 50 | 51 | // Safety: 52 | // ROOT_CA must have been set and checked at this moment. 53 | let public_key = ROOT_CA 54 | .get() 55 | .unwrap() 56 | .tbs_certificate 57 | .subject_public_key_info 58 | .subject_public_key 59 | .as_bytes() 60 | .unwrap(); 61 | 62 | unsafe { 63 | let result = verify_quote_integrity( 64 | quote.as_ptr() as *const c_void, 65 | quote.len() as u32, 66 | public_key.as_ptr() as *const c_void, 67 | public_key.len() as u32, 68 | td_report_verify.as_mut_ptr() as *mut c_void, 69 | &mut report_verify_size as *mut u32, 70 | ); 71 | if result != AttestLibError::AttestSuccess { 72 | return Err(Error::VerifyQuote); 73 | } 74 | } 75 | 76 | if report_verify_size as usize != TD_VERIFIED_REPORT_SIZE { 77 | return Err(Error::InvalidOutput); 78 | } 79 | 80 | Ok(wrap_verified_report(td_report_verify)) 81 | } 82 | 83 | // The verified report returned from `verify_quote_integrity` is not in the 84 | // format of the raw TD report. To simplify the use of returned report, wrap 85 | // the result into the raw format. 86 | // { 87 | // // TEE_TCB_INFO 88 | // tee_tcb_svn: [u8; 16], 89 | // mrseam: [u8; 48], 90 | // mrsigner_seam: [u8; 48], 91 | // seam_attributes: [u8; 8], 92 | // // TD_INFO 93 | // td_attributes: [u8; 8], 94 | // xfam: [u8; 8], 95 | // mrtd: [u8; 48], 96 | // mrconfig_id: [u8; 48], 97 | // mrowner: [u8; 48], 98 | // mrownerconfig: [u8; 48], 99 | // rtmr0: [u8; 48], 100 | // rtmr1: [u8; 48], 101 | // rtmr2: [u8; 48], 102 | // rtmr3: [u8; 48], 103 | // // ADDITIONAL_REPORT_DATA 104 | // report_data: [u8; 64], 105 | // } 106 | fn wrap_verified_report(verified_report: Vec) -> Vec { 107 | let mut report = vec![0u8; TD_REPORT_SIZE]; 108 | // REPORT_DATA 109 | report[128..192].copy_from_slice(&verified_report[520..584]); 110 | // TEE_TCB_INFO 111 | report[264..384].copy_from_slice(&verified_report[0..120]); 112 | // TD_INFO 113 | report[512..912].copy_from_slice(&verified_report[120..520]); 114 | 115 | report 116 | } 117 | -------------------------------------------------------------------------------- /src/attestation/src/binding.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: BSD-2-Clause-Patent 4 | 5 | #[allow(unused)] 6 | #[repr(C)] 7 | #[derive(Debug, PartialEq)] 8 | pub(crate) enum AttestLibError { 9 | /// Success 10 | AttestSuccess = 0x0000, 11 | /// Unexpected error 12 | AttestErrorUnexpected = 0x0001, 13 | /// The parameter is incorrect 14 | AttestErrorInvalidParameter = 0x0002, 15 | /// Not enough memory is available to complete this operation 16 | AttestErrorOutOfMemory = 0x0003, 17 | /// vsock related failure 18 | AttestErrorVsockFailure = 0x0004, 19 | /// Failed to get the TD Report 20 | AttestErrorReportFailure = 0x0005, 21 | /// Failed to extend rtmr 22 | AttestErrorExtendFailure = 0x0006, 23 | /// Request feature is not supported 24 | AttestErrorNotSupported = 0x0007, 25 | /// Failed to get the TD Quote 26 | AttestErrorQuoteFailure = 0x0008, 27 | /// The device driver return busy 28 | AttestErrorBusy = 0x0009, 29 | /// Failed to acess tdx attest device 30 | AttestErrorDeviceFailure = 0x000a, 31 | /// Only supported RTMR index is 2 and 3 32 | AttestErrorInvalidRtmrIndex = 0x000b, 33 | } 34 | 35 | extern "C" { 36 | /// Get MigTD's Quote by passing tdx_report. 37 | /// Note: all IN/OUT memory should be managed by Caller 38 | /// 39 | /// @param p_tdx_report [in] pointer to the input buffer for tdx_report. Must not be NULL. 40 | /// @param tdx_report_size [in] length of p_tdx_report(in bytes), should be = TDX_REPORT_SIZE. 41 | /// @param p_quote [in, out] pointer to the quote buffer. Must not be NULL. 42 | /// @param p_quote_size [in, out] This function will place the size of the Quote, in 43 | /// bytes, in the uint32_t pointed to by the 44 | /// p_quote_size parameter. Must not be NULL. 45 | /// @return Status code of the operation, one of: 46 | /// - MIGTD_ATTEST_SUCCESS: Successfully generate the Quote 47 | /// - MIGTD_ATTEST_ERROR_UNEXPECTED: An unexpected internal error occurred. E.g. 48 | /// the parameter is incorrect, failed to get quote from QGS, heap memory allocation error, 49 | /// the input (*p_quote_size) is not enough to place the real Quote, etc. 50 | pub(crate) fn get_quote( 51 | p_tdx_report: *const ::core::ffi::c_void, 52 | tdx_report_size: u32, 53 | p_quote: *mut ::core::ffi::c_void, 54 | p_quote_size: *mut u32, 55 | ) -> AttestLibError; 56 | } 57 | 58 | extern "C" { 59 | /// Verify the integrity of MigTD's Quote and return td report of MigTD 60 | /// Note: all IN/OUT memory should be managed by Caller 61 | /// @param p_quote [in] pointer to the input buffer for td_quote 62 | /// @param quote_size [in] length of p_quote(in bytes), should be the real size of MigTD td quote 63 | /// @param p_quote_collateral [in] quote collateral that get from PCS by get_collateral 64 | /// @param root_pub_key [in] pointer to Intel Root Public Key 65 | /// @param root_pub_key_size [in] length of Intel Root Public Key(in bytes) 66 | /// @param p_tdx_report_verify [in, out] pointer to the output buffer for tdx_report 67 | /// @param p_tdx_report_verify_size [in, out], out_size should be = TDX_REPORT_SIZE 68 | /// 69 | /// @return Status code of the operation, one of: 70 | /// - MIGTD_ATTEST_SUCCESS 71 | /// - MIGTD_ATTEST_ERROR_UNEXPECTED 72 | pub(crate) fn verify_quote_integrity( 73 | p_quote: *const ::core::ffi::c_void, 74 | quote_size: u32, 75 | root_pub_key: *const ::core::ffi::c_void, 76 | root_pub_key_size: u32, 77 | p_tdx_report_verify: *mut ::core::ffi::c_void, 78 | p_tdx_report_verify_size: *mut u32, 79 | ) -> AttestLibError; 80 | } 81 | 82 | extern "C" { 83 | /// Allocate heap space for MigTD Attestation library internal use, 84 | /// Must be called only once by MigTD before other attestation lib APIs 85 | /// 86 | /// @param p_td_heap_base [in] the heap base address allocated by MigTD, the address should be aligned(0x1000). 87 | /// @param td_heap_size [in] the capacity of the heap, should be multiples of 0x1000 (in bytes) 88 | /// 89 | /// @return true: Successfully init heap for internal use. 90 | /// @return false: Failed to init heap for internal use. E.g. the parameter is incorrect, etc. 91 | pub(crate) fn init_heap( 92 | p_td_heap_base: *const ::core::ffi::c_void, 93 | td_heap_size: u32, 94 | ) -> AttestLibError; 95 | } 96 | -------------------------------------------------------------------------------- /src/attestation/src/ghci.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: BSD-2-Clause-Patent 4 | 5 | use core::sync::atomic::{AtomicU8, Ordering}; 6 | use core::{ffi::c_void, ptr::null_mut, slice::from_raw_parts_mut}; 7 | use td_payload::arch::apic::{disable, enable_and_hlt}; 8 | use td_payload::arch::idt::register; 9 | use td_payload::{interrupt_handler_template, mm::shared::SharedMemory}; 10 | use tdx_tdcall::{td_vmcall, tdx, TdVmcallArgs, TdVmcallError}; 11 | 12 | use crate::binding::AttestLibError; 13 | 14 | pub const NOTIFY_VALUE: u8 = 1; 15 | const NOTIFY_VECTOR: u8 = 0x51; 16 | const GET_QUOTE_MAX_SIZE: u64 = 32 * 0x1000; 17 | const TDVMCALL_GETQUOTE: u64 = 0x10002; 18 | 19 | pub static NOTIFIER: AtomicU8 = AtomicU8::new(0); 20 | 21 | #[no_mangle] 22 | pub extern "C" fn migtd_get_quote(tdquote_req_buf: *mut c_void, len: u64) -> i32 { 23 | if tdquote_req_buf == null_mut() || len > GET_QUOTE_MAX_SIZE { 24 | return AttestLibError::AttestErrorInvalidParameter as i32; 25 | } 26 | 27 | let input = unsafe { from_raw_parts_mut(tdquote_req_buf as *mut u8, len as usize) }; 28 | 29 | let mut shared = if let Some(shared) = SharedMemory::new(len as usize / 0x1000) { 30 | shared 31 | } else { 32 | return AttestLibError::AttestErrorOutOfMemory as i32; 33 | }; 34 | shared.as_mut_bytes()[..len as usize].copy_from_slice(input); 35 | 36 | set_vmm_notification(); 37 | 38 | if tdvmcall_get_quote(shared.as_mut_bytes()).is_err() { 39 | return AttestLibError::AttestErrorQuoteFailure as i32; 40 | } 41 | 42 | wait_for_vmm_notification(); 43 | 44 | input.copy_from_slice(&shared.as_bytes()[..len as usize]); 45 | 46 | // Success 47 | 0 48 | } 49 | 50 | // TODO: remove this after next version of `td-shim` is released 51 | fn tdvmcall_get_quote(buffer: &mut [u8]) -> Result<(), TdVmcallError> { 52 | let addr = buffer.as_mut_ptr() as u64 | tdx::td_shared_mask().unwrap(); 53 | 54 | let mut args = TdVmcallArgs { 55 | r11: TDVMCALL_GETQUOTE, 56 | r12: addr, 57 | r13: buffer.len() as u64, 58 | ..Default::default() 59 | }; 60 | 61 | let ret = td_vmcall(&mut args); 62 | 63 | if ret != 0 { 64 | return Err(ret.into()); 65 | } 66 | 67 | Ok(()) 68 | } 69 | 70 | interrupt_handler_template!(vmm_notification, _stack, { 71 | NOTIFIER.store(NOTIFY_VALUE, Ordering::SeqCst); 72 | }); 73 | 74 | pub fn set_vmm_notification() { 75 | // Setup interrupt handler 76 | register(NOTIFY_VECTOR, vmm_notification); 77 | 78 | // Setup event notifier 79 | if tdx_tdcall::tdx::tdvmcall_setup_event_notify(NOTIFY_VECTOR as u64).is_err() { 80 | panic!("Fail to setup VMM event notifier\n"); 81 | } 82 | } 83 | 84 | pub fn wait_for_vmm_notification() { 85 | while NOTIFIER.load(Ordering::SeqCst) == 0 { 86 | // Halt to wait until interrupt comming 87 | enable_and_hlt(); 88 | if NOTIFIER.load(Ordering::SeqCst) == 1 { 89 | break; 90 | } 91 | } 92 | 93 | // Reset the value of NOTIFIER 94 | NOTIFIER.store(0, Ordering::SeqCst); 95 | disable(); 96 | } 97 | -------------------------------------------------------------------------------- /src/attestation/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: BSD-2-Clause-Patent 4 | 5 | #![no_std] 6 | #![feature(naked_functions)] 7 | 8 | extern crate alloc; 9 | 10 | #[cfg(all(feature = "remote-attestation", not(test)))] 11 | mod ghci; 12 | 13 | #[cfg(all(feature = "remote-attestation", not(test)))] 14 | mod binding; 15 | 16 | #[cfg(all(feature = "remote-attestation", not(test)))] 17 | mod attest; 18 | #[cfg(all(feature = "remote-attestation", not(test)))] 19 | pub use attest::*; 20 | 21 | #[cfg(any(not(feature = "remote-attestation"), test))] 22 | mod null; 23 | #[cfg(any(not(feature = "remote-attestation"), test))] 24 | pub use null::*; 25 | 26 | pub mod root_ca; 27 | 28 | #[derive(Debug)] 29 | pub enum Error { 30 | InvalidRootCa, 31 | InitHeap, 32 | GetQuote, 33 | VerifyQuote, 34 | InvalidOutput, 35 | OutOfMemory, 36 | } 37 | -------------------------------------------------------------------------------- /src/attestation/src/null.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: BSD-2-Clause-Patent 4 | 5 | use alloc::vec::Vec; 6 | 7 | use crate::Error; 8 | 9 | pub fn attest_init_heap() {} 10 | 11 | pub fn get_quote(td_report: &[u8]) -> Result, Error> { 12 | Ok(td_report.to_vec()) 13 | } 14 | 15 | pub fn verify_quote(quote: &[u8]) -> Result, Error> { 16 | Ok(quote.to_vec()) 17 | } 18 | -------------------------------------------------------------------------------- /src/attestation/src/root_ca.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: BSD-2-Clause-Patent 4 | 5 | use crypto::x509::Certificate; 6 | use der::Decode; 7 | use spin::Once; 8 | 9 | use crate::Error; 10 | 11 | pub static ROOT_CA: Once = Once::new(); 12 | 13 | pub fn set_ca(cert: &'static [u8]) -> Result<(), Error> { 14 | ROOT_CA 15 | .try_call_once(|| Certificate::from_der(cert)) 16 | .map_err(|_| Error::InvalidRootCa)?; 17 | 18 | let cert = ROOT_CA.get(); 19 | if cert.is_none() { 20 | return Err(Error::InvalidRootCa); 21 | } 22 | 23 | if cert 24 | .unwrap() 25 | .tbs_certificate 26 | .subject_public_key_info 27 | .subject_public_key 28 | .as_bytes() 29 | .is_none() 30 | { 31 | return Err(Error::InvalidRootCa); 32 | } 33 | 34 | Ok(()) 35 | } 36 | -------------------------------------------------------------------------------- /src/crypto/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "crypto" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | bytes = { version="1", default-features=false } 10 | der = {version = "0.7.9", features = ["oid", "alloc", "derive"]} 11 | global = { path = "../global" } 12 | log = "0.4.13" 13 | ring = { version = "0.17.6" } 14 | spdmlib = { path = "../../deps/spdm-rs/spdmlib", default-features = false, features = ["spdm-ring", "mut-auth", "is_sync"]} 15 | tdx-tdcall = { path = "../../deps/td-shim/tdx-tdcall" } 16 | zerocopy = { version = "0.7.31", features = ["derive"] } 17 | -------------------------------------------------------------------------------- /src/crypto/fuzz/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "certchain-fuzz" 3 | version = "0.0.0" 4 | authors = ["Automatically generated"] 5 | publish = false 6 | edition = "2018" 7 | 8 | [package.metadata] 9 | cargo-fuzz = true 10 | 11 | [dependencies] 12 | libfuzzer-sys = {version = "0.4", optional = true } 13 | afl = {version = "*", optional = true } 14 | log = "0.4.13" 15 | arbitrary = "=1.1.3" 16 | der = {version = "0.7.9", features = ["oid", "alloc", "derive"]} 17 | serde = "=1.0.198" 18 | 19 | [dependencies.crypto] 20 | path = ".." 21 | 22 | [patch.crates-io] 23 | ring = { path = "../../../deps/spdm-rs/external/ring" } 24 | webpki = { path = "../../../deps/spdm-rs/external/webpki" } 25 | 26 | # Prevent this from interfering with workspaces 27 | [workspace] 28 | members = ["."] 29 | 30 | [features] 31 | default = ["libfuzzer-sys"] 32 | fuzz = ["afl"] 33 | 34 | [[bin]] 35 | name = "afl_certchain" 36 | path = "fuzz_targets/afl_certchain.rs" 37 | test = false 38 | doc = false 39 | 40 | [[bin]] 41 | name = "certchain" 42 | path = "fuzz_targets/certchain.rs" 43 | test = false 44 | doc = false -------------------------------------------------------------------------------- /src/crypto/fuzz/fuzz_targets/afl_certchain.rs: -------------------------------------------------------------------------------- 1 | use crypto::resolve::{get_cert_from_certchain, parse_extensions}; 2 | use crypto::x509::Certificate; 3 | use der::Decode; 4 | 5 | 6 | fn main() { 7 | #[cfg(feature = "fuzz")] 8 | afl::fuzz!(|data: &[u8]| { 9 | let range = get_cert_from_certchain(data, 0); 10 | if range.is_ok() { 11 | let (start, end) = range.unwrap(); 12 | let cert = Certificate::from_der(&data[start..end]); 13 | if cert.is_ok() { 14 | let cert = cert.unwrap(); 15 | let extensions = cert 16 | .tbs_certificate 17 | .extensions 18 | .as_ref(); 19 | if extensions.is_some() { 20 | let td_report = parse_extensions(&extensions.unwrap()); 21 | } 22 | } 23 | } 24 | }); 25 | } -------------------------------------------------------------------------------- /src/crypto/fuzz/fuzz_targets/certchain.rs: -------------------------------------------------------------------------------- 1 | #![no_main] 2 | use libfuzzer_sys::fuzz_target; 3 | 4 | use crypto::resolve::{get_cert_from_certchain, parse_extensions}; 5 | use crypto::x509::Certificate; 6 | use der::Decode; 7 | 8 | fuzz_target!(|data: &[u8]| { 9 | // fuzzed code goes here 10 | let range = get_cert_from_certchain(data, 0); 11 | if range.is_ok() { 12 | let (start, end) = range.unwrap(); 13 | let cert = Certificate::from_der(&data[start..end]); 14 | if cert.is_ok() { 15 | let cert = cert.unwrap(); 16 | let extensions = cert 17 | .tbs_certificate 18 | .extensions 19 | .as_ref(); 20 | if extensions.is_some() { 21 | let td_report = parse_extensions(&extensions.unwrap()); 22 | } 23 | } 24 | } 25 | }); -------------------------------------------------------------------------------- /src/crypto/fuzz/seeds/certchain/cert_chain: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/intel/vtpm-td/00a2f8619661a4a7ee26efd47fbb4c5efbcab869/src/crypto/fuzz/seeds/certchain/cert_chain -------------------------------------------------------------------------------- /src/crypto/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | #![cfg_attr(not(test), no_std)] 6 | 7 | extern crate alloc; 8 | 9 | pub mod ek_cert; 10 | pub mod resolve; 11 | pub mod td_report; 12 | pub mod x509; 13 | 14 | pub const MUTUAL_ATTESTATION_ERROR: &str = "MutualAttestationError"; 15 | -------------------------------------------------------------------------------- /src/crypto/src/td_report.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | use spdmlib::error::{SpdmResult, SPDM_STATUS_INVALID_CERT}; 6 | use tdx_tdcall::{ 7 | td_call, 8 | tdreport::{TdxReport, TD_REPORT_SIZE}, 9 | TdcallArgs, 10 | }; 11 | 12 | const TDCALL_VERIFYREPORT: u64 = 22; 13 | const TD_REPORT_MAC_SIZE: usize = 0x100; 14 | const TD_REPORT_MAC_BUF_SIZE: usize = 2 * TD_REPORT_MAC_SIZE; 15 | 16 | struct TdxReportMacBuf { 17 | buf: [u8; TD_REPORT_MAC_BUF_SIZE], 18 | start: usize, 19 | offset: usize, 20 | end: usize, 21 | } 22 | 23 | impl TdxReportMacBuf { 24 | fn new() -> Self { 25 | let mut buf = TdxReportMacBuf { 26 | buf: [0u8; TD_REPORT_MAC_BUF_SIZE], 27 | start: 0, 28 | offset: 0, 29 | end: 0, 30 | }; 31 | buf.adjust(); 32 | buf 33 | } 34 | 35 | fn adjust(&mut self) { 36 | self.start = self.buf.as_ptr() as *const u8 as usize; 37 | self.offset = TD_REPORT_MAC_SIZE - (self.start & (TD_REPORT_MAC_SIZE - 1)); 38 | self.end = self.offset + TD_REPORT_MAC_SIZE; 39 | } 40 | 41 | fn report_mac_buf_start(&mut self) -> u64 { 42 | &mut self.buf[self.offset] as *mut u8 as u64 43 | } 44 | 45 | fn report_mac_buf_mut(&mut self) -> &mut [u8] { 46 | &mut self.buf[self.offset..self.end] 47 | } 48 | } 49 | 50 | pub fn verify_td_report(td_report: &[u8]) -> SpdmResult { 51 | if td_report.len() != TD_REPORT_SIZE { 52 | return Err(SPDM_STATUS_INVALID_CERT); 53 | } 54 | 55 | let mut td_report_mac = TdxReportMacBuf::new(); 56 | td_report_mac.adjust(); 57 | 58 | let addr = td_report_mac.report_mac_buf_start(); 59 | td_report_mac 60 | .report_mac_buf_mut() 61 | .copy_from_slice(&td_report[..TD_REPORT_MAC_SIZE]); 62 | 63 | let mut args = TdcallArgs { 64 | rax: TDCALL_VERIFYREPORT, 65 | rcx: addr, 66 | ..Default::default() 67 | }; 68 | 69 | let ret = td_call(&mut args); 70 | if ret != 0 { 71 | log::error!("tdcall_verifyreport failed with {:X?}\n", args.r10); 72 | return Err(SPDM_STATUS_INVALID_CERT); 73 | } 74 | 75 | let mut report = TdxReport::default(); 76 | let mut all_zero = true; 77 | report.as_bytes_mut().copy_from_slice(td_report); 78 | for v in report.td_info.rtmr3.iter() { 79 | if *v != 0u8 { 80 | all_zero = false; 81 | break; 82 | } 83 | } 84 | 85 | if !all_zero { 86 | log::error!("rtmr3 is not all zero! - {:02x?}\n", report.td_info.rtmr3); 87 | return Err(SPDM_STATUS_INVALID_CERT); 88 | } 89 | 90 | Ok(()) 91 | } 92 | -------------------------------------------------------------------------------- /src/eventlog/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "eventlog" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | cc-measurement = { path = "../../deps/td-shim/cc-measurement"} 10 | td-shim = { path = "../../deps/td-shim/td-shim", default-featuers = false } 11 | td-shim-interface = { path = "../../deps/td-shim/td-shim-interface" } 12 | td-payload = { path = "../../deps/td-shim/td-payload", features = ["tdx"] } 13 | zerocopy = { version = "0.7.31", features = ["derive"] } -------------------------------------------------------------------------------- /src/eventlog/src/eventlog.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | use cc_measurement::log::CcEventLogReader; 6 | use cc_measurement::CcEventHeader; 7 | use cc_measurement::TcgPcrEventHeader; 8 | use core::mem::size_of; 9 | use td_payload::acpi::get_acpi_tables; 10 | use td_shim_interface::acpi::Ccel; 11 | use zerocopy::{AsBytes, FromBytes, FromZeroes}; 12 | 13 | pub fn event_log_size(event_log: &[u8]) -> Option { 14 | let reader = CcEventLogReader::new(event_log)?; 15 | 16 | // The first event is TCG_EfiSpecIDEvent with TcgPcrEventHeader 17 | let mut size = size_of::() + reader.pcr_event_header.event_size as usize; 18 | 19 | for (header, _) in reader.cc_events { 20 | size += size_of::() + header.event_size as usize; 21 | } 22 | 23 | Some(size) 24 | } 25 | 26 | fn get_event_log_from_acpi(acpi_table: &[u8]) -> Option<&'static mut [u8]> { 27 | if acpi_table.len() < size_of::() { 28 | return None; 29 | } 30 | 31 | let ccel = Ccel::read_from(&acpi_table[..size_of::()])?; 32 | 33 | let event_log = 34 | unsafe { core::slice::from_raw_parts_mut(ccel.lasa as *mut u8, ccel.laml as usize) }; 35 | 36 | Some(event_log) 37 | } 38 | 39 | pub fn get_event_log() -> &'static mut [u8] { 40 | // Parse out ACPI tables handoff from firmware and find the event log location 41 | let ccel = get_acpi_tables() 42 | .and_then(|tables| tables.iter().find(|&&t| t[..4] == *b"CCEL")) 43 | .expect("Failed to find CCEL"); 44 | get_event_log_from_acpi(ccel).expect("Fail to get event log according CCEL\n") 45 | } 46 | -------------------------------------------------------------------------------- /src/eventlog/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | #![cfg_attr(not(test), no_std)] 6 | #![cfg_attr(test, allow(unused_imports))] 7 | #![feature(alloc_error_handler)] 8 | #![feature(naked_functions)] 9 | #[allow(unused, non_snake_case, non_upper_case_globals, non_camel_case_types)] 10 | pub mod eventlog; 11 | -------------------------------------------------------------------------------- /src/global/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "global" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | spin = "0.9.2" 10 | zeroize = "1.5.7" 11 | 12 | [dependencies.lazy_static] 13 | version = "1.0" 14 | features = ["spin_no_std"] 15 | -------------------------------------------------------------------------------- /src/global/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | #![cfg_attr(not(test), no_std)] 6 | 7 | use zeroize::Zeroize; 8 | 9 | pub mod spdm; 10 | pub mod tpm; 11 | 12 | pub const VTPM_MAX_BUFFER_SIZE: usize = 0x1000; 13 | pub const TPM2_NV_SIZE: usize = 0x4000; 14 | pub const PKCS8_DOCUMENT_MAX_LEN: usize = 185; 15 | pub const VTPM_CA_CERT_MAX_SIZE: usize = 0x2000; 16 | 17 | use lazy_static::lazy_static; 18 | use spin::Mutex; 19 | 20 | use crate::{spdm::GlobalSpdmData, tpm::GlobalTpmData}; 21 | 22 | lazy_static! { 23 | pub static ref GLOBAL_SPDM_DATA: Mutex = Mutex::new(GlobalSpdmData::new()); 24 | } 25 | 26 | lazy_static! { 27 | pub static ref GLOBAL_TPM_DATA: Mutex = Mutex::new(GlobalTpmData::new()); 28 | } 29 | 30 | #[derive(Debug, PartialEq, Eq)] 31 | pub enum VtpmError { 32 | /// Buffer too small 33 | Truncated, 34 | 35 | /// Out of Resource 36 | OutOfResource, 37 | 38 | /// Vmm error 39 | VmmError, 40 | 41 | /// Spdm error 42 | SpdmError, 43 | 44 | /// PipeError 45 | PipeError, 46 | 47 | /// Invalid param 48 | InvalidParameter, 49 | 50 | /// 51 | ExceedMaxConnection, 52 | 53 | /// 54 | ExceedMaxTpmInstanceCount, 55 | 56 | /// 57 | TpmLibError, 58 | 59 | /// 60 | EkProvisionError, 61 | 62 | /// 63 | CaCertError, 64 | 65 | Unknown, 66 | } 67 | pub type VtpmResult = core::result::Result; 68 | 69 | #[derive(Clone, Copy, PartialEq, Debug)] 70 | pub enum TdVtpmOperation { 71 | None = 0, 72 | Communicate = 1, 73 | Create = 2, 74 | Destroy = 3, 75 | Migration = 4, 76 | Invalid = 0xff, 77 | } 78 | 79 | impl TryFrom for TdVtpmOperation { 80 | type Error = VtpmError; 81 | 82 | fn try_from(value: u8) -> Result { 83 | match value { 84 | 0 => Ok(TdVtpmOperation::None), 85 | 1 => Ok(TdVtpmOperation::Communicate), 86 | 2 => Ok(TdVtpmOperation::Create), 87 | 3 => Ok(TdVtpmOperation::Destroy), 88 | 4 => Ok(TdVtpmOperation::Migration), 89 | _ => Err(VtpmError::InvalidParameter), 90 | } 91 | } 92 | } 93 | 94 | pub fn sensitive_data_cleanup(t: &mut T) { 95 | let bytes = unsafe { 96 | core::slice::from_raw_parts_mut(t as *mut T as u64 as *mut u8, core::mem::size_of::()) 97 | }; 98 | bytes.zeroize(); 99 | } 100 | 101 | #[cfg(test)] 102 | mod test { 103 | use super::*; 104 | 105 | const MAX_VTPM_OPERATION_ENUM: u8 = 4; 106 | 107 | #[test] 108 | fn test_try_form() { 109 | let num = [0, 1, 2, 3, 4, 5, 6]; 110 | for i in num { 111 | let res = TdVtpmOperation::try_from(i); 112 | if i > MAX_VTPM_OPERATION_ENUM { 113 | assert_eq!(res.unwrap_err(), VtpmError::InvalidParameter); 114 | } else { 115 | assert!(res.is_ok()) 116 | } 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/protocol/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "protocol" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | byteorder = { version = "1.0", default-features = false } 10 | global = { path = "../global" } 11 | log = "0.4.13" 12 | td-shim-interface = { path = "../../deps/td-shim/td-shim-interface" } 13 | -------------------------------------------------------------------------------- /src/protocol/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | #![cfg_attr(not(test), no_std)] 6 | 7 | pub mod report_status; 8 | /// This file follow *TDX Guest Host Communication Interface(GHCI)* v1.5 9 | 10 | /// TDG.VP.VMCALL Protocol 11 | pub mod service; 12 | pub mod wait_for_request; 13 | 14 | use td_shim_interface::td_uefi_pi::pi::guid::Guid; 15 | 16 | /// Section 5.2: vTPM TD VMCALL 17 | /// {0xc3c87a08, 0x3b4a, 0x41ad, 0xa5, 0x2d, 0x96, 0xf1, 0x3c, 0xf8, 0x9a, 0x66} 18 | #[allow(unused)] 19 | pub static SERVICE_VTPMTD_GUID: Guid = Guid::from_fields( 20 | 0xc3c87a08, 21 | 0x3b4a, 22 | 0x41ad, 23 | [0xa5, 0x2d, 0x96, 0xf1, 0x3c, 0xf8, 0x9a, 0x66], 24 | ); 25 | -------------------------------------------------------------------------------- /src/protocol/src/report_status/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | pub const DEFAULT_VERSION: u8 = 0; 6 | pub const COMMAND_REPORT_STATUS: u8 = 0x2; 7 | 8 | pub mod command; 9 | pub mod response; 10 | 11 | #[derive(Clone, Copy, PartialEq, Debug)] 12 | pub enum TdVtpmReportStatus { 13 | Success = 0, 14 | InvalidParameter = 1, 15 | Unsupported = 2, 16 | OutOfResource = 3, 17 | Reserved = 4, 18 | NetworkError = 5, 19 | SecureSessionError = 6, 20 | MutualAttestationError = 7, 21 | VtpmMigPolicyError = 8, 22 | VtpmInstanceAlreadyStarted = 9, 23 | VtpmInstanceNotStarted = 0xA, 24 | VtpmTdInternalError = 0xff, 25 | } 26 | -------------------------------------------------------------------------------- /src/protocol/src/report_status/response.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | #![allow(unused)] 6 | 7 | use core::convert::TryInto; 8 | 9 | /// This file follow *TDX Guest Host Communication Interface(GHCI)* v1.5 10 | use byteorder::{ByteOrder, LittleEndian}; 11 | use global::{VtpmError, VtpmResult}; 12 | use td_shim_interface::td_uefi_pi::pi::guid::Guid; 13 | 14 | use super::{COMMAND_REPORT_STATUS, DEFAULT_VERSION}; 15 | 16 | /// Table 5-16: vTPM TD SendCommunication Response 17 | pub(crate) mod field { 18 | pub type Field = ::core::ops::Range; 19 | pub type Rest = ::core::ops::RangeFrom; 20 | pub const VERSION: usize = 0; 21 | pub const COMMAND: usize = 1; 22 | pub const RESERVED: Field = 2..4; 23 | } 24 | 25 | // pub const HEADER_LEN: usize = field::TPM_ID.end; 26 | pub const HEADER_LEN: usize = field::RESERVED.end; 27 | 28 | /// Packet manage a buffer for protocol. 29 | pub struct Packet> { 30 | buffer: T, 31 | } 32 | 33 | impl> Packet { 34 | pub fn new_unchecked(buffer: T) -> Packet { 35 | Packet { buffer } 36 | } 37 | pub fn version(&self) -> u8 { 38 | let buf = self.buffer.as_ref(); 39 | buf[field::VERSION] 40 | } 41 | pub fn command(&self) -> u8 { 42 | let buf = self.buffer.as_ref(); 43 | buf[field::COMMAND] 44 | } 45 | } 46 | 47 | impl> AsRef<[u8]> for Packet { 48 | fn as_ref(&self) -> &[u8] { 49 | self.buffer.as_ref() 50 | } 51 | } 52 | 53 | impl + AsMut<[u8]>> AsMut<[u8]> for Packet { 54 | fn as_mut(&mut self) -> &mut [u8] { 55 | self.buffer.as_mut() 56 | } 57 | } 58 | 59 | impl + AsMut<[u8]>> Packet { 60 | pub fn set_version(&mut self, value: u8) { 61 | let buf = self.buffer.as_mut(); 62 | buf[field::VERSION] = value; 63 | } 64 | pub fn set_command(&mut self, value: u8) { 65 | let buf = self.buffer.as_mut(); 66 | buf[field::COMMAND] = value; 67 | } 68 | } 69 | /// Build Respose Header at data_buffer 70 | /// # Arguments 71 | /// 72 | /// * `data_buffer` - data_buffer contains header and data. data_buffer = header + data. 73 | /// 74 | /// # Returns 75 | /// return success and failed. 76 | /// 77 | pub fn build_response_header(data_buffer: &mut [u8]) -> VtpmResult { 78 | let data_buffer_len = data_buffer.len(); 79 | if data_buffer_len < HEADER_LEN { 80 | return Err(VtpmError::InvalidParameter); 81 | } 82 | let mut packet = Packet::new_unchecked(data_buffer); 83 | packet.set_version(DEFAULT_VERSION); 84 | packet.set_command(COMMAND_REPORT_STATUS); 85 | Ok(HEADER_LEN) 86 | } 87 | 88 | #[cfg(test)] 89 | mod test { 90 | use super::*; 91 | 92 | const BUFFER_SIZE: usize = 0x100; 93 | 94 | #[test] 95 | fn test_packet() { 96 | let mut data_buffer = [0u8; BUFFER_SIZE]; 97 | let version = 100 as u8; 98 | let command = 0xff as u8; 99 | let mut packet = Packet::new_unchecked(&mut data_buffer); 100 | packet.set_version(version); 101 | packet.set_command(command); 102 | assert_eq!(packet.version(), version); 103 | assert_eq!(packet.command(), command); 104 | let version1 = 32; 105 | packet.as_mut()[field::VERSION] = version1; 106 | assert_eq!(packet.as_ref()[field::VERSION], version1); 107 | } 108 | 109 | #[test] 110 | fn test_build_response_header() { 111 | let mut buffer = [0u8; BUFFER_SIZE]; 112 | let res = build_response_header(&mut buffer); 113 | assert_eq!(res.unwrap(), HEADER_LEN); 114 | } 115 | 116 | #[test] 117 | fn test_zerodata() { 118 | let res = build_response_header(&mut []); 119 | assert!(res.is_err()); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/protocol/src/service/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | pub mod command; 6 | pub mod response; 7 | -------------------------------------------------------------------------------- /src/protocol/src/wait_for_request/command.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | #![allow(unused)] 6 | 7 | use super::{COMMAND_WAIT_FOR_REQUEST, DEFAULT_VERSION}; 8 | /// This file follow *Trust Domain Extension (TDX) Virtual TPM Design Guide* 9 | /// 5.1.7 vTPM TD WaitForCommunication 10 | /// 11 | use byteorder::{ByteOrder, LittleEndian}; 12 | use global::{VtpmError, VtpmResult}; 13 | use td_shim_interface::td_uefi_pi::pi::guid::Guid; 14 | 15 | /// Table 5-15: vTPM TD WaitForCommunication Command 16 | pub(crate) mod field { 17 | pub type Field = ::core::ops::Range; 18 | pub type Rest = ::core::ops::RangeFrom; 19 | pub const VERSION: usize = 0; 20 | pub const COMMAND: usize = 1; 21 | pub const RESERVED: Field = 2..4; 22 | pub const TPM_ID: Field = 4..20; 23 | } 24 | 25 | pub const HEADER_LEN: usize = field::TPM_ID.end; 26 | /// Packet manage a buffer for protocol. 27 | pub struct Packet> { 28 | buffer: T, 29 | } 30 | 31 | impl> Packet { 32 | pub fn new_unchecked(buffer: T) -> Packet { 33 | Packet { buffer } 34 | } 35 | } 36 | 37 | impl + AsMut<[u8]>> Packet { 38 | pub fn set_version(&mut self, value: u8) { 39 | let buf = self.buffer.as_mut(); 40 | buf[field::VERSION] = value; 41 | } 42 | pub fn set_command(&mut self, value: u8) { 43 | let buf = self.buffer.as_mut(); 44 | buf[field::COMMAND] = value; 45 | } 46 | pub fn set_tpm_id(&mut self, vtpm_id: u128) { 47 | let buf = self.buffer.as_mut(); 48 | LittleEndian::write_u128(&mut buf[field::TPM_ID], vtpm_id); 49 | } 50 | } 51 | 52 | impl> AsRef<[u8]> for Packet { 53 | fn as_ref(&self) -> &[u8] { 54 | self.buffer.as_ref() 55 | } 56 | } 57 | 58 | impl + AsMut<[u8]>> AsMut<[u8]> for Packet { 59 | fn as_mut(&mut self) -> &mut [u8] { 60 | self.buffer.as_mut() 61 | } 62 | } 63 | 64 | /// Build Command Header at data_buffer 65 | /// # Arguments 66 | /// 67 | /// * `data_buffer` - data_buffer contains header and data. data_buffer = header + data. 68 | /// 69 | /// # Returns 70 | /// return success and failed. 71 | /// 72 | pub fn build_command_header(data_buffer: &mut [u8], vtpm_id: u128) -> VtpmResult { 73 | let data_buffer_len = data_buffer.len(); 74 | if data_buffer_len < HEADER_LEN { 75 | return Err(VtpmError::InvalidParameter); 76 | } 77 | let mut packet = Packet::new_unchecked(data_buffer); 78 | packet.set_version(DEFAULT_VERSION); 79 | packet.set_command(COMMAND_WAIT_FOR_REQUEST); 80 | packet.set_tpm_id(vtpm_id); 81 | Ok(HEADER_LEN) 82 | } 83 | 84 | #[cfg(test)] 85 | mod test { 86 | use super::*; 87 | 88 | const BUFFER_SIZE: usize = 0x1000; 89 | const PACKET_BUFFER_SIZE: usize = 0x100; 90 | const INVALID_DATA_BUFFER_SIZE: usize = HEADER_LEN - 1; 91 | 92 | #[test] 93 | fn test_packet() { 94 | let mut data_buffer = [0u8; PACKET_BUFFER_SIZE]; 95 | let version = 100 as u8; 96 | let command = 0xff as u8; 97 | let vtpm_id = 100; 98 | let mut packet = Packet::new_unchecked(&mut data_buffer); 99 | packet.set_version(version); 100 | packet.set_command(command); 101 | packet.set_tpm_id(vtpm_id); 102 | assert_eq!(packet.as_ref()[field::VERSION], version); 103 | let version_2 = 1; 104 | packet.as_mut()[field::VERSION] = version_2; 105 | assert_eq!(version_2, packet.as_ref()[field::VERSION]); 106 | assert_eq!(data_buffer[field::COMMAND], command); 107 | assert_eq!( 108 | LittleEndian::read_u128(&data_buffer[field::TPM_ID]), 109 | vtpm_id 110 | ); 111 | } 112 | 113 | #[test] 114 | fn test_build_cmd_header() { 115 | let mut data_buffer = [0u8; BUFFER_SIZE]; 116 | let vtpmid = 101 as u128; 117 | let res = build_command_header(&mut data_buffer, vtpmid); 118 | assert_eq!(res.unwrap(), HEADER_LEN); 119 | assert_eq!(LittleEndian::read_u128(&data_buffer[field::TPM_ID]), vtpmid); 120 | } 121 | 122 | #[test] 123 | fn test_zerodata() { 124 | let res = build_command_header(&mut [], 0); 125 | assert!(res.is_err()); 126 | } 127 | 128 | #[test] 129 | fn test_invalid_data() { 130 | let mut data_buffer: [u8; INVALID_DATA_BUFFER_SIZE] = [0; INVALID_DATA_BUFFER_SIZE]; 131 | let res = build_command_header(&mut data_buffer, 0); 132 | assert!(res.is_err()); 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /src/protocol/src/wait_for_request/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | pub const DEFAULT_VERSION: u8 = 1; 6 | pub const COMMAND_WAIT_FOR_REQUEST: u8 = 0x1; 7 | 8 | pub mod command; 9 | pub mod response; 10 | -------------------------------------------------------------------------------- /src/spdm/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "spdm" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | global = { path = "../global" } 10 | log = "0.4.13" 11 | 12 | ring = { version = "0.17.6" } 13 | spin = "0.9.2" 14 | x86 = "0.47.0" 15 | x86_64 = "0.14.9" 16 | 17 | codec = { path = "../../deps/spdm-rs/codec" } 18 | protocol = { path = "../protocol" } 19 | tdtunnel = { path = "../tdtunnel" } 20 | spdmlib = { path = "../../deps/spdm-rs/spdmlib", default-features = false, features = ["spdm-ring", "mut-auth", "is_sync"]} 21 | td-exception = { path = "../../deps/td-shim/td-exception", features = ["tdx"]} 22 | tdx-tdcall = { path = "../../deps/td-shim/tdx-tdcall" } 23 | td-payload = { path = "../../deps/td-shim/td-payload", features = ["tdx"] } 24 | maybe-async = {version = "0.2.7", features = ["is_sync"] } -------------------------------------------------------------------------------- /src/spdm/src/crypto_callback.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | use core::panic; 6 | use global::{sensitive_data_cleanup, GLOBAL_SPDM_DATA}; 7 | use spdmlib::protocol::{ 8 | SpdmBaseAsymAlgo, SpdmBaseHashAlgo, SpdmSignatureStruct, SPDM_MAX_ASYM_KEY_SIZE, 9 | }; 10 | use spdmlib::secret::SpdmSecretAsymSign; 11 | 12 | pub static ASYM_SIGN_IMPL: SpdmSecretAsymSign = SpdmSecretAsymSign { sign_cb: asym_sign }; 13 | 14 | fn asym_sign( 15 | base_hash_algo: SpdmBaseHashAlgo, 16 | base_asym_algo: SpdmBaseAsymAlgo, 17 | data: &[u8], 18 | ) -> Option { 19 | match (base_hash_algo, base_asym_algo) { 20 | (SpdmBaseHashAlgo::TPM_ALG_SHA_384, SpdmBaseAsymAlgo::TPM_ALG_ECDSA_ECC_NIST_P384) => { 21 | sign_ecdsa_asym_algo(&ring::signature::ECDSA_P384_SHA384_FIXED_SIGNING, data) 22 | } 23 | _ => { 24 | panic!( 25 | "Not supported asym_algo! - {0:?}:{1:?}\n", 26 | base_hash_algo, base_asym_algo 27 | ); 28 | } 29 | } 30 | } 31 | 32 | fn sign_ecdsa_asym_algo( 33 | algorithm: &'static ring::signature::EcdsaSigningAlgorithm, 34 | data: &[u8], 35 | ) -> Option { 36 | assert!(algorithm == &ring::signature::ECDSA_P384_SHA384_FIXED_SIGNING); 37 | 38 | let binding = GLOBAL_SPDM_DATA.lock(); 39 | let mut pkcs8 = binding.pkcs8()?; 40 | 41 | let rng = ring::rand::SystemRandom::new(); 42 | let key_pair = ring::signature::EcdsaKeyPair::from_pkcs8(algorithm, pkcs8, &rng); 43 | if key_pair.is_err() { 44 | return None; 45 | } 46 | let mut key_pair = key_pair.unwrap(); 47 | 48 | let rng = ring::rand::SystemRandom::new(); 49 | 50 | let signature = key_pair.sign(&rng, data); 51 | if signature.is_err() { 52 | return None; 53 | } 54 | 55 | let binding = signature.unwrap(); 56 | let signature = binding.as_ref(); 57 | 58 | let mut full_signature: [u8; SPDM_MAX_ASYM_KEY_SIZE] = [0u8; SPDM_MAX_ASYM_KEY_SIZE]; 59 | full_signature[..signature.len()].copy_from_slice(signature); 60 | 61 | sensitive_data_cleanup(&mut key_pair); 62 | sensitive_data_cleanup(&mut pkcs8); 63 | 64 | Some(SpdmSignatureStruct { 65 | data_size: signature.len() as u16, 66 | data: full_signature, 67 | }) 68 | } 69 | 70 | #[cfg(test)] 71 | mod test { 72 | 73 | use super::*; 74 | use ring::rand::SystemRandom; 75 | use ring::signature::{self, EcdsaKeyPair}; 76 | #[test] 77 | fn test_asym_sign() { 78 | let mut data = [2u8; 0x100]; 79 | let base_hash_algo = SpdmBaseHashAlgo::TPM_ALG_SHA_384; 80 | let base_asym_algo = SpdmBaseAsymAlgo::TPM_ALG_ECDSA_ECC_NIST_P384; 81 | GLOBAL_SPDM_DATA.lock().valid = true; 82 | let rand = SystemRandom::new(); 83 | let pkcs8_bytes = 84 | EcdsaKeyPair::generate_pkcs8(&signature::ECDSA_P384_SHA384_ASN1_SIGNING, &rand) 85 | .map_err(|_| 0); 86 | 87 | assert_eq!(pkcs8_bytes.is_err(), false); 88 | let pkcs8 = pkcs8_bytes.unwrap(); 89 | let res = GLOBAL_SPDM_DATA.lock().set_pkcs8(pkcs8.as_ref()); 90 | assert_eq!(res.is_err(), false); 91 | 92 | let res = asym_sign(base_hash_algo, base_asym_algo, &mut data); 93 | assert_eq!(res.is_none(), false); 94 | } 95 | 96 | #[test] 97 | #[should_panic] 98 | fn test_sign_ecdsa_asym_algo_other_algo() { 99 | let mut data = [2u8; 96]; 100 | sign_ecdsa_asym_algo(&ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING, &mut data); 101 | } 102 | 103 | #[test] 104 | #[should_panic] 105 | fn test_asym_sign_other_algo() { 106 | let mut data = [2u8; 0x100]; 107 | let base_hash_algo = SpdmBaseHashAlgo::TPM_ALG_SHA_256; 108 | let base_asym_algo = SpdmBaseAsymAlgo::TPM_ALG_ECDSA_ECC_NIST_P256; 109 | asym_sign(base_hash_algo, base_asym_algo, &mut data); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/spdm/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | #![cfg_attr(not(test), no_std)] 6 | 7 | pub mod crypto_callback; 8 | pub mod vtpm_io_transport; 9 | pub mod vtpm_transport_encap; 10 | -------------------------------------------------------------------------------- /src/tdtunnel/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tdtunnel" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | global = { path = "../global" } 10 | log = "0.4.13" 11 | x86 = "0.47.0" 12 | x86_64 = "0.14.9" 13 | 14 | protocol = { path = "../protocol" } 15 | tdx-tdcall = { path = "../../deps/td-shim/tdx-tdcall" } 16 | td-exception = { path = "../../deps/td-shim/td-exception", features = ["tdx"]} 17 | td-payload = { path = "../../deps/td-shim/td-payload", features = ["tdx"] } -------------------------------------------------------------------------------- /src/tdtunnel/src/interrupt.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | use core::sync::atomic::{AtomicU8, Ordering}; 6 | pub use td_exception::*; 7 | use td_payload::arch::apic::{disable, enable_and_hlt}; 8 | use td_payload::interrupt_handler_template; 9 | 10 | pub const NOTIFY_VALUE_CLEAR: u8 = 0; 11 | pub const NOTIFY_VALUE_SET: u8 = 1; 12 | 13 | // 32~255 are available 14 | pub const INTERRUPT_VECTOR_WAIT_FOR_REQUEST: u8 = 32; 15 | 16 | // Define a static atomic variable to store the notification state. 17 | static NOTIFY_WAIT_FOR_REQUEST: AtomicU8 = AtomicU8::new(NOTIFY_VALUE_CLEAR); 18 | const NOTIFY_VECTOR_WAIT_FOR_REQUEST: u8 = INTERRUPT_VECTOR_WAIT_FOR_REQUEST; 19 | 20 | // Define the interrupt handler via the provided interrupt_handler_template macro. 21 | interrupt_handler_template!(vmm_notification_wait_for_request, _stack, { 22 | NOTIFY_WAIT_FOR_REQUEST.store(NOTIFY_VALUE_SET, Ordering::SeqCst); 23 | }); 24 | 25 | // Function to register the VMM notification interrupt. 26 | pub fn register_vmm_notification_wait_for_request() { 27 | // Setup interrupt handler. 28 | unsafe { 29 | idt::register_handler( 30 | NOTIFY_VECTOR_WAIT_FOR_REQUEST, 31 | vmm_notification_wait_for_request, 32 | ); 33 | } 34 | } 35 | 36 | // Function to wait for the VMM notification interrupt. 37 | pub fn wait_for_vmm_notification_wait_for_request() { 38 | while NOTIFY_WAIT_FOR_REQUEST.load(Ordering::SeqCst) != NOTIFY_VALUE_SET { 39 | enable_and_hlt(); 40 | if NOTIFY_WAIT_FOR_REQUEST.load(Ordering::SeqCst) == NOTIFY_VALUE_SET { 41 | break; 42 | } 43 | } 44 | disable(); 45 | // Reset notification state. 46 | NOTIFY_WAIT_FOR_REQUEST.store(NOTIFY_VALUE_CLEAR, Ordering::SeqCst); 47 | } 48 | -------------------------------------------------------------------------------- /src/tdtunnel/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | #![cfg_attr(not(test), no_std)] 6 | #![feature(naked_functions)] 7 | 8 | pub mod interrupt; 9 | pub mod td_tunnel; 10 | -------------------------------------------------------------------------------- /src/tpm/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tpm" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | attestation = { path = "../attestation", default-features = false } 10 | eventlog = { path = "../eventlog" } 11 | global = { path = "../global" } 12 | crypto = { path = "../crypto" } 13 | log = "0.4.13" 14 | ring = { version = "0.17.6" } 15 | rust-tpm-20-ref = { path = "../../deps/rust-tpm-20-ref" } 16 | spin = "0.9.2" 17 | tdx-tdcall = { path = "../../deps/td-shim/tdx-tdcall" } 18 | x86_64 = "0.14" 19 | time = { version = "0.3", default-features = false } 20 | 21 | [dependencies.lazy_static] 22 | version = "1.0" 23 | features = ["spin_no_std"] 24 | -------------------------------------------------------------------------------- /src/tpm/build.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | use std::path::PathBuf; 6 | 7 | fn main() { 8 | println!("cargo:rerun-if-changed=build.rs"); 9 | 10 | let rust_tpm_20_ref_path = get_manifest_dir().join("../../deps/rust-tpm-20-ref"); 11 | 12 | println!( 13 | "cargo:rustc-link-search=native={}", 14 | rust_tpm_20_ref_path 15 | .join("smallc/lib") 16 | .as_os_str() 17 | .to_str() 18 | .unwrap() 19 | ); 20 | println!("cargo:rustc-link-lib=static=smallc"); 21 | 22 | println!( 23 | "cargo:rustc-link-search=native={}", 24 | rust_tpm_20_ref_path 25 | .join("openssl-stubs") 26 | .as_os_str() 27 | .to_str() 28 | .unwrap() 29 | ); 30 | println!("cargo:rustc-link-lib=static=crypto"); 31 | 32 | println!( 33 | "cargo:rustc-link-search=native={}", 34 | rust_tpm_20_ref_path 35 | .join("tpm") 36 | .as_os_str() 37 | .to_str() 38 | .unwrap() 39 | ); 40 | println!("cargo:rustc-link-lib=static=platform"); 41 | println!("cargo:rustc-link-lib=static=tpm"); 42 | } 43 | 44 | /// Get manifest directory. 45 | fn get_manifest_dir() -> PathBuf { 46 | let dir = std::env::var("CARGO_MANIFEST_DIR").unwrap(); 47 | PathBuf::from(dir) 48 | } 49 | -------------------------------------------------------------------------------- /src/tpm/src/cty.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | #![allow(non_camel_case_types)] 6 | 7 | pub use arch::*; 8 | pub use os::*; 9 | 10 | #[cfg(any(target_arch = "x86", target_arch = "x86_64",))] 11 | mod arch { 12 | pub type c_char = super::c_schar; 13 | pub type c_int = i32; 14 | pub type c_uint = u32; 15 | } 16 | 17 | #[cfg(any(windows,))] 18 | mod os { 19 | pub type c_long = i32; 20 | pub type c_ulong = u32; 21 | } 22 | #[cfg(not(any(windows,)))] 23 | mod os { 24 | #[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))] 25 | pub type c_long = i32; 26 | #[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))] 27 | pub type c_ulong = u32; 28 | #[cfg(all(target_pointer_width = "64"))] 29 | pub type c_long = i64; 30 | #[cfg(all(target_pointer_width = "64"))] 31 | pub type c_ulong = u64; 32 | } 33 | 34 | pub type int8_t = i8; 35 | pub type int16_t = i16; 36 | pub type int32_t = i32; 37 | pub type int64_t = i64; 38 | 39 | pub type uint8_t = u8; 40 | pub type uint16_t = u16; 41 | pub type uint32_t = u32; 42 | pub type uint64_t = u64; 43 | 44 | pub type c_schar = i8; 45 | pub type c_short = i16; 46 | pub type c_longlong = i64; 47 | 48 | pub type c_uchar = u8; 49 | pub type c_ushort = u16; 50 | pub type c_ulonglong = u64; 51 | 52 | pub type c_float = f32; 53 | pub type c_double = f64; 54 | 55 | pub type intmax_t = i64; 56 | pub type uintmax_t = u64; 57 | 58 | pub type size_t = usize; 59 | pub type ptrdiff_t = isize; 60 | pub type intptr_t = isize; 61 | pub type uintptr_t = usize; 62 | pub type ssize_t = isize; 63 | 64 | pub type c_void = core::ffi::c_void; 65 | -------------------------------------------------------------------------------- /src/tpm/src/std_lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | #![cfg_attr(test, allow(unused_imports))] 6 | use alloc::collections::BTreeMap; 7 | use core::alloc::Layout; 8 | #[allow(unused, non_snake_case, non_upper_case_globals, non_camel_case_types)] 9 | use core::{ffi::c_void, ptr::null_mut}; 10 | use lazy_static::lazy_static; 11 | use spin::Mutex; 12 | 13 | extern crate alloc; 14 | 15 | #[no_mangle] 16 | /// # Safety 17 | /// 18 | /// This function is unsafe because of the parameter of msg 19 | pub unsafe extern "C" fn __fw_debug_msg(msg: *const u8, len: usize) { 20 | let msg = unsafe { 21 | let r = core::slice::from_raw_parts(msg, len); 22 | core::str::from_utf8_unchecked(r) 23 | }; 24 | log::info!("{}", msg); 25 | } 26 | 27 | #[no_mangle] 28 | /// # Safety 29 | /// 30 | /// This function is unsafe because of the parameter of buffer 31 | pub unsafe extern "C" fn __fw_debug_buffer(buffer: *const u8, len: usize) { 32 | let buf = unsafe { core::slice::from_raw_parts(buffer, len) }; 33 | log::info!("buffer {:x?}\n", buf); 34 | } 35 | 36 | #[no_mangle] 37 | pub extern "C" fn __fw_abort() { 38 | panic!("abort called"); 39 | } 40 | 41 | #[no_mangle] 42 | pub extern "C" fn __fw_rdrand32() -> u32 { 43 | unsafe { 44 | let mut ret: u32 = 0; 45 | for _ in 0..10 { 46 | if core::arch::x86_64::_rdrand32_step(&mut ret) == 1 { 47 | return ret; 48 | } 49 | } 50 | panic!("Failed to obtain random data"); 51 | } 52 | } 53 | 54 | lazy_static! { 55 | static ref MALLOC_TABLE: Mutex> = Mutex::new(BTreeMap::new()); 56 | } 57 | 58 | #[no_mangle] 59 | /// # Safety 60 | /// 61 | /// This function is unsafe 62 | pub unsafe extern "C" fn __fw_malloc(size: usize) -> *mut c_void { 63 | let addr = alloc::alloc::alloc(Layout::from_size_align_unchecked(size, 1)) as *mut c_void; 64 | if !addr.is_null() { 65 | MALLOC_TABLE.lock().insert(addr as usize, size); 66 | } 67 | addr 68 | } 69 | 70 | #[no_mangle] 71 | /// # Safety 72 | /// 73 | /// This function is unsafe because of the parameter of ptr 74 | pub unsafe extern "C" fn __fw_free(ptr: *mut c_void) { 75 | if MALLOC_TABLE.lock().contains_key(&(ptr as usize)) { 76 | let size = *MALLOC_TABLE.lock().get(&(ptr as usize)).unwrap(); 77 | alloc::alloc::dealloc(ptr as *mut u8, Layout::from_size_align_unchecked(size, 1)); 78 | MALLOC_TABLE.lock().remove_entry(&(ptr as usize)); 79 | } 80 | } 81 | 82 | #[no_mangle] 83 | /// # Safety 84 | pub unsafe extern "C" fn __fw_realloc(ptr: *mut c_void, new_size: usize) -> *mut c_void { 85 | if MALLOC_TABLE.lock().contains_key(&(ptr as usize)) { 86 | let old_size = *MALLOC_TABLE.lock().get(&(ptr as usize)).unwrap(); 87 | let ptr_new = alloc::alloc::realloc( 88 | ptr as *mut u8, 89 | Layout::from_size_align_unchecked(old_size, 1), 90 | new_size, 91 | ) as *mut c_void; 92 | 93 | if !ptr_new.is_null() { 94 | MALLOC_TABLE.lock().remove_entry(&(ptr as usize)); 95 | MALLOC_TABLE.lock().insert(ptr_new as usize, new_size); 96 | } 97 | 98 | ptr_new 99 | } else { 100 | null_mut() 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/tpm/src/tpm2_ca_cert.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | use alloc::vec::Vec; 6 | use attestation::get_quote; 7 | use crypto::{ 8 | ek_cert::generate_ca_cert, 9 | resolve::{generate_ecdsa_keypairs, ResolveError}, 10 | }; 11 | use eventlog::eventlog::{event_log_size, get_event_log}; 12 | use global::{sensitive_data_cleanup, VtpmError, VtpmResult, GLOBAL_TPM_DATA}; 13 | use ring::{ 14 | digest, 15 | signature::{EcdsaKeyPair, KeyPair}, 16 | }; 17 | 18 | fn get_td_quote(data: &[u8]) -> Result, VtpmError> { 19 | // first calc the hash of ek_pub 20 | let data_hash = digest::digest(&digest::SHA384, data); 21 | 22 | // Generate the TD Report that contains the ek_pub hash as nonce 23 | let mut td_report_data = [0u8; 64]; 24 | td_report_data[..data_hash.as_ref().len()].copy_from_slice(data_hash.as_ref()); 25 | let td_report = 26 | tdx_tdcall::tdreport::tdcall_report(&td_report_data).map_err(|_| ResolveError::GetTdReport); 27 | if td_report.is_err() { 28 | log::error!("Failed to get td_report.\n"); 29 | return Err(VtpmError::CaCertError); 30 | } 31 | let td_report = td_report.unwrap(); 32 | 33 | // at last call get_quote 34 | let td_quote = get_quote(td_report.as_bytes()).map_err(|_| VtpmError::CaCertError); 35 | 36 | if td_quote.is_err() { 37 | log::error!("Failed to get td_quote.\n"); 38 | return Err(VtpmError::CaCertError); 39 | } 40 | 41 | td_quote 42 | } 43 | 44 | pub fn gen_tpm2_ca_cert() -> VtpmResult { 45 | // create ecdsa_keypair for ca-cert 46 | let pkcs8 = generate_ecdsa_keypairs(); 47 | if pkcs8.is_none() { 48 | log::error!("Failed to generate pkcs8.\n"); 49 | return Err(VtpmError::CaCertError); 50 | } 51 | let mut pkcs8 = pkcs8.unwrap(); 52 | 53 | let rng = ring::rand::SystemRandom::new(); 54 | let key_pair = EcdsaKeyPair::from_pkcs8( 55 | &ring::signature::ECDSA_P384_SHA384_ASN1_SIGNING, 56 | pkcs8.as_ref(), 57 | &rng, 58 | ); 59 | 60 | if key_pair.is_err() { 61 | log::error!("Failed to generate ecdsa keypair from pkcs8.\n"); 62 | return Err(VtpmError::CaCertError); 63 | } 64 | let mut key_pair = key_pair.unwrap(); 65 | 66 | // get td_quote 67 | let td_quote = get_td_quote(key_pair.public_key().as_ref()); 68 | if td_quote.is_err() { 69 | return Err(VtpmError::CaCertError); 70 | } 71 | let td_quote = td_quote.unwrap(); 72 | 73 | // get the event_log 74 | let event_log = get_event_log(); 75 | let size = event_log_size(event_log); 76 | if size.is_none() { 77 | return Err(VtpmError::CaCertError); 78 | } 79 | let size = size.unwrap(); 80 | let event_log = &event_log[..size + 1]; 81 | 82 | // generate ca-cert 83 | let ca_cert = generate_ca_cert(td_quote.as_slice(), event_log, &key_pair); 84 | if ca_cert.is_err() { 85 | return Err(VtpmError::CaCertError); 86 | } 87 | let ca_cert = ca_cert.unwrap(); 88 | 89 | GLOBAL_TPM_DATA 90 | .lock() 91 | .set_ca_cert(ca_cert) 92 | .map_err(|_| VtpmError::CaCertError)?; 93 | GLOBAL_TPM_DATA.lock().set_ca_cert_pkcs8(pkcs8.as_ref())?; 94 | 95 | sensitive_data_cleanup(&mut key_pair); 96 | sensitive_data_cleanup(&mut pkcs8); 97 | Ok(()) 98 | } 99 | -------------------------------------------------------------------------------- /src/tpm/src/tpm2_cmd_rsp/command.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | // pub const TPM_CMD_STARTUP: [u8; _] = [0x80, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x44, 0x00, 0x00]; 6 | 7 | use alloc::slice; 8 | 9 | use super::TPM2_COMMAND_HEADER_SIZE; 10 | 11 | #[repr(C, packed)] 12 | #[derive(Debug, PartialEq, Copy, Clone)] 13 | pub struct Tpm2CommandHeader { 14 | tag: u16, 15 | param_size: u32, 16 | command_code: u32, 17 | } 18 | 19 | impl Tpm2CommandHeader { 20 | pub fn new(tag: u16, param_size: u32, command_code: u32) -> Tpm2CommandHeader { 21 | Self { 22 | tag: tag.to_be(), 23 | param_size: param_size.to_be(), 24 | command_code: command_code.to_be(), 25 | } 26 | } 27 | 28 | pub fn from_bytes(bytes: &[u8]) -> Option { 29 | if bytes.len() < TPM2_COMMAND_HEADER_SIZE { 30 | log::error!( 31 | "Invalid length ({:?}) of tpm2 command header.\n", 32 | bytes.len() 33 | ); 34 | return None; 35 | } 36 | 37 | let tag = u16::from_le_bytes([bytes[0], bytes[1]]); 38 | let param_size = u32::from_le_bytes([bytes[2], bytes[3], bytes[4], bytes[5]]); 39 | let command_code = u32::from_le_bytes([bytes[6], bytes[7], bytes[8], bytes[9]]); 40 | 41 | Some(Tpm2CommandHeader { 42 | tag, 43 | param_size, 44 | command_code, 45 | }) 46 | } 47 | 48 | pub fn as_slice(&self) -> &[u8] { 49 | unsafe { 50 | slice::from_raw_parts( 51 | self as *const Tpm2CommandHeader as *const u8, 52 | core::mem::size_of::(), 53 | ) 54 | } 55 | } 56 | 57 | pub fn set_size(&mut self, size: u32) { 58 | self.param_size = size.to_be(); 59 | } 60 | 61 | pub fn get_command_code(&self) -> u32 { 62 | self.command_code.to_be() 63 | } 64 | 65 | pub fn header_size() -> u32 { 66 | core::mem::size_of::() as u32 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/tpm/src/tpm2_cmd_rsp/getcaps.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | use alloc::collections::BTreeMap; 6 | use global::VTPM_MAX_BUFFER_SIZE; 7 | 8 | use crate::execute_command; 9 | 10 | use super::TPM_RC_SUCCESS; 11 | 12 | const TPM_CAP_TPM_PROPERTIES: u32 = 6; 13 | 14 | fn read_u32_from_bytes(bytes: &[u8], be: bool) -> u32 { 15 | let mut buf: [u8; 4] = [0; 4]; 16 | buf.copy_from_slice(bytes); 17 | let val: u32; 18 | if be { 19 | val = u32::from_be_bytes(buf); 20 | } else { 21 | val = u32::from_le_bytes(buf); 22 | } 23 | 24 | val 25 | } 26 | 27 | pub fn tpm2_get_caps() -> Option> { 28 | let req: &mut [u8] = &mut [ 29 | 0x80, 0x01, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x01, 0x7a, 0x00, 0x00, 0x00, 0x06, 0x00, 30 | 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x7f, 31 | ]; 32 | let mut rsp: [u8; VTPM_MAX_BUFFER_SIZE] = [0; VTPM_MAX_BUFFER_SIZE]; 33 | let (rsp_size, rsp_code) = execute_command(req, &mut rsp, 0); 34 | 35 | if rsp_size == 0 || rsp_code != TPM_RC_SUCCESS { 36 | log::error!("Failed to tpm2_get_caps\n"); 37 | return None; 38 | } 39 | 40 | let mut properties: BTreeMap = BTreeMap::new(); 41 | 42 | // skip the rsp header 43 | let mut offset: usize = 10; 44 | // skip the more_data 45 | offset += 1; 46 | // check capability. It should be TPM_CAP_TPM_PROPERTIES(0x6) 47 | let capability: u32 = read_u32_from_bytes(&rsp[offset..offset + 4], true); 48 | if capability != TPM_CAP_TPM_PROPERTIES { 49 | return None; 50 | } 51 | 52 | //properties count 53 | offset += 4; 54 | let prop_count: u32 = read_u32_from_bytes(&rsp[offset..offset + 4], true); 55 | if prop_count == 0 { 56 | return None; 57 | } 58 | 59 | // walk thru the properties 60 | offset += 4; 61 | if rsp_size as usize - offset != (prop_count * 8) as usize { 62 | return None; 63 | } 64 | 65 | for _i in 0..prop_count { 66 | let prop: u32 = read_u32_from_bytes(&rsp[offset..offset + 4], true); 67 | offset += 4; 68 | let val: u32 = read_u32_from_bytes(&rsp[offset..offset + 4], true); 69 | properties.insert(prop, val); 70 | offset += 4; 71 | } 72 | 73 | Some(properties) 74 | } 75 | -------------------------------------------------------------------------------- /src/tpm/src/tpm2_cmd_rsp/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | pub mod command; 6 | pub mod getcaps; 7 | pub mod response; 8 | pub mod shutdown; 9 | pub mod startup; 10 | 11 | pub const TPM2_COMMAND_HEADER_SIZE: usize = 10; 12 | pub const TPM2_RESPONSE_HEADER_SIZE: usize = 10; 13 | pub const TPM_ST_NO_SESSIONS: u16 = 0x8001; 14 | pub const TPM_ST_SESSIONS: u16 = 0x8002; 15 | 16 | pub const TPM_CC_STARTUP: u32 = 0x144; 17 | pub const TPM_SU_CLEAR: u16 = 0u16; 18 | pub const TPM_SU_STATE: u16 = 1u16; 19 | pub const TPM_RC_SUCCESS: u32 = 0; 20 | pub const TPM2_CC_CREATEPRIMARY: u32 = 0x00000131; 21 | pub const TPM2_CC_NV_DEFINESPACE: u32 = 0x0000012a; 22 | pub const TPM2_CC_NV_WRITE: u32 = 0x00000137; 23 | pub const TPM2_CC_EVICTCONTROL: u32 = 0x00000120; 24 | 25 | /// TPM Shutdown 26 | pub const TPM_CC_SHUTDOWN: u32 = 0x145; 27 | pub const TPM_STARTUP_CMD: [u8; 12] = [ 28 | 0x80, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x44, 0x00, 0x00, 29 | ]; 30 | pub const TPM_SHUTDOWN_CMD: [u8; 12] = [ 31 | 0x80, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x45, 0x00, 0x00, 32 | ]; 33 | -------------------------------------------------------------------------------- /src/tpm/src/tpm2_cmd_rsp/response.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | // pub const TPM_CMD_STARTUP: [u8; _] = [0x80, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x44, 0x00, 0x00]; 6 | 7 | use alloc::slice; 8 | 9 | use super::TPM2_RESPONSE_HEADER_SIZE; 10 | 11 | #[repr(C, packed)] 12 | #[derive(Debug, PartialEq, Copy, Clone)] 13 | pub struct Tpm2ResponseHeader { 14 | tag: u16, 15 | param_size: u32, 16 | response_code: u32, 17 | } 18 | 19 | impl Tpm2ResponseHeader { 20 | pub fn new(tag: u16, param_size: u32, response_code: u32) -> Tpm2ResponseHeader { 21 | Self { 22 | tag: tag.to_be(), 23 | param_size: param_size.to_be(), 24 | response_code: response_code.to_be(), 25 | } 26 | } 27 | 28 | pub fn from_bytes(bytes: &[u8]) -> Option { 29 | if bytes.len() < TPM2_RESPONSE_HEADER_SIZE { 30 | log::error!( 31 | "Invalid length ({:?}) of tpm2 response header.\n", 32 | bytes.len() 33 | ); 34 | return None; 35 | } 36 | 37 | let tag = u16::from_le_bytes([bytes[0], bytes[1]]); 38 | let param_size = u32::from_le_bytes([bytes[2], bytes[3], bytes[4], bytes[5]]); 39 | let response_code = u32::from_le_bytes([bytes[6], bytes[7], bytes[8], bytes[9]]); 40 | 41 | Some(Tpm2ResponseHeader { 42 | tag, 43 | param_size, 44 | response_code, 45 | }) 46 | } 47 | 48 | pub fn get_response_code(&self) -> u32 { 49 | self.response_code.to_be() 50 | } 51 | 52 | pub fn as_slice(&self) -> &[u8] { 53 | unsafe { 54 | slice::from_raw_parts( 55 | self as *const Tpm2ResponseHeader as *const u8, 56 | core::mem::size_of::(), 57 | ) 58 | } 59 | } 60 | 61 | pub fn size() -> u32 { 62 | core::mem::size_of::() as u32 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/tpm/src/tpm2_cmd_rsp/shutdown.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | use super::{TPM_RC_SUCCESS, TPM_SHUTDOWN_CMD}; 6 | use crate::execute_command; 7 | use global::{VtpmError, VtpmResult, VTPM_MAX_BUFFER_SIZE}; 8 | 9 | pub fn tpm2_shutdown() -> VtpmResult { 10 | let mut tpm_rsp: [u8; VTPM_MAX_BUFFER_SIZE] = [0; VTPM_MAX_BUFFER_SIZE]; 11 | 12 | let (rsp_size, rsp_code) = execute_command(&TPM_SHUTDOWN_CMD, &mut tpm_rsp, 0); 13 | 14 | if rsp_size == 0 || rsp_code != TPM_RC_SUCCESS { 15 | log::error!("Tpm2Shutdown failed.\n"); 16 | return Err(VtpmError::TpmLibError); 17 | } 18 | 19 | Ok(()) 20 | } 21 | -------------------------------------------------------------------------------- /src/tpm/src/tpm2_cmd_rsp/startup.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | use super::{TPM_RC_SUCCESS, TPM_STARTUP_CMD}; 6 | use crate::execute_command; 7 | use global::{VtpmError, VtpmResult, VTPM_MAX_BUFFER_SIZE}; 8 | 9 | pub fn tpm2_startup() -> VtpmResult { 10 | let mut tpm_rsp: [u8; VTPM_MAX_BUFFER_SIZE] = [0; VTPM_MAX_BUFFER_SIZE]; 11 | 12 | let (rsp_size, rsp_code) = execute_command(&TPM_STARTUP_CMD, &mut tpm_rsp, 0); 13 | 14 | if rsp_size == 0 || rsp_code != TPM_RC_SUCCESS { 15 | log::error!("tpm2_startup failed with rsp_code 0x{:x?}\n", rsp_code); 16 | return Err(VtpmError::TpmLibError); 17 | } 18 | 19 | Ok(()) 20 | } 21 | -------------------------------------------------------------------------------- /src/tpm/src/tpm2_digests.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | use alloc::vec::Vec; 6 | use global::{VtpmError, VtpmResult}; 7 | 8 | pub const TPM2_HASH_ALG_ID_SHA256: u16 = 0xb; 9 | pub const TPM2_HASH_ALG_ID_SHA384: u16 = 0xc; 10 | pub const TPM2_HASH_ALG_ID_SHA512: u16 = 0xd; 11 | 12 | pub const TPM2_SUPPORTED_HASH_COUNT: usize = 4; 13 | pub const MAX_TPM2_DIGESTS_SIZE: usize = (MAX_TPM2_HASH_SIZE + 2) * TPM2_SUPPORTED_HASH_COUNT; 14 | 15 | pub const TPM2_SHA256_SIZE: usize = 32; 16 | pub const TPM2_SHA384_SIZE: usize = 48; 17 | pub const TPM2_SHA512_SIZE: usize = 64; 18 | pub const MAX_TPM2_HASH_SIZE: usize = TPM2_SHA512_SIZE; 19 | 20 | #[derive(Debug, PartialEq, Copy, Clone)] 21 | pub struct Tpm2Digest { 22 | pub alg_id: u16, 23 | pub hash_size: usize, 24 | pub total_size: usize, 25 | pub hash: [u8; MAX_TPM2_HASH_SIZE], 26 | } 27 | 28 | impl Tpm2Digest { 29 | pub fn new(alg_id: u16, value: &[u8]) -> Option { 30 | let hash_size = Tpm2Digest::get_hash_size(alg_id)?; 31 | if value.len() != hash_size { 32 | return None; 33 | } 34 | 35 | let mut hash: [u8; MAX_TPM2_HASH_SIZE] = [0; MAX_TPM2_HASH_SIZE]; 36 | hash[..hash_size].copy_from_slice(value); 37 | 38 | let total_size = hash_size + 2; 39 | 40 | Some(Self { 41 | alg_id, 42 | hash_size, 43 | total_size, 44 | hash, 45 | }) 46 | } 47 | 48 | fn get_hash_size(alg_id: u16) -> Option { 49 | match alg_id { 50 | TPM2_HASH_ALG_ID_SHA256 => Some(TPM2_SHA256_SIZE), 51 | TPM2_HASH_ALG_ID_SHA384 => Some(TPM2_SHA384_SIZE), 52 | TPM2_HASH_ALG_ID_SHA512 => Some(TPM2_SHA512_SIZE), 53 | _ => None, 54 | } 55 | } 56 | 57 | pub fn from_bytes(bytes: &[u8]) -> Option { 58 | let alg_id = u16::from_be_bytes([bytes[0], bytes[1]]); 59 | let hash_size = Tpm2Digest::get_hash_size(alg_id)?; 60 | if bytes.len() < hash_size + 2 { 61 | return None; 62 | } 63 | 64 | Tpm2Digest::new(alg_id, &bytes[2..hash_size + 2]) 65 | } 66 | 67 | pub fn to_bytes(&self, out_buffer: &mut [u8]) -> Option { 68 | if out_buffer.len() < self.total_size { 69 | return None; 70 | } 71 | 72 | out_buffer[..2].copy_from_slice(&self.alg_id.to_be_bytes()); 73 | out_buffer[2..self.hash_size + 2].copy_from_slice(&self.hash[..self.hash_size]); 74 | 75 | Some(self.total_size) 76 | } 77 | } 78 | 79 | #[derive(Debug, PartialEq, Clone)] 80 | pub struct Tpm2Digests { 81 | digests: Vec, 82 | pub total_size: usize, 83 | pub digests_count: usize, 84 | } 85 | 86 | impl Tpm2Digests { 87 | pub fn new() -> Tpm2Digests { 88 | Self { 89 | digests: Vec::new(), 90 | total_size: 0, 91 | digests_count: 0, 92 | } 93 | } 94 | 95 | pub fn push_digest(&mut self, digest: &Tpm2Digest) -> VtpmResult { 96 | let hash_size = Tpm2Digest::get_hash_size(digest.alg_id); 97 | if hash_size.is_none() { 98 | return Err(VtpmError::InvalidParameter); 99 | } 100 | 101 | self.digests.push(*digest); 102 | self.total_size += digest.total_size; 103 | self.digests_count += 1; 104 | 105 | Ok(()) 106 | } 107 | 108 | pub fn from_bytes(bytes: &[u8]) -> Option { 109 | let size = bytes.len(); 110 | let mut offset: usize = 0; 111 | let mut digests = Tpm2Digests::default(); 112 | 113 | loop { 114 | let dig = Tpm2Digest::from_bytes(&bytes[offset..])?; 115 | offset = dig.total_size; 116 | let _ = digests.push_digest(&dig); 117 | 118 | if offset >= size { 119 | break; 120 | } 121 | } 122 | 123 | Some(digests) 124 | } 125 | 126 | pub fn to_bytes(&self, out_buffer: &mut [u8]) -> Option { 127 | let mut offset: usize = 0; 128 | let out_buffer_size = out_buffer.len(); 129 | let mut tmp_buffer: [u8; MAX_TPM2_HASH_SIZE + 2] = [0; MAX_TPM2_HASH_SIZE + 2]; 130 | 131 | if out_buffer_size < self.total_size { 132 | return None; 133 | } 134 | 135 | for digest in &self.digests { 136 | if digest.total_size > out_buffer_size - offset { 137 | return None; 138 | } 139 | let size = digest.to_bytes(&mut tmp_buffer)?; 140 | out_buffer[offset..offset + digest.total_size].copy_from_slice(&tmp_buffer[..size]); 141 | offset += digest.total_size; 142 | } 143 | 144 | Some(offset) 145 | } 146 | } 147 | 148 | impl Default for Tpm2Digests { 149 | fn default() -> Self { 150 | Self::new() 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /src/tpm/src/tpm2_sys.rs: -------------------------------------------------------------------------------- 1 | /* automatically generated by rust-bindgen 0.59.2 */ 2 | 3 | extern "C" { 4 | pub fn _plat__RunCommand( 5 | requestSize: u32, 6 | request: *mut crate::cty::c_uchar, 7 | responseSize: *mut u32, 8 | response: *mut *mut crate::cty::c_uchar, 9 | ); 10 | } 11 | 12 | extern "C" { 13 | pub fn _plat__TPM_Terminate() -> crate::cty::c_int; 14 | } 15 | 16 | extern "C" { 17 | pub fn _plat__TPM_Initialize( 18 | firstTime: crate::cty::c_int, 19 | platParameter: *mut crate::cty::c_void, 20 | ) -> crate::cty::c_int; 21 | } 22 | 23 | extern "C" { 24 | pub fn _plat__NvMemoryRead( 25 | startOffset: crate::cty::c_uint, 26 | size: crate::cty::c_uint, 27 | data: *mut crate::cty::c_void, 28 | ); 29 | } 30 | 31 | extern "C" { 32 | pub fn _TPM_Hash_Start(); 33 | } 34 | 35 | extern "C" { 36 | pub fn _TPM_Hash_Data(dataSize: u32, data: *mut crate::cty::c_uchar); 37 | } 38 | 39 | extern "C" { 40 | pub fn _TPM_Hash_End(); 41 | } 42 | -------------------------------------------------------------------------------- /src/vtpmtd/.gitignore: -------------------------------------------------------------------------------- 1 | clear-*-kvm.img* 2 | fat*.img 3 | target 4 | test_data 5 | Cargo.lock 6 | *.o 7 | *.obj 8 | -------------------------------------------------------------------------------- /src/vtpmtd/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "vtpmtd" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | [dependencies] 7 | attestation = { path = "../attestation", default-features = false } 8 | bitfield = "0.13.2" 9 | bitflags = "1.2.1" 10 | bitmap-allocator = { git = "https://github.com/rcore-os/bitmap-allocator", rev = "03bd9909" } 11 | conquer-once = { version = "0.3.2", default-features = false } 12 | scroll = { version = "0.10", default-features = false, features = ["derive"]} 13 | spin = "0.9.2" 14 | x86 = "0.47.0" 15 | x86_64 = "0.14.9" 16 | zerocopy = { version = "0.7.31", features = ["derive"] } 17 | anyhow = { version = "1.0.68", default-features = false } 18 | sha2 = { version = "0.10.6", default-features = false, features = ["force-soft"]} 19 | bytes = { version="1", default-features=false } 20 | der = {version = "0.7.9", features = ["oid", "alloc", "derive"]} 21 | 22 | eventlog = { path = "../eventlog" } 23 | linked_list_allocator = "0.10.2" 24 | log = "0.4.13" 25 | td-shim-interface = { path = "../../deps/td-shim/td-shim-interface" } 26 | tdx-tdcall = { path = "../../deps/td-shim/tdx-tdcall" } 27 | td-logger = { path = "../../deps/td-shim/td-logger" } 28 | td-exception = { path = "../../deps/td-shim/td-exception", features = ["tdx"]} 29 | td-layout = { path = "../../deps/td-shim/td-layout" } 30 | td-loader = { path = "../../deps/td-shim/td-loader"} 31 | td-paging = { path = "../../deps/td-shim/td-paging" } 32 | td-payload = { path = "../../deps/td-shim/td-payload", features = ["tdx"] } 33 | td-shim = { path = "../../deps/td-shim/td-shim", default-featuers = false } 34 | 35 | spdmlib = { path = "../../deps/spdm-rs/spdmlib", default-features = false, features = ["spdm-ring", "mut-auth", "is_sync"]} 36 | codec = { path = "../../deps/spdm-rs/codec" } 37 | 38 | byteorder = { version = "1.0", default-features = false } 39 | ring = { version = "0.17.6" } 40 | 41 | global = { path = "../global" } 42 | crypto = { path = "../crypto" } 43 | protocol = { path = "../protocol" } 44 | spdm = { path = "../spdm" } 45 | tdtunnel = { path = "../tdtunnel" } 46 | tpm = { path = "../tpm" } 47 | 48 | td-benchmark = { path = "../../deps/td-shim/devtools/td-benchmark", default-features = false, optional = true } 49 | 50 | [dependencies.lazy_static] 51 | version = "1.0" 52 | features = ["spin_no_std"] 53 | 54 | [features] 55 | remote-attestation = ["attestation/remote-attestation"] 56 | sha256 = [] 57 | sha384 = [] 58 | sha512 = [] 59 | test_heap_size = ["td-benchmark", "td-payload/test_heap_size"] 60 | test_stack_size = ["td-benchmark"] 61 | -------------------------------------------------------------------------------- /src/vtpmtd/src/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | #![cfg_attr(not(test), no_std)] 6 | #![cfg_attr(not(test), no_main)] 7 | #![cfg_attr(test, allow(unused_imports))] 8 | #![feature(alloc_error_handler)] 9 | #![feature(naked_functions)] 10 | #![allow(unused)] 11 | 12 | extern crate alloc; 13 | 14 | #[allow( 15 | unused, 16 | non_snake_case, 17 | non_upper_case_globals, 18 | non_camel_case_types, 19 | improper_ctypes 20 | )] 21 | #[allow(unused)] 22 | mod vtpm; 23 | 24 | use core::ffi::c_void; 25 | use core::panic::PanicInfo; 26 | use linked_list_allocator::LockedHeap; 27 | use td_layout::runtime::*; 28 | use td_shim_interface::td_uefi_pi::hob::{ 29 | check_hob_integrity, dump_hob, get_system_memory_size_below_4gb, 30 | }; 31 | 32 | #[cfg(not(test))] 33 | #[no_mangle] 34 | #[cfg(target_os = "none")] 35 | pub extern "C" fn _start(hob: u64, payload: u64) -> ! { 36 | use td_payload::arch; 37 | use td_payload::mm::end_of_ram; 38 | use td_payload::mm::layout::*; 39 | 40 | const STACK_SIZE: usize = 0x10_0000; // 1M 41 | const HEAP_SIZE: usize = 0x20_0000; // 2M 42 | const PT_SIZE: usize = 0x8_0000; 43 | 44 | extern "C" { 45 | fn start_spdm_server(); 46 | } 47 | 48 | let layout = RuntimeLayout { 49 | heap_size: HEAP_SIZE, 50 | stack_size: STACK_SIZE, 51 | page_table_size: PT_SIZE, 52 | shared_memory_size: DEFAULT_SHARED_MEMORY_SIZE, 53 | #[cfg(feature = "cet-shstk")] 54 | shadow_stack_size: DEFAULT_SHADOW_STACK_SIZE, 55 | }; 56 | 57 | #[cfg(feature = "test_stack_size")] 58 | { 59 | td_benchmark::StackProfiling::init(0x5a5a_5a5a_5a5a_5a5a, 0xd000); 60 | } 61 | 62 | let _ = td_logger::init(); 63 | log::info!("vtpm-td is startup\n"); 64 | 65 | #[cfg(any(feature = "test_stack_size", feature = "test_heap_size"))] 66 | { 67 | log::info!("td_benchmark enabled.\n"); 68 | } 69 | 70 | arch::init::pre_init(hob, &layout); 71 | 72 | // Init internal heap 73 | attestation::attest_init_heap(); 74 | 75 | // Run the global constructors 76 | init(payload); 77 | 78 | arch::init::init(&layout, start_spdm_server); 79 | 80 | panic!("deadloop"); 81 | } 82 | 83 | #[cfg(target_os = "none")] 84 | fn init(payload: u64) { 85 | use td_loader::elf; 86 | 87 | let elf = unsafe { 88 | core::slice::from_raw_parts( 89 | payload as *const u8, 90 | td_layout::runtime::exec::PAYLOAD_SIZE as usize, 91 | ) 92 | }; 93 | 94 | // Call the init functions (contains C++ constructions of global variables) 95 | if let Some(range) = elf::parse_init_array_section(elf) { 96 | let mut init_start = payload as usize + range.start; 97 | let init_end = payload as usize + range.end; 98 | while init_start < init_end { 99 | let init_fn = init_start as *const fn(); 100 | unsafe { (*init_fn)() }; 101 | init_start += 8; 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/vtpmtd/src/vtpm/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | pub mod spdm_cbs; 6 | pub mod spdm_connection; 7 | pub mod spdm_server; 8 | -------------------------------------------------------------------------------- /src/vtpmtd/src/vtpm/spdm_cbs.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 - 2023 Intel Corporation 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | use codec::Writer; 6 | use core::ffi::c_uchar; 7 | 8 | use crypto::resolve::{get_cert_from_certchain, verify_peer_cert}; 9 | use global::{VtpmError, VtpmResult, GLOBAL_SPDM_DATA, GLOBAL_TPM_DATA}; 10 | use ring::digest; 11 | 12 | use spdmlib::{ 13 | config::MAX_SPDM_MSG_SIZE, 14 | crypto::{cert_operation, SpdmCertOperation}, 15 | error::{SpdmResult, SPDM_STATUS_INVALID_CERT}, 16 | responder::ResponderContext, 17 | }; 18 | use tdx_tdcall::tdreport::{TdxReport, TD_REPORT_SIZE}; 19 | use tpm::{ 20 | execute_command, start_tpm, 21 | tpm2_digests::TPM2_SHA384_SIZE, 22 | tpm2_sys::{_TPM_Hash_Data, _TPM_Hash_End, _TPM_Hash_Start}, 23 | }; 24 | 25 | fn spdm_secure_app_message_handler<'a>( 26 | _: &mut ResponderContext, 27 | session_id: u32, 28 | app_buffer: &[u8], 29 | auxiliary_app_data: usize, 30 | writer: &'a mut Writer, 31 | ) -> (SpdmResult, Option<&'a [u8]>) { 32 | assert!(GLOBAL_SPDM_DATA.lock().valid); 33 | let tpm_cmd = app_buffer; 34 | let tpm_cmd_size = app_buffer.len(); 35 | 36 | let mut tpm_rsp: [u8; MAX_SPDM_MSG_SIZE] = [0; MAX_SPDM_MSG_SIZE]; 37 | 38 | let (rsp_size, rsp_code) = execute_command(tpm_cmd, &mut tpm_rsp, 0); 39 | 40 | writer.extend_from_slice(&tpm_rsp[..rsp_size as usize]); 41 | 42 | (Ok(()), Some(writer.used_slice())) 43 | } 44 | 45 | pub fn register_spdm_secure_app_message_handler() -> bool { 46 | let mut handler = spdmlib::responder::app_message_handler::SpdmAppMessageHandler { 47 | dispatch_secured_app_message_cb: spdm_secure_app_message_handler, 48 | }; 49 | 50 | spdmlib::responder::app_message_handler::register(handler) 51 | } 52 | 53 | pub fn gen_hcrtm_sequence(tdx_report: &[u8]) -> VtpmResult { 54 | if !GLOBAL_TPM_DATA.lock().tpm_active() { 55 | start_tpm(); 56 | GLOBAL_TPM_DATA.lock().set_tpm_active(true); 57 | } 58 | 59 | // Before extending TdReport.ReportData and TdReport.Mac shall be zeroed. 60 | let mut report = TdxReport::default(); 61 | report.as_bytes_mut().copy_from_slice(tdx_report); 62 | report.report_mac.mac.iter_mut().for_each(|m| *m = 0); 63 | report 64 | .report_mac 65 | .report_data 66 | .iter_mut() 67 | .for_each(|m| *m = 0); 68 | 69 | let td_report = report.as_bytes(); 70 | 71 | let td_report_sha384 = digest::digest(&digest::SHA384, td_report); 72 | 73 | let mut data: [u8; TPM2_SHA384_SIZE] = [0; TPM2_SHA384_SIZE]; 74 | data.copy_from_slice(td_report_sha384.as_ref()); 75 | 76 | let ptr: *mut c_uchar = data.as_mut_ptr() as *mut c_uchar; 77 | 78 | unsafe { 79 | _TPM_Hash_Start(); 80 | _TPM_Hash_Data(TPM2_SHA384_SIZE as u32, ptr); 81 | _TPM_Hash_End(); 82 | } 83 | 84 | Ok(()) 85 | } 86 | 87 | pub fn get_cert_from_cert_chain_cb(cert_chain: &[u8], index: isize) -> SpdmResult<(usize, usize)> { 88 | get_cert_from_certchain(cert_chain, index) 89 | } 90 | 91 | pub fn verify_cert_chain_cb(cert_chain: &[u8]) -> SpdmResult { 92 | let mut td_report: [u8; TD_REPORT_SIZE] = [0; TD_REPORT_SIZE]; 93 | verify_peer_cert(cert_chain, &mut td_report)?; 94 | let res = gen_hcrtm_sequence(&td_report); 95 | if res.is_err() { 96 | return Err(SPDM_STATUS_INVALID_CERT); 97 | } 98 | 99 | Ok(()) 100 | } 101 | 102 | pub fn register_spdm_cert_operation() -> bool { 103 | let mut handler = SpdmCertOperation { 104 | get_cert_from_cert_chain_cb, 105 | verify_cert_chain_cb, 106 | }; 107 | 108 | cert_operation::register(handler) 109 | } 110 | --------------------------------------------------------------------------------