├── .github ├── auto_assign-issues.yml ├── auto_assign.yml └── workflows │ ├── create_release.yml │ ├── dco.yml │ ├── lint.yml │ └── test.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── docs ├── extended.PNG ├── regular.PNG └── snpguest.1.adoc └── src ├── certs.rs ├── display.rs ├── fetch.rs ├── hyperv └── mod.rs ├── key.rs ├── main.rs ├── ok.rs ├── preattestation.rs ├── report.rs └── verify.rs /.github/auto_assign-issues.yml: -------------------------------------------------------------------------------- 1 | addAssignees: true 2 | 3 | assignees: 4 | - tylerfanelli 5 | - larrydewey 6 | - DGonzalezVillal 7 | -------------------------------------------------------------------------------- /.github/auto_assign.yml: -------------------------------------------------------------------------------- 1 | # Set to true to add reviewers to pull requests 2 | addReviewers: true 3 | 4 | # Set to true to add assignees to pull requests 5 | addAssignees: true 6 | 7 | # A list of reviewers to be added to pull requests (GitHub user name) 8 | reviewers: 9 | - DGonzalezVillal 10 | - tylerfanelli 11 | - larrydewey 12 | 13 | # A list of keywords to be skipped the process that add reviewers if pull requests include it 14 | skipKeywords: 15 | - wip 16 | - WIP 17 | 18 | # A number of reviewers added to the pull request 19 | # Set 0 to add all the reviewers (default: 0) 20 | numberOfReviewers: 2 21 | -------------------------------------------------------------------------------- /.github/workflows/create_release.yml: -------------------------------------------------------------------------------- 1 | permissions: 2 | contents: write 3 | 4 | on: 5 | workflow_dispatch: 6 | inputs: 7 | create_release: 8 | description: 'Create a release from current commit' 9 | type: boolean 10 | default: false 11 | release_name: 12 | description: 'Release name (optional)' 13 | required: false 14 | type: string 15 | push: 16 | branches: [main, master] 17 | tags: 18 | - "v[0-9]+.[0-9]+.[0-9]+" 19 | pull_request: 20 | branches: [main, master] 21 | 22 | name: Build and Release 23 | 24 | jobs: 25 | build: 26 | name: Build and Test 27 | runs-on: ubuntu-latest 28 | steps: 29 | - run: sudo apt-get install -y asciidoctor musl-tools 30 | - uses: actions/checkout@v4 31 | - uses: actions-rs/toolchain@v1 32 | with: 33 | toolchain: stable 34 | target: x86_64-unknown-linux-musl 35 | override: true 36 | 37 | - name: Build 38 | uses: actions-rs/cargo@v1 39 | with: 40 | command: build 41 | args: --release --target x86_64-unknown-linux-musl 42 | 43 | - name: Test 44 | uses: actions-rs/cargo@v1 45 | with: 46 | command: test 47 | args: --release --target x86_64-unknown-linux-musl 48 | 49 | - name: Verify binary exists 50 | run: ls -la target/x86_64-unknown-linux-musl/release/snpguest 51 | 52 | - name: Upload Build Artifact 53 | uses: actions/upload-artifact@v4 54 | with: 55 | name: snpguest-binary 56 | path: target/x86_64-unknown-linux-musl/release/snpguest 57 | 58 | release: 59 | name: Create Release 60 | needs: build 61 | if: startsWith(github.ref, 'refs/tags/v') || (github.event_name == 'workflow_dispatch' && github.event.inputs.create_release == 'true') 62 | runs-on: ubuntu-latest 63 | steps: 64 | - uses: actions/checkout@v4 65 | 66 | - name: Download Build Artifact 67 | uses: actions/download-artifact@v4 68 | with: 69 | name: snpguest-binary 70 | path: ./ 71 | 72 | - name: Make binary executable 73 | run: | 74 | ls -la 75 | chmod +x ./snpguest 76 | 77 | - name: Create GitHub Release 78 | uses: softprops/action-gh-release@v2 79 | with: 80 | files: ./snpguest 81 | generate_release_notes: true 82 | name: ${{ github.event.inputs.release_name || '' }} 83 | tag_name: ${{ startsWith(github.ref, 'refs/tags/') && github.ref_name || format('manual-release-{0}', github.sha) }} 84 | env: 85 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 86 | -------------------------------------------------------------------------------- /.github/workflows/dco.yml: -------------------------------------------------------------------------------- 1 | name: Sign-off Check 2 | 3 | on: 4 | pull_request: 5 | 6 | jobs: 7 | check: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: KineticCafe/actions-dco@v1 11 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | name: lint 3 | jobs: 4 | fmt: 5 | name: cargo fmt 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v2 9 | - uses: actions-rs/toolchain@v1 10 | with: 11 | components: rustfmt 12 | toolchain: nightly 13 | profile: minimal 14 | override: true 15 | - uses: actions-rs/cargo@v1 16 | with: 17 | command: fmt 18 | args: --all -- --check 19 | 20 | clippy: 21 | name: cargo clippy 22 | runs-on: ubuntu-latest 23 | steps: 24 | - run: sudo apt-get install -y asciidoctor 25 | - uses: actions/checkout@v2 26 | - uses: actions-rs/toolchain@v1 27 | with: 28 | components: clippy 29 | toolchain: 1.80.0 30 | profile: minimal 31 | override: true 32 | - uses: actions-rs/cargo@v1 33 | with: 34 | command: clippy 35 | args: --all-targets -- -D clippy::all -D unused_imports -Dwarnings 36 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | name: test 3 | jobs: 4 | test: 5 | name: ${{ matrix.toolchain }} (${{ matrix.profile.name }}) 6 | runs-on: ubuntu-latest 7 | steps: 8 | - run: sudo apt-get install -y asciidoctor 9 | - uses: actions/checkout@v2 10 | - uses: actions-rs/toolchain@v1 11 | with: 12 | toolchain: ${{ matrix.toolchain }} 13 | override: true 14 | - uses: actions-rs/cargo@v1 15 | with: 16 | command: test 17 | args: ${{ matrix.profile.flag }} 18 | strategy: 19 | fail-fast: false 20 | matrix: 21 | toolchain: 22 | - nightly 23 | - beta 24 | - stable 25 | profile: 26 | - name: debug 27 | - name: release 28 | flag: --release 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | .vscode -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "snpguest" 3 | version = "0.9.1" 4 | authors = ["The VirTEE Project Developers"] 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | homepage = "https://github.com/virtee/snpguest" 8 | repository = "https://github.com/virtee/snpguest" 9 | description = "Navigation utility for AMD SEV-SNP guest environment" 10 | readme = "README.md" 11 | keywords = ["amd", "sev", "sev-snp", "snp"] 12 | exclude = [ ".gitignore", ".github/*" ] 13 | rust-version = "1.80" 14 | 15 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 16 | 17 | [features] 18 | default = [] 19 | hyperv = ["tss-esapi"] 20 | 21 | [dependencies] 22 | clap = { version = "4.5", features = [ "derive" ] } 23 | env_logger = "0.10.0" 24 | anyhow = "1.0.69" 25 | sev = { version = "6.1.0", default-features = false, features = ['openssl','snp']} 26 | nix = "^0.23" 27 | serde = { version = "1.0", features = ["derive"] } 28 | bincode = "^1.2.1" 29 | openssl = { version = "^0.10", features = ["vendored"]} 30 | reqwest = { version="0.11.10", features = ["blocking"] } 31 | hex = "0.4" 32 | x509-parser = { version="0.16.0", features=["verify"] } 33 | asn1-rs = "0.6.2" 34 | rand = "0.8.5" 35 | tss-esapi = { version = "7.2", optional=true } 36 | msru = "0.2.0" 37 | colorful = "0.2.2" 38 | bitfield = "0.15.0" 39 | clap-num = "1.1.1" 40 | base64 = "0.22.1" 41 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # snpguest 2 | 3 | `snpguest` is a Command Line Interface utility for managing an AMD SEV-SNP enabled guest. This tool allows users to interact with the AMD SEV-SNP guest firmware device enabling various operations such as: attestation, certificate management, derived key fetching, and more. 4 | 5 | - [Usage](#usage) 6 | - [1. help](#1-help) 7 | - [2. certificates](#2-certificates) 8 | - [3. display](#3-display) 9 | - [4. fetch](#4.fetch) 10 | - [5. key](#5-key) 11 | - [6. report](#6-report) 12 | - [7. verify](#7-verify) 13 | - [Extended Attestation Workflow](#extended-attestation-workflow) 14 | - [Regular Attestation Workflow](#regular-attestation-workflow) 15 | - [Global Options](#global-options) 16 | - [Extended Attestation Flowchart](#extended-attestation-flowchart) 17 | - [Regular Attestation Flowchart](#regular-attestation-flowchart) 18 | - [Building](#building) 19 | - [Ubuntu Dependencies](#ubuntu-dependencies) 20 | - [RHEL and its compatible distributions dependencies](#rhel-and-its-compatible-distributions-dependencies) 21 | - [openSUSE and its compatible distributions dependencies](#opensuse-and-its-compatible-distributions-dependencies) 22 | - [Reporting Bugs](#reporting-bugs) 23 | 24 | ## Usage 25 | 26 | ### 1. `help` 27 | 28 | Every `snpguest` (sub)command comes with a `--help` option for a description on its use. 29 | 30 | Usage 31 | ```bash 32 | snpguest --help 33 | ``` 34 | 35 | ### 2. `certificates` 36 | 37 | Requests the certificate chain (ASK, ARK & VCEK) from host memory (requests extended-config). The user needs to specify the certificate encoding to store the certificates in (PEM or DER). Currently, only PEM and DER encodings are supported. All certificates will be in the same encoding. The user also needs to provide the path to the directory where the certificates will be stored. If certificates already exist in the provided directory, they will be overwritten. 38 | 39 | Usage 40 | ```bash 41 | snpguest certificates $ENCODING $CERTS_DIR 42 | ``` 43 | Arguments 44 | 45 | - `$ENCODING` : Specifies the certificate encoding to store the certificates in (PEM or DER). 46 | 47 | - `$CERTS_DIR` : Specifies the directory to store the certificates in. This is required only when requesting an extended attestation report. 48 | 49 | Example 50 | ```bash 51 | snpguest certificates pem ./certs 52 | ``` 53 | 54 | ### 3. `display` 55 | 56 | Displays files in human readable form. 57 | 58 | Usage 59 | ```bash 60 | snpguest display 61 | ``` 62 | Subcommands 63 | 64 | 1. `report` 65 | 66 | When used for displaying a report, it prints the attestation report contents into the terminal. The user has to provide the path of the stored attestation report to display. 67 | 68 | Usage 69 | ```bash 70 | snpguest display report $ATT_REPORT_PATH 71 | ``` 72 | 73 | Argument 74 | 75 | - `$ATT_REPORT_PATH` : Specifies the path of the stored attestation report to display. 76 | 77 | Example 78 | ```bash 79 | snpguest display report attestation-report.bin 80 | ``` 81 | 82 | 2. `key` 83 | 84 | When used for displaying the fetched derived key's contents, it prints the derived key in hex format into the terminal. The user has to provide the path of a stored derived key to display. 85 | 86 | Usage 87 | 88 | ```bash 89 | snpguest display key $KEY_PATH 90 | ``` 91 | Argument 92 | 93 | - `$KEY_PATH` : Specifies the path of the stored derived key to display. 94 | 95 | Example 96 | ```bash 97 | snpguest display key derived-key.bin 98 | ``` 99 | 100 | ### 4. `fetch` 101 | 102 | Command to Requests certificates from the KDS. 103 | 104 | Usage 105 | ```bash 106 | snpguest fetch 107 | ``` 108 | 109 | Subcommands 110 | 1. `ca` 111 | 112 | Requests the certificate authority chain (ARK & ASK) from the KDS. The user needs to specify the certificate encoding to store the certificates in (PEM or DER). Currently, only PEM and DER encodings are supported. Both certificates will be in the same encoding. The user must specify their host processor model. The user also needs to provide the path to the directory where the certificates will be stored. If the certificates already exist in the provided directory, they will be overwritten. The `--endorser` argument specifies the type of attestation signing key (defaults to VCEK). 113 | 114 | Usage 115 | ```bash 116 | snpguest fetch ca $ENCODING $PROCESSOR_MODEL $CERTS_DIR --endorser $ENDORSER 117 | ``` 118 | Arguments 119 | 120 | - `$ENCODING` : Specifies the certificate encoding to store the certificates in (PEM or DER). 121 | 122 | - `$PROCESSOR_MODEL` : Specifies the host processor model. 123 | 124 | - `$CERTS_DIR` : Specifies the directory to store the certificates in. 125 | - `$ENDORSER` : Specifies the endorser type, possible values: vcek, vlek. 126 | 127 | Example 128 | ```bash 129 | snpguest fetch ca der milan ./certs-kds -e vlek 130 | ``` 131 | 132 | 2. `vcek` 133 | 134 | Requests the VCEK certificate from the KDS. The user needs to specify the certificate encoding to store the certificate in (PEM or DER). Currently, only PEM and DER encodings are supported. The user must specify their host processor model. The user also needs to provide the path to the directory where the VCEK will be stored and the path to a stored attestation report that will be used to request the VCEK. If the certificate already exists in the provided directory, it will be overwritten. 135 | 136 | Usage 137 | ```bash 138 | snpguest fetch vcek $ENCODING $PROCESSOR_MODEL $CERTS_DIR $ATT_REPORT_PATH 139 | ``` 140 | Arguments 141 | 142 | - `$ENCODING` : Specifies the certificate encoding to store the certificates in (PEM or DER). 143 | 144 | - `$PROCESSOR_MODEL` : Specifies the host processor model. 145 | 146 | - `$CERTS_DIR` : Specifies the directory to store the certificates in. 147 | 148 | - `$ATT_REPORT_PATH` : Specifies the path of the stored attestation report. 149 | 150 | Example 151 | ```bash 152 | snpguest fetch vcek der milan ./certs-kds attestation-report.bin 153 | ``` 154 | 155 | ### 5. `key` 156 | 157 | Creates the derived key based on input parameters and stores it. `$KEY_PATH` is the path to store the derived key. `$ROOT_KEY_SELECT` is the root key from which to derive the key (either "vcek" or "vmrk"). The `--guest_field_select` option specifies which Guest Field Select bits to enable as a 6-digit binary string. Each of the 6 bits from left to right correspond to Guest Policy, Image ID, Family ID, Measurement, SVN and TCB Version respectively. For each bit, 0 denotes off, and 1 denotes on. The `--guest_svn` option specifies the guest SVN to mix into the key, and the `--tcb_version` option specifies the TCB version to mix into the derived key. The `--vmpl` option specifies the VMPL level the Guest is running on and defaults to 1. 158 | 159 | 160 | Usage 161 | ```bash 162 | snpguest key $KEY_PATH $ROOT_KEY_SELECT [-g, --guest_field_select] [-s, --guest_svn] [-t, --tcb_version] [-v, --vmpl] 163 | ``` 164 | Arguments 165 | 166 | - `$KEY_PATH` : The path to store the derived key. 167 | 168 | - `$ROOT_KEY_SELECT` : is the root key from which to derive the key (either "vcek" or "vmrk"). 169 | 170 | Options 171 | 172 | - `--guest_field_select` : option specifies which Guest Field Select bits to enable as a 6-digit binary string. For each bit, 0 denotes off, and 1 denotes on. 173 | 174 | For example, `--guest_field_select 100001` denotes 175 | 176 | Guest Policy:On (1), 177 | 178 | Image ID:Off (0), 179 | 180 | Family ID:Off (0), 181 | 182 | Measurement:Off (0), 183 | 184 | SVN:Off (0), 185 | 186 | TCB Version:On (1). 187 | 188 | - `--guest_svn` : option specifies the guest SVN to mix into the key, 189 | 190 | - `--tcb_version` : option specifies the TCB version to mix into the derived key. 191 | 192 | - `--vmpl` : option specifies the VMPL level the Guest is running on and defaults to 1. 193 | 194 | Example 195 | ```bash 196 | # Creating and storing a derived key 197 | snpguest key derived-key.bin vcek --guest_field_select 100001 --guest_svn 2 --tcb_version 1 --vmpl 3 198 | ``` 199 | 200 | ### 6. `report` 201 | 202 | Requests an attestation report from the host and writes it to a file with the provided request data and VMPL. The attestation report is written in binary format to the specified report path. The user can pass 64 bytes of data in any file format into `$REQUEST_FILE` to request the attestation report. The `--random` flag can be used to generate and use random data for the request, and for Microsoft Hyper-V guests, the `--platform` flag is required to use pre-generated request data. The data already generated from the hypervisor will be written into the file provided in `$REQUEST_FILE`. `VMPL` is an optional parameter that defaults to 1. `--random` is not available in Hyper-V, as the request data is pre-generated. 203 | 204 | Usage 205 | ```bash 206 | snpguest report $ATT_REPORT_PATH $REQUEST_FILE [-v, --vmpl] [-r, --random] [-p, --platform] 207 | ``` 208 | 209 | Arguments 210 | 211 | - `$ATT_REPORT_PATH` : Specifies the path where the attestation report would be stored. 212 | 213 | - `$REQUEST_FILE` : File where the data generated from the hypervisor will be written into. 214 | 215 | Options 216 | 217 | - `-r, --random`: Generate 64 random bytes of data for the report request (Not available for in Hyper-V). 218 | - `-p, --platform` : Use platform provided 64 bytes of data for the request report (Only available for Hyper-V). 219 | - `-v, --vmpl` : option specifies the VMPL level the Guest is running on and defaults to 1. 220 | 221 | Example 222 | ```bash 223 | # Requesting Attestation Report with user-generated data 224 | snpguest report attestation-report.bin request-file.txt 225 | # Requesting Attestation Report using random data 226 | snpguest report attestation-report.bin random-request-file.txt --random 227 | # Requesting Attestation Report using platform data 228 | snpguest report attestation-report.bin platform-request-file.txt --platform 229 | ``` 230 | 231 | ### 7. `verify` 232 | 233 | Verifies certificates and the attestation report. 234 | 235 | Usage 236 | ```bash 237 | snpguest verify 238 | ``` 239 | 240 | Subcommands 241 | 1. `certs` 242 | 243 | Verifies that the provided certificate chain has been properly signed by each certificate. The user needs to provide a directory where all three certificates (ARK, ASK, and VCEK) are stored. An error will be raised if any of the certificates fail verification. 244 | 245 | Usage 246 | ```bash 247 | snpguest verify certs $CERTS_DIR 248 | ``` 249 | Argument 250 | 251 | - `$CERTS_DIR` : Specifies the directory where the certificates are stored in. 252 | 253 | Example 254 | ```bash 255 | snpguest verify certs ./certs 256 | ``` 257 | 258 | 2. `attestation` 259 | 260 | Verifies the contents of the Attestation Report using the VCEK certificate. The user needs to provide the path to the directory containing the VCEK certificate and the path to a stored attestation report to be verified. An error will be raised if the attestation verification fails at any point. The user can use the `-t, --tcb` flag to only validate the TCB contents of the report and the `-s, --signature` flag to only validate the report's signature. 261 | 262 | Usage 263 | ```bash 264 | snpguest verify attestation $CERTS_DIR $ATT_REPORT_PATH [-t, --tcb] [-s, --signature] 265 | ``` 266 | Arguments 267 | 268 | - `$CERTS_DIR` : Specifies the directory where the certificates are stored in. 269 | 270 | - `$ATT_REPORT_PATH` : Specifies the path of the stored attestation report. 271 | 272 | Options 273 | 274 | - `-t, --tcb`: Verify the TCB section of the report only. 275 | - `-s, --signature`: Verify the signature of the report only. 276 | 277 | Example 278 | ```bash 279 | # Verify Attestation 280 | snpguest verify attestation ./certs attestation-report.bin 281 | # Verify Attestation Signature only 282 | snpguest verify attestation ./certs attestation-report.bin --signature 283 | ``` 284 | 285 | ### [Extended Attestation Workflow](#extended-attestation-flowchart) 286 | 287 | **Step 1.** Request the attestation report by providing the two mandatory parameters - $ATT_REPORT_PATH which is the path pointing to where the user wishes to store the attestation report and $REQUEST_FILE which is the path pointing to where the request file used to request the attestation report is stored. The optional parameters [-v, --vmpl] specifies the vmpl level for the attestation report and is set to 1 by default. [-r, --random] generates random data to be used as request data for the attestation report. Lastly, [-p, --platform] obtains the request data from the platform. Microsoft Hyper-V is mandatory when the user is expecting the platform to provide the request data for the attestaion report. 288 | 289 | ```bash 290 | snpguest report $ATT_REPORT_PATH $REQUEST_FILE [-v, --vmpl] [-r, --random] [-p, --platform] 291 | ``` 292 | 293 | **Step 2.** Request certificates from the extended memory by providing the two mandatory parameters - $ENCODING whichspecifies whether to use PEM or DER encoding to store the certificates and $CERTS_DIR which specifies the path in the user's directory where the certificates will be saved. 294 | 295 | ```bash 296 | snpguest certificates $ENCODING $CERTS_DIR 297 | ``` 298 | 299 | **Step 3.** Verify the certificates obtained from the extended memory by providing $CERTS_DIR which specifies the path in the user's directory where the certificates were saved from Step 2. 300 | 301 | ```bash 302 | snpguest verify certs $CERTS_DIR 303 | ``` 304 | 305 | **Step 4.** Verify the attestation by providing the two mandatory parameters - $CERTS_DIR which specifies the path in the user's directory where the certificates were saved from Step 2 and $ATT_REPORT_PATH which is the path pointing to the stored attestation report which the user wishes to verify. The optional parameters [-t, --tcb] is used to verify just the TCB contents of the attestaion report and [-s, --signature] is used to verify just the signature of the attestaion report. 306 | 307 | ```bash 308 | snpguest verify attestation $CERTS_DIR $ATT_REPORT_PATH [-t, --tcb] [-s, --signature] 309 | ``` 310 | 311 | ### [Regular Attestation Workflow](#regular-attestation-flowchart) 312 | 313 | **Step 1.** Request the attestation report by providing the two mandatory parameters - $ATT_REPORT_PATH which is the path pointing to where the user wishes to store the attestation report and $REQUEST_FILE which is the path pointing to where the request file used to request the attestation report is stored. The optional parameters [-v, --vmpl] specifies the vmpl level for the attestation report and is set to 1 by default. [-r, --random] generates random data to be used as request data for the attestation report. Lastly, [-p, --platform] obtains the request data from the platform. Microsoft Hyper-V is mandatory when the user is expecting the platform to provide the request data for the attestation report. 314 | 315 | ```bash 316 | snpguest report $ATT_REPORT_PATH $REQUEST_FILE [-v, --vmpl] [-r, --random] [-p, --platform] 317 | ``` 318 | 319 | **Step 2.** Request AMD Root Key (ARK) and AMD SEV Key (ASK) from the AMD Key Distribution Service (KDS) by providing the three mandatory parameters - $ENCODING which specifies whether to use PEM or DER encoding to store the certificates, $PROCESSOR_MODEL - which specifies the AMD Processor model for which the certificates are to be fetched and $CERTS_DIR which specifies the path in the user's directory where the certificates will be saved. The `-e, --endorser` argument specifies the type of attestation signing key (defaults to VCEK). 320 | 321 | ```bash 322 | snpguest fetch ca $ENCODING $PROCESSOR_MODEL $CERTS_DIR [-e, --endorser] $ENDORSER 323 | ``` 324 | 325 | **Step 3.** Request the Versioned Chip Endorsement Key (VCEK) from the AMD Key Distribution Service (KDS) by providing the three mandatory parameters - $ENCODING whichspecifies whether to use PEM or DER encoding to store the certificates, $PROCESSOR_MODEL - which specifies the AMD Processor model for which the certificates are to be fetched and $CERTS_DIR which specifies the path in the user's directory where the certificates will be saved. 326 | 327 | 328 | ```bash 329 | snpguest fetch vcek $ENCODING $PROCESSOR_MODEL $CERTS_DIR $ATT_REPORT_PATH 330 | ``` 331 | 332 | **Step 4.** Verify the certificates obtained by providing $CERTS_DIR which specifies the path in the user's directory where the certificates were saved from Step 2. 333 | 334 | ```bash 335 | snpguest verify certs $CERTS_DIR 336 | ``` 337 | 338 | **Step 5.** Verify the attestation by providing the two mandatory parameters - $CERTS_DIR which specifies the path in the user's directory where the certificates were saved from Step 2 and $ATT_REPORT_PATH which is the path pointing to the stored attestation report which the user wishes to verify. The optional parameters [-t, --tcb] is used to verify just the TCB contents of the attestaion report and [-s, --signature] is used to verify just the signature of the attestaion report. 339 | 340 | ```bash 341 | snpguest verify attestation $CERTS_DIR $ATT_REPORT_PATH [-t, --tcb] [-s, --signature] 342 | ``` 343 | 344 | ### Global Options 345 | 346 | - **-q, --quiet**: Suppress console output. 347 | 348 | ## Extended Attestation Flowchart 349 | ![alt text](https://github.com/virtee/snpguest/blob/main/docs/extended.PNG?raw=true) 350 | ## Regular Attestation Flowchart 351 | ![alt text](https://github.com/virtee/snpguest/blob/main/docs/regular.PNG?raw=true) 352 | 353 | ## Building 354 | 355 | Some packages may need to be installed on the host system in order to build `snpguest`. 356 | 357 | ```bash 358 | #Rust Installation 359 | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh 360 | source "$HOME/.cargo/env" 361 | 362 | #Building snpguest after cloning 363 | cargo build -r 364 | ``` 365 | ### Ubuntu Dependencies 366 | 367 | ```bash 368 | sudo apt install build-essential 369 | ``` 370 | 371 | ### RHEL and its compatible distributions Dependencies 372 | 373 | ```bash 374 | sudo dnf groupinstall "Development Tools" "Development Libraries" 375 | ``` 376 | 377 | ### openSUSE and its compatible distributions Dependencies 378 | 379 | ```bash 380 | sudo zypper in -t pattern "devel_basis" 381 | ``` 382 | 383 | ## Reporting Bugs 384 | 385 | Please report all bugs to the [Github snpguest](https://github.com/virtee/snpguest/issues) repository. 386 | -------------------------------------------------------------------------------- /docs/extended.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtee/snpguest/58a8eed791647c71b4068bdc121006e82f921041/docs/extended.PNG -------------------------------------------------------------------------------- /docs/regular.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtee/snpguest/58a8eed791647c71b4068bdc121006e82f921041/docs/regular.PNG -------------------------------------------------------------------------------- /docs/snpguest.1.adoc: -------------------------------------------------------------------------------- 1 | snpguest(1) 2 | =========== 3 | 4 | NAME 5 | ---- 6 | snpguest - Command line tool for managing the AMD SEV-SNP Guest environment. 7 | 8 | 9 | SYNOPSIS 10 | -------- 11 | *snpguest* [GLOBAL_OPTIONS] [COMMAND] [COMMAND_ARGS] [SUBCOMMAND] [SUBCOMMAND_ARGS] 12 | *snpguest* [_-h, --help_] 13 | 14 | 15 | DESCRIPTION 16 | ----------- 17 | snpguest is a CLI utility for navigating and interacting with the AMD SEV-SNP 18 | guest firmware device of a guest system. 19 | 20 | 21 | GLOBAL OPTIONS 22 | -------------- 23 | *-q, --quiet*:: Don't print any output to the console. 24 | 25 | 26 | COMMANDS 27 | -------- 28 | *snpguest report*:: 29 | usage: snpguest report $ATT_REPORT_PATH $REQUEST_FILE [-v, --vmpl] $VMPL [-r, --random] [-p, --platform] 30 | 31 | Requests an attestation report from the host and writes it in a file with the provided request data and vmpl. 32 | Will write the contents of the attestation report in binary format into the specified report path. 33 | A path for the attestation report must be provided. 34 | User can pass 64 bytes of data in any file format into $REQUEST_FILE in order to use that data to request the attestation report. 35 | The user can use the --random flag to generate and use random data for request data. 36 | For Microsoft Hyper-V guests, a user can use the --platform flag to use the request data that was pre-generated 37 | from the platform. Currently, for Hyper-V guests, --platform is required, as there is no ability to write 38 | request data for the attestation report. 39 | If the user uses the --random flag, then the data will be written into the file they provided in $REQUEST_FILE. 40 | VMPL is an optional parameter and it defaults to 1. 41 | 42 | options: 43 | -h, --help show a help message. 44 | -p, --platform Use platform generated 64 bytes of data to pass for the report request (Only available for Hyper-V). 45 | -r, --random Generate 64 random bytes of data to pass for the report request (Not available for Hyper-V). 46 | -v, --vmpl Specify a different vmpl level for the attestation report (defaults to 1). 47 | 48 | *snpguest certificates*:: 49 | usage: snpguest certificates $ENCODING $CERTS_DIR 50 | 51 | Requests the certificate chain (ASK, ARK & VCEK) from host memory (requests extended-config). 52 | The user needs to specify the certificate encoding they would like store the certs in [PEM | DER]. 53 | Currently only PEM and DER encondings are supported. 54 | All of the certs will be in the same encoding. 55 | The user also needs to provide the path to the directory where the certs will be stored. 56 | If the certificate already exists in the provided directory, it will be overwritten. 57 | The attestation report will be ingored for this request, to request and store an attestation report use the "report" command. 58 | 59 | options: 60 | -h, --help show a help message 61 | 62 | *snpguest fetch ca*:: 63 | usage: snpguest fetch ca $ENCODING $CERTS_DIR $PROCESSOR_MODEL [-r, --report] $ATT_REPORT_PATH [-E --endorser] $ENDORSEMENT 64 | 65 | Requests the certificate authority chain (ARK & ASK) from the KDS. 66 | The user needs to specify the certificate encoding they would like to store the certs in [PEM | DER]. 67 | Currently, only PEM and DER encodings are supported. 68 | Both certificates will be in the same encoding. 69 | The user needs to provide the path to the directory where the certs will be stored. 70 | If the certificates already exist in the provided directory, they will be overwritten. 71 | The user must either pass a V3 attestation report or manually specify the host processor model using the --processor_model flag. 72 | This ensures the correct CA certificates for attestation are retrieved from the KDS. [Milan | Genoa | Bergamo | Siena | Turin] 73 | Lastly, the user may specify the endorser they would like the CA chain for using the --endorser flag. [VCEK | VLEK] 74 | It will default to VCEK. 75 | 76 | options: 77 | -h, --help show a help message 78 | -p, -processor_model Specify processor model to retrieve the CA certificates for. 79 | -e, --enodorse Specify the endorser type to get the Ca certificates for. (defaults to: VCEK) 80 | 81 | *snpguest fetch vcek*:: 82 | usage: snpguest fetch vcek $ENCODING $CERTS_DIR $ATT_REPORT_PATH [-p, --processor_model] $PROCESSOR_MODEL 83 | 84 | Requests the VCEK certificate from the KDS. 85 | The user needs to specify the certificate encoding they would like store the cert in [PEM | DER]. 86 | Currently only PEM and DER encondings are supported. 87 | The user needs to provide the path to the directory where the VCEK will be stored. 88 | If the certificate already exists in the provided directory, it will be overwritten. 89 | The user must either pass a V3 attestation report or manually specify the host processor model using the --processor_model flag. 90 | This ensures the correct VCEK certificate for attestation is retrieved from the KDS. [Milan | Genoa | Bergamo | Siena | Turin] 91 | 92 | options: 93 | -h, --help show a help message 94 | -p, --processor_model Specify processor model to retrieve the VCEK certificates for. 95 | 96 | *snpguest guest verify certs*:: 97 | usage: snpguest verify certs $CERTS_DIR 98 | 99 | Verifies that the provided certificate chain has been properly signed by each certificate. 100 | The user needs to provide a directory were all 3 of the certificates are stored (ARK,ASK and VCEK). 101 | Error will be raised if any of the certificates fails verification. 102 | 103 | options: 104 | -h, --help show a help message 105 | 106 | *snpguest verify attestation*:: 107 | usage: snpguest verify attestation $CERTS_DIR $ATT_REPORT_PATH [-p, --processor_model] $PROCESSOR_MODEL [-t, --tcb] [-s, --signature] 108 | 109 | Verifies the contents of the Attestation Report using a VEK certificate. 110 | The user needs to provide the path to the directory containing the VEK certificate. 111 | The tool will automatically recognize whether it's a VLEK or VCEK. 112 | If both a VLEK and a VCEK are in the directory, then the VCEK will be used. 113 | The user also needs to provide the path to a stored attestation report to be verified. 114 | If the report is not version 3 or newer, then the user can specify the cpu model to verify using the --processor_model flag. 115 | If no processor model is passed, and the report is a version 2, then the verification will be treated as a Genoa or older verification. 116 | An error will be raised if the attestation verification fails at any point. 117 | The user can use the [-t, --tcb] flag to only validate the tcb contents of the report. 118 | The user can use the [-s, --signature] flag to only validate the report signature. 119 | 120 | options: 121 | -h, --help show a help message 122 | -p, --processor_model Specify the processor model to use for verification 123 | -t, --tcb verify the tcb section of the report only 124 | -s, --signature verify the signature of the report only 125 | 126 | *snpguest key*:: 127 | usage: snpguest key $KEY_PATH $ROOT_KEY_SELECT [-g, --guest_field_select] [-s, --guest_svn] [-t, --tcb_version] [-v, --vmpl] 128 | 129 | Creates the derived key based on input parameters and stores it. 130 | $KEY_PATH is the path to store the derived key. 131 | $ROOT_KEY_SELECT is the root key from which to derive the key. Input either "vcek" or "vmrk". 132 | The --guest_field_select option specifies which Guest Field Select bits to enable. It is a 6 digit binary string. For each bit, 0 denotes off and 1 denotes on. 133 | The least significant (rightmost) bit is Guest Policy followed by Image ID, Family ID, Measurement, SVN, TCB Version which is the most significant (leftmost) bit. 134 | example: snpguest key $KEY_PATH $ROOT_KEY_SELECT --guest_field_select 100001 (Denotes Guest Policy:On, Image ID:Off, Family ID:Off, Measurement:Off, SVN:Off, TCB Version:On) 135 | The --guest_svn specifies the guest SVN to mix into the key. Must not exceed the guest SVN provided at launch in the ID block. 136 | The --tcb_version specified the TCB version to mix into the derived key. Must not exceed CommittedTcb. 137 | 138 | 139 | options: 140 | -h, --help show a help message 141 | -g, --guest_field_select Specify which Guest Field Select bits to enable. 142 | -s, --guest_svn Specify the guest SVN to mix into the key. 143 | -t, --tcb_version Specify the TCB version to mix into the derived key. 144 | -v, --vmpl Specify VMPL level the Guest is running on. Defaults to 1. 145 | 146 | *snpguest generate measurement*:: 147 | usage: snpguest generate measurement [-v, --vcpus] [--vcpu-type] [--vcpu-sig] [--vcpu-family] [--vcpu-model] [--vcpu-stepping] [-t, --vmm-type] [-o ,--ovmf] [-k, --kernel] 148 | [-i, --initrd] [-a, --append] [-g, --guest-features] [--ovmf-hash] [-f, --output-format] [-m, --measurement-file] 149 | 150 | Calculates a secure guest expected launch digest measurement. 151 | Every parameter passed in is used to calculate this measurement, but the user does not need to provide every parameter. 152 | The only mandatory parameters are the [-o, --ovmf] parameter which is a path to the ovmf file used to launch the secure guest, and provide the guest vcpu type. 153 | There are 3 ways to provide the vcpu type, and the 3 of them are mutually exclusive (will get an error if the user tries to use more than one method): 154 | - [--vcpu-type] A string with the vcpu-type used to launch the secure guest 155 | - [--vcpu-sig] The signature of the vcpu-type used to launch the secure guest 156 | - [--vcpu-family] [--vcpu-model] [--vcpu-stepping] The family, model and stepping of the vcpu used to launch the secure guest. 157 | Family, model and stepping have to be used together, if they're not all provided together an error will be raised. 158 | If the user provides the [-k, --kernel] parameter to calculate the measurement, they also need to provide [-i, --initrd] and [-a, --append]. 159 | There were kernel features added that affect the result of the measurement if those are enabled. With the [-g, --guest-features] parameter the user can provide which of this features are enabled in their kernel. 160 | The [-g, --guest-features] can be a hex or decimal number that cover the features enabled. 161 | For information on the guest-features bitfield checkout: https://github.com/virtee/sev/blob/a3c91d7b6e742c1b5685a7e0c1e5464819527b06/src/measurement/vmsa.rs#L139 162 | A user can use a pre-calculated ovmf-hash using [--ovmf-hash], but the ovmf file still has to be provided. 163 | The calculated measurement will be printed in the console, if the user wishes to store the measurement value they can provide a file path with [-m, --measurement-file] and the measurement will get written there. 164 | If the [--quiet] flag is used, nothing will be printed out. 165 | 166 | options: 167 | -h, --help Show a help message 168 | -v, --vcpus Number of guest vcpus [default: 1] 169 | --vcpu-type Type of guest vcpu (EPYC, EPYC-v1, EPYC-v2, EPYC-IBPB, EPYC-v3, EPYC-v4, EPYC-Rome, EPYC-Rome-v1, EPYC-Rome-v2, EPYC-Rome-v3, EPYC-Milan, EPYC- Milan-v1, EPYC-Milan-v2, EPYC-Genoa, EPYC-Genoa-v1) 170 | --vcpu-sig Guest vcpu signature value 171 | --vcpu-family Guest vcpu family 172 | --vcpu-model Guest vcpu model 173 | --vcpu-stepping Guest vcpu stepping 174 | -t, --vmm-type Type of guest vmm (QEMU, ec2, KRUN) [default: QEMU] 175 | -o, --ovmf OVMF file to calculate measurement from 176 | -k, --kernel Kernel file to calculate measurement from 177 | -i, --initrd Initrd file to calculate measurement from 178 | -a, --append Kernel command line in string format to calculate measurement from 179 | -g, --guest-features Hex representation of the guest kernel features expected to be included [default: 0x1] 180 | --ovmf-hash Precalculated hash of the OVMF binary 181 | -f, --output-format Output format (base64, hex). [default: hex] 182 | -m, --measurement-file Optional file path where the measurement value can be stored in 183 | 184 | *snpguest generate ovmf-hash*:: 185 | usage: snpguest generate ovmf-hash [-o, --ovmf] [-f, --output--format] [--hash-file] 186 | 187 | Calculates the hash of an ovmf file. 188 | User only needs to provide the file they want the hash for. 189 | The hash will be printed in the console, if the user wishes to store the hash value they can provide a file path with [--hash-file] and the hash will get written there. 190 | If the [--quiet] flag is used, nothing will be printed out. 191 | 192 | options: 193 | -h, --help Show a help message 194 | -o, --ovmf OVMF file to generate hash for 195 | -f, --output-format Output format (base64, hex). [default: hex] 196 | --hash-file Optional file path where the hash value can be stored in 197 | 198 | *snpguest generate id-block*:: 199 | usage: snpguest generate id-block $ID-BLOCK-KEY $AUTH-KEY $LAUNCH-DIGEST [-f, --family-id] [-m, --image-id] [-v, --version] [-s, --svn] [-p, --policy] 200 | [-i, --id-file] [-a, --auth-file] 201 | 202 | Calculates an id-block and auth-block for a secure guest. 203 | User needs to provide a path to two different EC p384 keys in pem or der format. One will be for the id-block the other for the auth-block. 204 | The user will also need to provide the launch digest (in either hex or base64 format) of the secure guest. 205 | The user can generate the launch digest using the "generate measurement" command. 206 | The user can provide optional id's for further verification using the [-f, --family-id] and [-m, image-id] paramerters. 207 | The user can provide the security version number of the guest using [-s, --svn]. 208 | The user can specify the launch policy of the guest using the [-p, --policy] parameter.. 209 | The policy can be provided in either hex or decimal format. It will default to 0x30000. 210 | For more information on the guest-policy, you can refer to: https://www.amd.com/content/dam/amd/en/documents/epyc-technical-docs/specifications/56860.pdf#page=27 211 | The blocks will be printed in the console, if the user wishes to store the blocks values they can provide a file path with [-i, --id-file] for the id-block 212 | and [-a, --auth-file] for the auth-block. 213 | If the [--quiet] flag is used, nothing wibe printed out. 214 | 215 | options: 216 | -h, --help Show a help message 217 | -f, --family-id Family ID of the guest provided by the guest owner. Has to be 16 characters 218 | -m, --image-id Image ID of the guest provided by the guest owner. Has to be 16 characters 219 | -v, --version Id-Block version. Currently only version 1 is available 220 | -s, --svn SVN (SECURITY VERSION NUMBER) of the guest 221 | -p, --policy Launch policy of the guest. Can provide in decimal or hex format 222 | -i, --id-file Optional file where the Id-Block value can be stored in 223 | -a, --auth-file Optional file where the Auth-Block value can be stored in 224 | 225 | *snpguest generate key-digest*:: 226 | usage: snpguest generate key-digest $KEY-PATH [-d, --key-digest-file] 227 | 228 | Generates an SEV key digest for a provided EC p384 key. 229 | User needs to provide a path to the key 230 | The key has to be a EC p384 key in either pem or der format. 231 | The digest will be printed in the console, if the user wishes to store the digest value they can provide a file path with [-d, --key-digest-file] 232 | If the [--quiet] flag is used, nothing wibe printed out. 233 | 234 | options: 235 | -h, --help Show a help message 236 | -d, --key-digest-file File to store the key digest in 237 | 238 | *snpguest guest display report*:: 239 | usage: snpguest display report $ATT_REPORT_PATH 240 | 241 | Prints the attestation report contents into terminal. 242 | The user has to provide a path to a stored attestation report to display. 243 | 244 | options: 245 | -h, --help show a help message 246 | 247 | *snpguest guest display key*:: 248 | usage: snpguest display key $KEY_PATH 249 | 250 | Prints the derived key contents in hex format into terminal. 251 | The user has to provide the path of a stored derived key to display. 252 | 253 | options: 254 | -h, --help show a help message 255 | 256 | * 257 | 258 | REPORTING BUGS 259 | -------------- 260 | 261 | Please report all bugs to -------------------------------------------------------------------------------- /src/certs.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | // This file contains code related to managing certificates. It defines a structure for managing certificate paths (`CertPaths`) and functions for obtaining extended certificates from the AMD Secure Processor. 3 | 4 | use crate::fetch::Endorsement; 5 | 6 | use super::*; 7 | 8 | use std::{ 9 | fs, 10 | io::{ErrorKind, Read, Write}, 11 | path::{Path, PathBuf}, 12 | str::FromStr, 13 | }; 14 | 15 | use sev::{ 16 | certs::snp::{ca, Certificate, Chain}, 17 | firmware::{guest::Firmware, host::CertType}, 18 | }; 19 | 20 | pub struct CertPaths { 21 | pub ark_path: PathBuf, 22 | pub ask_path: PathBuf, 23 | pub vek_path: PathBuf, 24 | } 25 | 26 | #[derive(ValueEnum, Clone, Copy)] 27 | pub enum CertFormat { 28 | /// Certificates are encoded in PEM format. 29 | Pem, 30 | 31 | /// Certificates are encoded in DER format. 32 | Der, 33 | } 34 | 35 | impl std::fmt::Display for CertFormat { 36 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 37 | match self { 38 | CertFormat::Pem => write!(f, "pem"), 39 | CertFormat::Der => write!(f, "der"), 40 | } 41 | } 42 | } 43 | 44 | impl FromStr for CertFormat { 45 | type Err = anyhow::Error; 46 | fn from_str(input: &str) -> Result { 47 | match input.to_lowercase().as_str() { 48 | "pem" => Ok(CertFormat::Pem), 49 | "der" => Ok(CertFormat::Der), 50 | _ => Err(anyhow::anyhow!("Invalid Cert Format!")), 51 | } 52 | } 53 | } 54 | 55 | // Function that will convert a cert path into a snp Certificate 56 | pub fn convert_path_to_cert( 57 | cert_path: &PathBuf, 58 | cert_type: &str, 59 | ) -> Result { 60 | let mut buf = vec![]; 61 | 62 | let mut current_file = if cert_path.as_os_str().is_empty() { 63 | match fs::File::open(format!("./certs/{cert_type}.pem")) { 64 | Ok(file) => file, 65 | Err(err) => match err.kind() { 66 | ErrorKind::NotFound => match fs::File::open(format!("./certs/{cert_type}.der")) { 67 | Ok(file) => file, 68 | Err(e) => { 69 | return Err(anyhow::anyhow!("Problem opening {cert_type} file {:?}", e)) 70 | } 71 | }, 72 | other_error => { 73 | return Err(anyhow::anyhow!( 74 | "Problem opening {cert_type} file {:?}", 75 | other_error 76 | )); 77 | } 78 | }, 79 | } 80 | } else { 81 | fs::File::open(cert_path).context(format!("Could not open provided {cert_type} file"))? 82 | }; 83 | 84 | current_file 85 | .read_to_end(&mut buf) 86 | .context(format!("Could not read contents of {cert_type} file"))?; 87 | 88 | Ok(Certificate::from_bytes(&buf)?) 89 | } 90 | 91 | // Tryfrom function that takes in 3 certificate paths returns a snp Certificate Chain 92 | impl TryFrom for Chain { 93 | type Error = anyhow::Error; 94 | fn try_from(content: CertPaths) -> Result { 95 | let ark_cert: Certificate = convert_path_to_cert(&content.ark_path, "ark")?; 96 | let ask_cert: Certificate = convert_path_to_cert(&content.ask_path, "ask")?; 97 | let vek_cert: Certificate = if content 98 | .vek_path 99 | .to_string_lossy() 100 | .to_lowercase() 101 | .contains("vlek") 102 | { 103 | convert_path_to_cert(&content.vek_path, "vlek")? 104 | } else { 105 | convert_path_to_cert(&content.vek_path, "vcek")? 106 | }; 107 | 108 | let ca_chain = ca::Chain { 109 | ark: ark_cert, 110 | ask: ask_cert, 111 | }; 112 | 113 | Ok(Chain { 114 | ca: ca_chain, 115 | vek: vek_cert, 116 | }) 117 | } 118 | } 119 | 120 | // Function used to write provided cert into desired directory. 121 | pub fn write_cert( 122 | path: &Path, 123 | cert_type: &CertType, 124 | data: &[u8], 125 | encoding: CertFormat, 126 | endorser: &Endorsement, 127 | ) -> Result<()> { 128 | // Get cert type into str 129 | let cert: Certificate = Certificate::from_bytes(data)?; 130 | 131 | let cert_str: String = match (cert_type, endorser) { 132 | (CertType::ASK, Endorsement::Vlek) => "asvk".to_string(), 133 | (_, _) => match cert_type { 134 | CertType::Empty => "empty".to_string(), 135 | CertType::ARK => "ark".to_string(), 136 | CertType::ASK => "ask".to_string(), 137 | CertType::VCEK => "vcek".to_string(), 138 | CertType::VLEK => "vlek".to_string(), 139 | CertType::CRL => "crl".to_string(), 140 | CertType::OTHER(uuid) => format!("other-{uuid}"), 141 | }, 142 | }; 143 | 144 | let bytes: Vec = match encoding { 145 | CertFormat::Pem => cert.to_pem()?, 146 | CertFormat::Der => cert.to_der()?, 147 | }; 148 | 149 | let cert_path: PathBuf = path.join(format!("{cert_str}.{encoding}")); 150 | 151 | // Write cert into directory 152 | let mut file = if cert_path.exists() { 153 | std::fs::OpenOptions::new() 154 | .write(true) 155 | .truncate(true) 156 | .open(cert_path) 157 | .context(format!("Unable to overwrite {cert_str} cert contents"))? 158 | } else { 159 | fs::File::create(cert_path).context(format!("Unable to create {cert_str} certificate"))? 160 | }; 161 | 162 | file.write(&bytes) 163 | .context(format!("unable to write data to file {:?}", file))?; 164 | 165 | Ok(()) 166 | } 167 | 168 | #[derive(Parser)] 169 | pub struct CertificatesArgs { 170 | /// Specify encoding to use for certificates. 171 | #[arg(value_name = "encoding", required = true, ignore_case = true)] 172 | pub encoding: CertFormat, 173 | 174 | /// Directory to store certificates in. Required if requesting an extended-report. 175 | #[arg(value_name = "certs-dir", required = true)] 176 | pub certs_dir: PathBuf, 177 | } 178 | 179 | pub fn get_ext_certs(args: CertificatesArgs) -> Result<()> { 180 | let mut sev_fw: Firmware = Firmware::open().context("failed to open SEV firmware device.")?; 181 | 182 | // Generate random request data 183 | let request_data: [u8; 64] = report::create_random_request(); 184 | 185 | // Request extended attestation report 186 | let (_, mut certificates) = sev_fw 187 | .get_ext_report(None, Some(request_data), None) 188 | .context("Failed to get extended report.")?; 189 | 190 | // Create certificate directory if missing 191 | if !args.certs_dir.exists() { 192 | fs::create_dir(&args.certs_dir).context("Could not create certs folder")?; 193 | }; 194 | 195 | // If certificates are present, write certs into directory 196 | if let Some(ref mut certificates) = certificates { 197 | // Unless VLEK is encountered, assume VCEK style endorsement with ASK. 198 | let mut endorsement: Endorsement = Endorsement::Vcek; 199 | 200 | certificates.iter().try_for_each(|cert| { 201 | if cert.cert_type == CertType::VLEK { 202 | endorsement = Endorsement::Vlek; 203 | } 204 | write_cert( 205 | &args.certs_dir, 206 | &cert.cert_type, 207 | &cert.data, 208 | args.encoding, 209 | &endorsement, 210 | ) 211 | })?; 212 | } else { 213 | eprintln!("No certificates were loaded by the host..."); 214 | } 215 | 216 | Ok(()) 217 | } 218 | -------------------------------------------------------------------------------- /src/display.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | // This file contains the subcommands for displaying attestation reports and derived keys. 3 | 4 | use super::*; 5 | use std::path::PathBuf; 6 | 7 | #[derive(Subcommand)] 8 | pub enum DisplayCmd { 9 | /// Display an attestation report in console. 10 | Report(report_display::Args), 11 | 12 | /// Display the derived key in console. 13 | Key(key_display::Args), 14 | } 15 | 16 | pub fn cmd(cmd: DisplayCmd, quiet: bool) -> Result<()> { 17 | match cmd { 18 | DisplayCmd::Report(args) => report_display::display_attestation_report(args, quiet), 19 | DisplayCmd::Key(args) => key_display::display_derived_key(args, quiet), 20 | } 21 | } 22 | mod report_display { 23 | use super::*; 24 | 25 | #[derive(Parser)] 26 | pub struct Args { 27 | /// Path to attestation report to display. 28 | #[arg(value_name = "att-report-path", required = true)] 29 | pub att_report_path: PathBuf, 30 | } 31 | 32 | // Print attestation report in console 33 | pub fn display_attestation_report(args: Args, quiet: bool) -> Result<()> { 34 | let att_report = report::read_report(args.att_report_path) 35 | .context("Could not open attestation report")?; 36 | 37 | if !quiet { 38 | println!("{}", att_report); 39 | }; 40 | 41 | Ok(()) 42 | } 43 | } 44 | 45 | mod key_display { 46 | use super::*; 47 | 48 | #[derive(Parser)] 49 | pub struct Args { 50 | /// Path of key to be displayed. 51 | #[arg(value_name = "key-path", required = true)] 52 | pub key_path: PathBuf, 53 | } 54 | 55 | // Print derived key in console 56 | pub fn display_derived_key(args: Args, quiet: bool) -> Result<()> { 57 | let key_report = key::read_key(args.key_path).context("Could not open key")?; 58 | 59 | if !quiet { 60 | let mut keydata: String = String::new(); 61 | for (i, byte) in key_report.iter().enumerate() { 62 | if (i % 16) == 0 { 63 | keydata.push('\n'); 64 | } 65 | //Displaying key in Hex format 66 | keydata.push_str(&format!("{byte:02x} ")); 67 | } 68 | keydata.push('\n'); 69 | println!("{}", keydata); 70 | }; 71 | 72 | Ok(()) 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/fetch.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | // This file contains subcommands for fetching various types of certificates from the AMD Secure Processor. 3 | 4 | use super::*; 5 | 6 | use core::fmt; 7 | 8 | use std::{fs, path::PathBuf, str::FromStr}; 9 | 10 | use reqwest::blocking::{get, Response}; 11 | 12 | use sev::{ 13 | certs::snp::ca::Chain, 14 | firmware::{guest::AttestationReport, host::CertType}, 15 | }; 16 | 17 | use certs::{write_cert, CertFormat}; 18 | 19 | #[derive(Subcommand)] 20 | pub enum FetchCmd { 21 | /// Fetch the certificate authority (ARK & ASK) from the KDS. 22 | CA(cert_authority::Args), 23 | 24 | /// Fetch the VCEK from the KDS. 25 | Vcek(vcek::Args), 26 | } 27 | 28 | #[derive(ValueEnum, Debug, Clone, PartialEq, Eq)] 29 | pub enum Endorsement { 30 | /// Versioned Chip Endorsement Key 31 | Vcek, 32 | 33 | /// Versioned Loaded Endorsement Key 34 | Vlek, 35 | } 36 | 37 | impl fmt::Display for Endorsement { 38 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 39 | match self { 40 | Endorsement::Vcek => write!(f, "VCEK"), 41 | Endorsement::Vlek => write!(f, "VLEK"), 42 | } 43 | } 44 | } 45 | 46 | impl FromStr for Endorsement { 47 | type Err = anyhow::Error; 48 | 49 | fn from_str(s: &str) -> std::prelude::v1::Result { 50 | match s.to_lowercase().as_str() { 51 | "vcek" => Ok(Self::Vcek), 52 | "vlek" => Ok(Self::Vlek), 53 | _ => Err(anyhow::anyhow!("Endorsement type not found!")), 54 | } 55 | } 56 | } 57 | #[derive(ValueEnum, Debug, Clone, PartialEq, Eq)] 58 | pub enum ProcType { 59 | /// 3rd Gen AMD EPYC Processor (Standard) 60 | Milan, 61 | 62 | /// 4th Gen AMD EPYC Processor (Standard) 63 | Genoa, 64 | 65 | /// 4th Gen AMD EPYC Processor (Performance) 66 | Bergamo, 67 | 68 | /// 4th Gen AMD EPYC Processor (Edge) 69 | Siena, 70 | 71 | /// 5th Gen AMD EPYC Processor (Standard) 72 | Turin, 73 | } 74 | 75 | impl ProcType { 76 | fn to_kds_url(&self) -> String { 77 | match self { 78 | ProcType::Genoa | ProcType::Siena | ProcType::Bergamo => &ProcType::Genoa, 79 | _ => self, 80 | } 81 | .to_string() 82 | } 83 | } 84 | 85 | impl FromStr for ProcType { 86 | type Err = anyhow::Error; 87 | fn from_str(input: &str) -> Result { 88 | match input.to_lowercase().as_str() { 89 | "milan" => Ok(ProcType::Milan), 90 | "genoa" => Ok(ProcType::Genoa), 91 | "bergamo" => Ok(ProcType::Bergamo), 92 | "siena" => Ok(ProcType::Siena), 93 | "turin" => Ok(ProcType::Turin), 94 | _ => Err(anyhow::anyhow!("Processor type not found!")), 95 | } 96 | } 97 | } 98 | 99 | impl fmt::Display for ProcType { 100 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 101 | match self { 102 | ProcType::Milan => write!(f, "Milan"), 103 | ProcType::Genoa => write!(f, "Genoa"), 104 | ProcType::Bergamo => write!(f, "Bergamo"), 105 | ProcType::Siena => write!(f, "Siena"), 106 | ProcType::Turin => write!(f, "Turin"), 107 | } 108 | } 109 | } 110 | 111 | pub fn get_processor_model(att_report: AttestationReport) -> Result { 112 | if att_report.version < 3 { 113 | if [0u8; 64] == *att_report.chip_id { 114 | return Err(anyhow::anyhow!( 115 | "Attestation report version is lower than 3 and Chip ID is all 0s. Make sure MASK_CHIP_ID is set to 0 or update firmware." 116 | )); 117 | } else { 118 | let chip_id = *att_report.chip_id; 119 | if chip_id[8..64] == [0; 56] { 120 | return Ok(ProcType::Turin); 121 | } else { 122 | return Err(anyhow::anyhow!( 123 | "Attestation report could be either Milan or Genoa. Update firmware to get a new version of the report." 124 | )); 125 | } 126 | } 127 | } 128 | 129 | let cpu_fam = att_report 130 | .cpuid_fam_id 131 | .ok_or_else(|| anyhow::anyhow!("Attestation report version 3+ is missing CPU family ID"))?; 132 | 133 | let cpu_mod = att_report 134 | .cpuid_mod_id 135 | .ok_or_else(|| anyhow::anyhow!("Attestation report version 3+ is missing CPU model ID"))?; 136 | 137 | match cpu_fam { 138 | 0x19 => match cpu_mod { 139 | 0x0..=0xF => Ok(ProcType::Milan), 140 | 0x10..=0x1F | 0xA0..0xAF => Ok(ProcType::Genoa), 141 | _ => Err(anyhow::anyhow!("Processor model not supported")), 142 | }, 143 | 0x1A => match cpu_mod { 144 | 0x0..=0x11 => Ok(ProcType::Turin), 145 | _ => Err(anyhow::anyhow!("Processor model not supported")), 146 | }, 147 | _ => Err(anyhow::anyhow!("Processor family not supported")), 148 | } 149 | } 150 | 151 | pub fn cmd(cmd: FetchCmd) -> Result<()> { 152 | match cmd { 153 | FetchCmd::CA(args) => cert_authority::fetch_ca(args), 154 | FetchCmd::Vcek(args) => vcek::fetch_vcek(args), 155 | } 156 | } 157 | 158 | mod cert_authority { 159 | use super::*; 160 | use reqwest::StatusCode; 161 | 162 | #[derive(Parser)] 163 | pub struct Args { 164 | /// Specify encoding to use for certificates. 165 | #[arg(value_name = "encoding", required = true, ignore_case = true)] 166 | pub encoding: CertFormat, 167 | 168 | /// Directory to store the certificates in. 169 | #[arg(value_name = "certs-dir", required = true)] 170 | pub certs_dir: PathBuf, 171 | 172 | /// Specify the processor model for the desired certificate chain. 173 | #[arg( 174 | value_name = "processor-model", 175 | required_unless_present = "att_report", 176 | conflicts_with = "att_report", 177 | ignore_case = true 178 | )] 179 | pub processor_model: Option, 180 | 181 | /// Attestation Report to get processor model from (V3 of report needed). 182 | #[arg( 183 | short = 'r', 184 | long = "report", 185 | value_name = "att-report", 186 | conflicts_with = "processor_model", 187 | ignore_case = true 188 | )] 189 | pub att_report: Option, 190 | 191 | /// Specify which endorsement certificate chain to pull, either VCEK or VLEK. 192 | #[arg(short, long, value_name = "endorser", default_value_t = Endorsement::Vcek, ignore_case = true)] 193 | pub endorser: Endorsement, 194 | } 195 | 196 | // Function to build kds request for ca chain and return a vector with the 2 certs (ASK & ARK) 197 | pub fn request_ca_kds( 198 | processor_model: ProcType, 199 | endorser: &Endorsement, 200 | ) -> Result { 201 | const KDS_CERT_SITE: &str = "https://kdsintf.amd.com"; 202 | const KDS_CERT_CHAIN: &str = "cert_chain"; 203 | 204 | // Should make -> https://kdsintf.amd.com/vcek/v1/{SEV_PROD_NAME}/cert_chain 205 | let url: String = format!( 206 | "{KDS_CERT_SITE}/{}/v1/{}/{KDS_CERT_CHAIN}", 207 | endorser.to_string().to_lowercase(), 208 | processor_model.to_kds_url() 209 | ); 210 | 211 | let rsp: Response = get(url).context("Unable to send request for certs to URL")?; 212 | 213 | match rsp.status() { 214 | StatusCode::OK => { 215 | // Parse the request 216 | let body = rsp 217 | .bytes() 218 | .context("Unable to parse AMD certificate chain")? 219 | .to_vec(); 220 | 221 | let certificates = Chain::from_pem_bytes(&body)?; 222 | 223 | Ok(certificates) 224 | } 225 | status => Err(anyhow::anyhow!("Unable to fetch certificate: {:?}", status)), 226 | } 227 | } 228 | 229 | // Fetch the ca from the kds and write it into the certs directory 230 | pub fn fetch_ca(args: Args) -> Result<()> { 231 | let proc_model = if let Some(processor_model) = args.processor_model { 232 | processor_model 233 | } else if let Some(att_report) = args.att_report { 234 | let report = 235 | report::read_report(att_report).context("Could not open attestation report")?; 236 | get_processor_model(report)? 237 | } else { 238 | return Err(anyhow::anyhow!("Attestation report is missing or invalid, or the user did not specify a processor model")); 239 | }; 240 | // Get certs from kds 241 | let certificates = request_ca_kds(proc_model, &args.endorser)?; 242 | 243 | // Create certs directory if missing 244 | if !args.certs_dir.exists() { 245 | fs::create_dir(&args.certs_dir).context("Could not create certs folder")?; 246 | } 247 | 248 | let ark_cert = certificates.ark; 249 | let ask_cert = certificates.ask; 250 | 251 | write_cert( 252 | &args.certs_dir, 253 | &CertType::ARK, 254 | &ark_cert.to_pem()?, 255 | args.encoding, 256 | &args.endorser, 257 | )?; 258 | write_cert( 259 | &args.certs_dir, 260 | &CertType::ASK, 261 | &ask_cert.to_pem()?, 262 | args.encoding, 263 | &args.endorser, 264 | )?; 265 | 266 | Ok(()) 267 | } 268 | } 269 | 270 | mod vcek { 271 | use asn1_rs::nom::AsBytes; 272 | use reqwest::StatusCode; 273 | 274 | use super::*; 275 | 276 | #[derive(Parser)] 277 | pub struct Args { 278 | /// Specify encoding to use for certificates. 279 | #[arg(value_name = "encoding", required = true, ignore_case = true)] 280 | pub encoding: CertFormat, 281 | 282 | /// Directory to store the certificates in. 283 | #[arg(value_name = "certs-dir", required = true)] 284 | pub certs_dir: PathBuf, 285 | 286 | /// Path to attestation report to use to request VCEK. 287 | #[arg(value_name = "att-report-path", required = true)] 288 | pub att_report: PathBuf, 289 | 290 | /// Specify the processor model for the desired vcek. 291 | #[arg(short, long, value_name = "processor-model", ignore_case = true)] 292 | pub processor_model: Option, 293 | } 294 | 295 | // Function to request vcek from KDS. Return vcek in der format. 296 | pub fn request_vcek_kds( 297 | processor_model: ProcType, 298 | att_report_path: PathBuf, 299 | ) -> Result, anyhow::Error> { 300 | // KDS URL parameters 301 | const KDS_CERT_SITE: &str = "https://kdsintf.amd.com"; 302 | const KDS_VCEK: &str = "/vcek/v1"; 303 | 304 | // Grab attestation report if path provided, request report if no path is provided 305 | let att_report = if !att_report_path.exists() { 306 | return Err(anyhow::anyhow!("No attestation report in provided path.")); 307 | } else { 308 | report::read_report(att_report_path).context("Could not open attestation report")? 309 | }; 310 | 311 | // Get hardware id 312 | let hw_id: String = if att_report.chip_id.as_bytes() != [0; 64] { 313 | match processor_model { 314 | ProcType::Turin => { 315 | let shorter_bytes: &[u8] = &att_report.chip_id[0..8]; 316 | hex::encode(shorter_bytes) 317 | } 318 | _ => hex::encode(att_report.chip_id), 319 | } 320 | } else { 321 | return Err(anyhow::anyhow!( 322 | "Hardware ID is 0s on attestation report. Confirm that MASK_CHIP_ID is set to 0." 323 | )); 324 | }; 325 | 326 | // Request VCEK from KDS 327 | let vcek_url: String = match processor_model { 328 | ProcType::Turin => { 329 | let fmc = if let Some(fmc) = att_report.reported_tcb.fmc { 330 | fmc 331 | } else { 332 | return Err(anyhow::anyhow!("A Turin processor must have a fmc value")); 333 | }; 334 | format!( 335 | "{KDS_CERT_SITE}{KDS_VCEK}/{}/\ 336 | {hw_id}?fmcSPL={:02}&blSPL={:02}&teeSPL={:02}&snpSPL={:02}&ucodeSPL={:02}", 337 | processor_model.to_kds_url(), 338 | fmc, 339 | att_report.reported_tcb.bootloader, 340 | att_report.reported_tcb.tee, 341 | att_report.reported_tcb.snp, 342 | att_report.reported_tcb.microcode 343 | ) 344 | } 345 | _ => { 346 | format!( 347 | "{KDS_CERT_SITE}{KDS_VCEK}/{}/\ 348 | {hw_id}?blSPL={:02}&teeSPL={:02}&snpSPL={:02}&ucodeSPL={:02}", 349 | processor_model.to_kds_url(), 350 | att_report.reported_tcb.bootloader, 351 | att_report.reported_tcb.tee, 352 | att_report.reported_tcb.snp, 353 | att_report.reported_tcb.microcode 354 | ) 355 | } 356 | }; 357 | 358 | // VCEK in DER format 359 | let vcek_rsp: Response = get(vcek_url).context("Unable to send request for VCEK")?; 360 | 361 | match vcek_rsp.status() { 362 | StatusCode::OK => { 363 | let vcek_rsp_bytes: Vec = 364 | vcek_rsp.bytes().context("Unable to parse VCEK")?.to_vec(); 365 | Ok(vcek_rsp_bytes) 366 | } 367 | status => Err(anyhow::anyhow!("Unable to fetch VCEK from URL: {status:?}")), 368 | } 369 | } 370 | 371 | // Function to request vcek from kds and write it into file 372 | pub fn fetch_vcek(args: Args) -> Result<()> { 373 | let proc_model = if let Some(proc_model) = args.processor_model { 374 | proc_model 375 | } else { 376 | let att_report = report::read_report(args.att_report.clone()) 377 | .context("Could not open attestation report")?; 378 | get_processor_model(att_report)? 379 | }; 380 | 381 | // Request vcek 382 | let vcek = request_vcek_kds(proc_model, args.att_report)?; 383 | 384 | if !args.certs_dir.exists() { 385 | fs::create_dir(&args.certs_dir).context("Could not create certs folder")?; 386 | } 387 | 388 | write_cert( 389 | &args.certs_dir, 390 | &CertType::VCEK, 391 | &vcek, 392 | args.encoding, 393 | &Endorsement::Vcek, 394 | )?; 395 | 396 | Ok(()) 397 | } 398 | } 399 | #[cfg(test)] 400 | mod tests { 401 | use super::*; 402 | use sev::firmware::guest::KeyInfo; 403 | 404 | #[test] 405 | fn test_kds_prod_name_milan_base() { 406 | let milan_proc: ProcType = ProcType::Milan; 407 | assert_eq!(milan_proc.to_kds_url(), ProcType::Milan.to_string()); 408 | } 409 | 410 | #[test] 411 | fn test_kds_prod_name_genoa_base() { 412 | assert_eq!(ProcType::Genoa.to_kds_url(), ProcType::Genoa.to_string()); 413 | assert_eq!(ProcType::Siena.to_kds_url(), ProcType::Genoa.to_string()); 414 | assert_eq!(ProcType::Bergamo.to_kds_url(), ProcType::Genoa.to_string()); 415 | } 416 | 417 | #[test] 418 | fn test_get_processor_model_milan() { 419 | let att_report = AttestationReport { 420 | version: 3, 421 | cpuid_fam_id: Some(0x19), 422 | cpuid_mod_id: Some(0x0), 423 | ..Default::default() 424 | }; 425 | let proc_model = get_processor_model(att_report).unwrap(); 426 | assert_eq!(proc_model, ProcType::Milan); 427 | } 428 | 429 | #[test] 430 | fn test_get_processor_model_genoa() { 431 | let att_report = AttestationReport { 432 | version: 3, 433 | cpuid_fam_id: Some(0x19), 434 | cpuid_mod_id: Some(0x10), 435 | ..Default::default() 436 | }; 437 | let proc_model = get_processor_model(att_report).unwrap(); 438 | assert_eq!(proc_model, ProcType::Genoa); 439 | } 440 | 441 | #[test] 442 | fn test_get_processor_model_turin() { 443 | let att_report = AttestationReport { 444 | version: 3, 445 | cpuid_fam_id: Some(0x1A), 446 | cpuid_mod_id: Some(0x0), 447 | ..Default::default() 448 | }; 449 | let proc_model = get_processor_model(att_report).unwrap(); 450 | assert_eq!(proc_model, ProcType::Turin); 451 | } 452 | 453 | #[test] 454 | fn test_get_processor_model_unsupported_family() { 455 | let att_report = AttestationReport { 456 | version: 3, 457 | cpuid_fam_id: Some(0x1B), 458 | cpuid_mod_id: Some(0x0), 459 | ..Default::default() 460 | }; 461 | let result = get_processor_model(att_report); 462 | assert!(result.is_err()); 463 | } 464 | 465 | #[test] 466 | fn test_get_processor_model_unsupported_model() { 467 | let att_report = AttestationReport { 468 | version: 3, 469 | cpuid_fam_id: Some(0x19), 470 | cpuid_mod_id: Some(0x20), 471 | ..Default::default() 472 | }; 473 | let result = get_processor_model(att_report); 474 | assert!(result.is_err()); 475 | } 476 | 477 | #[test] 478 | fn test_get_processor_model_version_too_low() { 479 | let att_report = AttestationReport { 480 | version: 2, 481 | chip_id: [1; 64].try_into().unwrap(), 482 | ..Default::default() 483 | }; 484 | let result = get_processor_model(att_report); 485 | assert!(result.is_err()); 486 | } 487 | 488 | #[test] 489 | fn test_get_processor_model_mask_chip_key_set() { 490 | let key_info = KeyInfo(0b10); 491 | let att_report = AttestationReport { 492 | version: 2, 493 | key_info, 494 | ..Default::default() 495 | }; 496 | let result = get_processor_model(att_report); 497 | assert!(result.is_err()); 498 | } 499 | } 500 | -------------------------------------------------------------------------------- /src/hyperv/mod.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | // This file contains code related to Hyper-V integration (Hypervisor). It provides a flag (`hyperv::present`) indicating whether the SNP Guest is running within a Hyper-V guest environment. 3 | 4 | use super::*; 5 | 6 | use std::arch::x86_64::__cpuid; 7 | use std::mem::size_of; 8 | 9 | const CPUID_GET_HIGHEST_FUNCTION: u32 = 0x80000000; 10 | const CPUID_PROCESSOR_INFO_AND_FEATURE_BITS: u32 = 0x1; 11 | 12 | const CPUID_FEATURE_HYPERVISOR: u32 = 1 << 31; 13 | 14 | const CPUID_HYPERV_SIG: &str = "Microsoft Hv"; 15 | const CPUID_HYPERV_VENDOR_AND_MAX_FUNCTIONS: u32 = 0x40000000; 16 | const CPUID_HYPERV_FEATURES: u32 = 0x40000003; 17 | const CPUID_HYPERV_MIN: u32 = 0x40000005; 18 | const CPUID_HYPERV_MAX: u32 = 0x4000ffff; 19 | const CPUID_HYPERV_ISOLATION: u32 = 1 << 22; 20 | const CPUID_HYPERV_CPU_MANAGEMENT: u32 = 1 << 12; 21 | const CPUID_HYPERV_ISOLATION_CONFIG: u32 = 0x4000000C; 22 | const CPUID_HYPERV_ISOLATION_TYPE_MASK: u32 = 0xf; 23 | const CPUID_HYPERV_ISOLATION_TYPE_SNP: u32 = 2; 24 | 25 | const RSV1_SIZE: usize = size_of::() * 8; 26 | const REPORT_SIZE: usize = 1184; 27 | const RSV2_SIZE: usize = size_of::() * 5; 28 | const TOTAL_SIZE: usize = RSV1_SIZE + REPORT_SIZE + RSV2_SIZE; 29 | const REPORT_RANGE: std::ops::Range = RSV1_SIZE..(RSV1_SIZE + REPORT_SIZE); 30 | 31 | pub fn present() -> bool { 32 | let mut cpuid = unsafe { __cpuid(CPUID_PROCESSOR_INFO_AND_FEATURE_BITS) }; 33 | if (cpuid.ecx & CPUID_FEATURE_HYPERVISOR) == 0 { 34 | return false; 35 | } 36 | 37 | cpuid = unsafe { __cpuid(CPUID_GET_HIGHEST_FUNCTION) }; 38 | if cpuid.eax < CPUID_HYPERV_VENDOR_AND_MAX_FUNCTIONS { 39 | return false; 40 | } 41 | 42 | cpuid = unsafe { __cpuid(CPUID_HYPERV_VENDOR_AND_MAX_FUNCTIONS) }; 43 | if cpuid.eax < CPUID_HYPERV_MIN || cpuid.eax > CPUID_HYPERV_MAX { 44 | return false; 45 | } 46 | 47 | let mut sig: Vec = vec![]; 48 | sig.append(&mut cpuid.ebx.to_le_bytes().to_vec()); 49 | sig.append(&mut cpuid.ecx.to_le_bytes().to_vec()); 50 | sig.append(&mut cpuid.edx.to_le_bytes().to_vec()); 51 | 52 | if sig != CPUID_HYPERV_SIG.as_bytes() { 53 | return false; 54 | } 55 | 56 | cpuid = unsafe { __cpuid(CPUID_HYPERV_FEATURES) }; 57 | 58 | let isolated: bool = (cpuid.ebx & CPUID_HYPERV_ISOLATION) != 0; 59 | let managed: bool = (cpuid.ebx & CPUID_HYPERV_CPU_MANAGEMENT) != 0; 60 | 61 | if !isolated || managed { 62 | return false; 63 | } 64 | 65 | cpuid = unsafe { __cpuid(CPUID_HYPERV_ISOLATION_CONFIG) }; 66 | let mask = cpuid.ebx & CPUID_HYPERV_ISOLATION_TYPE_MASK; 67 | let snp = CPUID_HYPERV_ISOLATION_TYPE_SNP; 68 | 69 | if mask != snp { 70 | return false; 71 | } 72 | 73 | true 74 | } 75 | 76 | pub mod report { 77 | use super::*; 78 | 79 | use anyhow::{anyhow, Context}; 80 | use serde::{Deserialize, Serialize}; 81 | use sev::firmware::guest::AttestationReport; 82 | use tss_esapi::{ 83 | abstraction::nv, 84 | handles::NvIndexTpmHandle, 85 | interface_types::{resource_handles::NvAuth, session_handles::AuthSession}, 86 | tcti_ldr::{DeviceConfig, TctiNameConf}, 87 | }; 88 | 89 | const VTPM_HCL_REPORT_NV_INDEX: u32 = 0x01400001; 90 | 91 | #[repr(C)] 92 | #[derive(Deserialize, Serialize, Debug, Clone, Copy)] 93 | struct Hcl { 94 | rsv1: [u32; 8], 95 | report: AttestationReport, 96 | rsv2: [u32; 5], 97 | } 98 | 99 | pub fn get(vmpl: u32) -> Result { 100 | if vmpl > 0 { 101 | return Err(anyhow!("Azure vTPM attestation report requires VMPL 0")); 102 | } 103 | let bytes = tpm2_read().context("unable to read attestation report bytes from vTPM")?; 104 | 105 | hcl_report(&bytes) 106 | } 107 | 108 | fn tpm2_read() -> Result> { 109 | let handle = NvIndexTpmHandle::new(VTPM_HCL_REPORT_NV_INDEX) 110 | .context("unable to initialize TPM handle")?; 111 | let mut ctx = tss_esapi::Context::new(TctiNameConf::Device(DeviceConfig::default()))?; 112 | ctx.set_sessions((Some(AuthSession::Password), None, None)); 113 | 114 | nv::read_full(&mut ctx, NvAuth::Owner, handle) 115 | .context("unable to read non-volatile vTPM data") 116 | } 117 | 118 | fn hcl_report(bytes: &[u8]) -> Result { 119 | if bytes.len() < TOTAL_SIZE { 120 | return Err(anyhow!( 121 | "HCL report size mismatch: expected at least {}, got {}", 122 | TOTAL_SIZE, 123 | bytes.len() 124 | )); 125 | } 126 | 127 | let report_bytes = &bytes[REPORT_RANGE]; 128 | 129 | AttestationReport::from_bytes(report_bytes) 130 | .context("Unable to convert HCL report bytes to AttestationReport") 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/key.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | // This file contains code for fetching derived keys from root keys. It also includes functions for requesting and saving derived keys. 3 | 4 | use super::*; 5 | use sev::firmware::guest::{DerivedKey, Firmware, GuestFieldSelect}; 6 | use std::io::Read; 7 | use std::{fs, path::PathBuf}; 8 | 9 | #[derive(Parser)] 10 | pub struct KeyArgs { 11 | /// This is the path where the derived key will be saved. 12 | #[arg(value_name = "key-path", required = true)] 13 | pub key_path: PathBuf, 14 | 15 | /// This is the root key from which to derive the key. Input either VCEK or VMRK. 16 | #[arg(value_name = "root-key-select", required = true, ignore_case = true)] 17 | pub root_key_select: String, 18 | 19 | /// Specify an integer VMPL level between 0 and 3 that the Guest is running on. 20 | #[arg(short, long, value_name = "vmpl", default_value = "1")] 21 | pub vmpl: Option, 22 | 23 | /// Specify which Guest Field Select bits to enable. It is a 6 digit binary string. For each bit, 0 denotes off and 1 denotes on. 24 | /// The least significant (rightmost) bit is Guest Policy followed by Image ID, Family ID, Measurement, SVN, TCB Version which is the most significant (leftmost) bit. 25 | #[arg(short, long = "guest_field_select", value_name = "######")] 26 | pub gfs: Option, 27 | 28 | /// Specify the guest SVN to mix into the key. Must not exceed the guest SVN provided at launch in the ID block. 29 | #[arg(short = 's', long = "guest_svn")] 30 | pub gsvn: Option, 31 | 32 | /// Specify the TCB version to mix into the derived key. Must not exceed CommittedTcb. 33 | #[arg(short, long = "tcb_version")] 34 | pub tcbv: Option, 35 | } 36 | 37 | pub fn get_derived_key(args: KeyArgs) -> Result<()> { 38 | let root_key_select = match args.root_key_select.as_str() { 39 | "vcek" => false, 40 | "vmrk" => true, 41 | _ => return Err(anyhow::anyhow!("Invalid input. Enter either vcek or vmrk")), 42 | }; 43 | 44 | let vmpl = match args.vmpl { 45 | Some(level) => { 46 | if level <= 3 { 47 | level 48 | } else { 49 | return Err(anyhow::anyhow!("Invalid Virtual Machine Privilege Level.")); 50 | } 51 | } 52 | None => 1, 53 | }; 54 | 55 | let gfs = match args.gfs { 56 | Some(gfs) => { 57 | let value: u64 = u64::from_str_radix(gfs.as_str(), 2).unwrap(); 58 | if value <= 63 { 59 | value 60 | } else { 61 | return Err(anyhow::anyhow!("Invalid Guest Field Select option.")); 62 | } 63 | } 64 | None => 0, 65 | }; 66 | 67 | let gsvn: u32 = args.gsvn.unwrap_or(0); 68 | 69 | let tcbv: u64 = args.tcbv.unwrap_or(0); 70 | 71 | let request = DerivedKey::new(root_key_select, GuestFieldSelect(gfs), vmpl, gsvn, tcbv); 72 | let mut sev_fw = Firmware::open().context("failed to open SEV firmware device.")?; 73 | let derived_key: [u8; 32] = sev_fw 74 | .get_derived_key(None, request) 75 | .context("Failed to request derived key")?; 76 | 77 | // Create derived key path 78 | let key_path: PathBuf = args.key_path; 79 | 80 | // Write derived key into desired file 81 | let mut key_file = if key_path.exists() { 82 | std::fs::OpenOptions::new() 83 | .write(true) 84 | .truncate(true) 85 | .open(key_path) 86 | .context("Unable to overwrite derived key file contents")? 87 | } else { 88 | fs::File::create(key_path).context("Unable to create derived key file contents")? 89 | }; 90 | 91 | bincode::serialize_into(&mut key_file, &derived_key) 92 | .context("Could not serialize derived key into file.")?; 93 | 94 | Ok(()) 95 | } 96 | 97 | pub fn read_key(key_path: PathBuf) -> Result, anyhow::Error> { 98 | let mut key_file = fs::File::open(key_path)?; 99 | let mut key = Vec::new(); 100 | // read the whole file 101 | key_file.read_to_end(&mut key)?; 102 | Ok(key) 103 | } 104 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | // This is the main entry point of the snpguest utility. The CLI includes subcommands for requesting and managing certificates, displaying information, fetching derived keys, and verifying certificates and attestation reports. 3 | 4 | mod certs; 5 | mod display; 6 | mod fetch; 7 | mod key; 8 | mod ok; 9 | mod preattestation; 10 | mod report; 11 | mod verify; 12 | 13 | #[cfg(feature = "hyperv")] 14 | mod hyperv; 15 | 16 | use certs::CertificatesArgs; 17 | use display::DisplayCmd; 18 | use fetch::FetchCmd; 19 | use key::KeyArgs; 20 | use preattestation::PreAttestationCmd; 21 | use report::ReportArgs; 22 | use verify::VerifyCmd; 23 | 24 | use anyhow::{Context, Result}; 25 | use clap::{arg, Parser, Subcommand, ValueEnum}; 26 | 27 | #[derive(Parser)] 28 | #[command(author, version, about, long_about = None)] 29 | struct SnpGuest { 30 | #[command(subcommand)] 31 | pub cmd: SnpGuestCmd, 32 | 33 | /// Don't print anything to the console 34 | #[arg(short, long, default_value_t = false)] 35 | pub quiet: bool, 36 | } 37 | 38 | #[allow(clippy::large_enum_variant)] 39 | /// Utilities for managing the SNP Guest environment 40 | #[derive(Subcommand)] 41 | enum SnpGuestCmd { 42 | /// Report command to request an attestation report. 43 | Report(ReportArgs), 44 | 45 | /// Certificates command to request cached certificates from the AMD PSP. 46 | Certificates(CertificatesArgs), 47 | 48 | /// Fetch command to request certificates. 49 | #[command(subcommand)] 50 | Fetch(FetchCmd), 51 | 52 | /// Verify command to verify certificates and attestation report. 53 | #[command(subcommand)] 54 | Verify(VerifyCmd), 55 | 56 | /// Display command to display files in human readable form. 57 | #[command(subcommand)] 58 | Display(DisplayCmd), 59 | 60 | /// Key command to generate derived key. 61 | Key(KeyArgs), 62 | 63 | /// Probe system for SEV-SNP support. 64 | Ok, 65 | 66 | /// Generate Pre-Attestation components 67 | #[command(subcommand)] 68 | Generate(PreAttestationCmd), 69 | } 70 | 71 | fn main() -> Result<()> { 72 | env_logger::init(); 73 | 74 | let snpguest = SnpGuest::parse(); 75 | 76 | #[cfg(feature = "hyperv")] 77 | let hv = hyperv::present(); 78 | 79 | #[cfg(not(feature = "hyperv"))] 80 | let hv = false; 81 | 82 | let status = match snpguest.cmd { 83 | SnpGuestCmd::Report(args) => report::get_report(args, hv), 84 | SnpGuestCmd::Certificates(args) => certs::get_ext_certs(args), 85 | SnpGuestCmd::Fetch(subcmd) => fetch::cmd(subcmd), 86 | SnpGuestCmd::Verify(subcmd) => verify::cmd(subcmd, snpguest.quiet), 87 | SnpGuestCmd::Display(subcmd) => display::cmd(subcmd, snpguest.quiet), 88 | SnpGuestCmd::Key(args) => key::get_derived_key(args), 89 | SnpGuestCmd::Ok => ok::cmd(snpguest.quiet), 90 | SnpGuestCmd::Generate(subcmd) => preattestation::cmd(subcmd, snpguest.quiet), 91 | }; 92 | 93 | if let Err(ref e) = status { 94 | if !snpguest.quiet { 95 | eprintln!("ERROR: {}", e); 96 | e.chain() 97 | .skip(1) 98 | .for_each(|cause| eprintln!("because: {}", cause)); 99 | } 100 | } 101 | 102 | status 103 | } 104 | -------------------------------------------------------------------------------- /src/ok.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | 3 | use std::fmt; 4 | 5 | use bitfield::bitfield; 6 | use colorful::*; 7 | use msru::*; 8 | use serde::{Deserialize, Serialize}; 9 | 10 | const SEV_MASK: usize = 1; 11 | const ES_MASK: usize = 1 << 1; 12 | const SNP_MASK: usize = 1 << 2; 13 | type TestFn = dyn Fn() -> TestResult; 14 | 15 | struct Test { 16 | name: &'static str, 17 | gen_mask: usize, 18 | run: Box, 19 | sub: Vec, 20 | } 21 | 22 | struct TestResult { 23 | name: String, 24 | stat: TestState, 25 | mesg: Option, 26 | } 27 | 28 | #[derive(PartialEq, Eq)] 29 | enum TestState { 30 | Pass, 31 | Skip, 32 | Fail, 33 | } 34 | 35 | bitfield! { 36 | #[repr(C)] 37 | #[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)] 38 | pub struct SevStatus(u64); 39 | impl Debug; 40 | pub sev_bit, _ : 0,0; 41 | pub es_bit, _ : 1,1; 42 | pub snp_bit, _ : 2,2; 43 | pub vtom_bit, _ : 3,3; 44 | pub reflectvc_bit, _ : 4,4; 45 | pub restricted_injection_bit, _ : 5,5; 46 | pub alternate_injection_bit, _ : 6,6; 47 | pub debug_swap_bit, _ : 7,7; 48 | pub prevent_host_ibs_bit, _ : 8,8; 49 | pub btb_isolation_bit, _ : 9,9; 50 | pub vmpl_sss_bit, _ : 10,10; 51 | pub secure_tse_bit, _ : 11,11; 52 | pub vmg_exit_parameter_bit, _ : 12,12; 53 | reserved_1, _ : 13, 13; 54 | pub ibs_virtualization_bit, _ : 14,14; 55 | reserved_2, _ : 15,15; 56 | pub vmsa_reg_prot_bit, _ : 16,16; 57 | pub smt_protection_bit, _ : 17, 17; 58 | reserved_3, _ : 18, 63; 59 | } 60 | 61 | impl fmt::Display for TestState { 62 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 63 | let s = match self { 64 | TestState::Pass => format!("{}", "PASS".green()), 65 | TestState::Skip => format!("{}", "SKIP".yellow()), 66 | TestState::Fail => format!("{}", "FAIL".red()), 67 | }; 68 | 69 | write!(f, "{}", s) 70 | } 71 | } 72 | 73 | fn collect_tests() -> Vec { 74 | // Grab your MSR value one time. 75 | let temp_bitfield = match get_values(0xC0010131, 0) { 76 | Ok(temp_bitfield) => temp_bitfield, 77 | Err(e) => { 78 | return vec![Test { 79 | name: "Error reading MSR", 80 | gen_mask: SEV_MASK, 81 | run: Box::new(move || TestResult { 82 | name: "Error reading MSR".to_string(), 83 | stat: TestState::Fail, 84 | mesg: Some(format!("Failed to get bit values, {e}")), 85 | }), 86 | sub: vec![], 87 | }] 88 | } 89 | }; 90 | 91 | let tests = vec![ 92 | Test { 93 | name: "SEV", 94 | gen_mask: SEV_MASK, 95 | run: Box::new(move || run_msr_check(temp_bitfield.sev_bit(), "SEV", false)), 96 | sub: vec![], 97 | }, 98 | Test { 99 | name: "SEV-ES", 100 | gen_mask: ES_MASK, 101 | run: Box::new(move || run_msr_check(temp_bitfield.es_bit(), "SEV-ES", false)), 102 | sub: vec![], 103 | }, 104 | Test { 105 | name: "SNP", 106 | gen_mask: SNP_MASK, 107 | run: Box::new(move || run_msr_check(temp_bitfield.snp_bit(), "SNP", false)), 108 | sub: vec![], 109 | }, 110 | Test { 111 | name: "Optional Features", 112 | gen_mask: SEV_MASK, 113 | run: Box::new(|| TestResult { 114 | name: "Optional Features statuses:".to_string(), 115 | stat: TestState::Pass, 116 | mesg: None, 117 | }), 118 | sub: vec![ 119 | Test { 120 | name: "vTOM", 121 | gen_mask: SNP_MASK, 122 | run: Box::new(move || run_msr_check(temp_bitfield.vtom_bit(), "VTOM", true)), 123 | sub: vec![], 124 | }, 125 | Test { 126 | name: "Reflect VC", 127 | gen_mask: SNP_MASK, 128 | run: Box::new(move || { 129 | run_msr_check(temp_bitfield.reflectvc_bit(), "ReflectVC", true) 130 | }), 131 | sub: vec![], 132 | }, 133 | Test { 134 | name: "Restricted Injection", 135 | gen_mask: SNP_MASK, 136 | run: Box::new(move || { 137 | run_msr_check( 138 | temp_bitfield.restricted_injection_bit(), 139 | "Restricted Injection", 140 | true, 141 | ) 142 | }), 143 | sub: vec![], 144 | }, 145 | Test { 146 | name: "Alternate Injection", 147 | gen_mask: SNP_MASK, 148 | run: Box::new(move || { 149 | run_msr_check( 150 | temp_bitfield.alternate_injection_bit(), 151 | "Alternate Injection", 152 | true, 153 | ) 154 | }), 155 | sub: vec![], 156 | }, 157 | Test { 158 | name: "Debug Swap", 159 | gen_mask: SNP_MASK, 160 | run: Box::new(move || { 161 | run_msr_check(temp_bitfield.debug_swap_bit(), "Debug Swap", true) 162 | }), 163 | sub: vec![], 164 | }, 165 | Test { 166 | name: "Prevent Host IBS", 167 | gen_mask: SNP_MASK, 168 | run: Box::new(move || { 169 | run_msr_check( 170 | temp_bitfield.prevent_host_ibs_bit(), 171 | "Prevent Host IBS", 172 | true, 173 | ) 174 | }), 175 | sub: vec![], 176 | }, 177 | Test { 178 | name: "SNP BTB Isolation", 179 | gen_mask: SNP_MASK, 180 | run: Box::new(move || { 181 | run_msr_check(temp_bitfield.btb_isolation_bit(), "SNP BTB Isolation", true) 182 | }), 183 | sub: vec![], 184 | }, 185 | Test { 186 | name: "VMPL SSS", 187 | gen_mask: SNP_MASK, 188 | run: Box::new(move || { 189 | run_msr_check(temp_bitfield.vmpl_sss_bit(), "VMPL SSS", true) 190 | }), 191 | sub: vec![], 192 | }, 193 | Test { 194 | name: "Secure TSE", 195 | gen_mask: SNP_MASK, 196 | run: Box::new(move || { 197 | run_msr_check(temp_bitfield.secure_tse_bit(), "Secure TSE", true) 198 | }), 199 | sub: vec![], 200 | }, 201 | Test { 202 | name: "VMG Exit Parameter", 203 | gen_mask: SNP_MASK, 204 | run: Box::new(move || { 205 | run_msr_check( 206 | temp_bitfield.vmg_exit_parameter_bit(), 207 | "VMG Exit Parameter", 208 | true, 209 | ) 210 | }), 211 | sub: vec![], 212 | }, 213 | Test { 214 | name: "IBS Virtualization", 215 | gen_mask: SNP_MASK, 216 | run: Box::new(move || { 217 | run_msr_check( 218 | temp_bitfield.ibs_virtualization_bit(), 219 | "IBS Virtualization", 220 | true, 221 | ) 222 | }), 223 | sub: vec![], 224 | }, 225 | Test { 226 | name: "VMSA Reg Prot", 227 | gen_mask: SNP_MASK, 228 | run: Box::new(move || { 229 | run_msr_check(temp_bitfield.vmsa_reg_prot_bit(), "VMSA Reg Prot", true) 230 | }), 231 | sub: vec![], 232 | }, 233 | Test { 234 | name: "SMT Protection", 235 | gen_mask: SNP_MASK, 236 | run: Box::new(move || { 237 | run_msr_check(temp_bitfield.smt_protection_bit(), "SMT Protection", true) 238 | }), 239 | sub: vec![], 240 | }, 241 | ], 242 | }, 243 | ]; 244 | tests 245 | } 246 | 247 | const INDENT: usize = 2; 248 | 249 | pub fn cmd(quiet: bool) -> Result<()> { 250 | let tests = collect_tests(); 251 | 252 | if run_test(&tests, 0, quiet, SEV_MASK | ES_MASK | SNP_MASK) { 253 | Ok(()) 254 | } else { 255 | Err(anyhow::anyhow!( 256 | "One or more tests in snpguest-ok reported a failure" 257 | )) 258 | } 259 | } 260 | 261 | fn run_test(tests: &[Test], level: usize, quiet: bool, mask: usize) -> bool { 262 | let mut passed = true; 263 | 264 | for t in tests { 265 | // Skip tests that aren't included in the specified generation. 266 | if (t.gen_mask & mask) != t.gen_mask { 267 | test_gen_not_included(t, level, quiet); 268 | continue; 269 | } 270 | 271 | let res = (t.run)(); 272 | emit_result(&res, level, quiet); 273 | match res.stat { 274 | TestState::Pass => { 275 | if !run_test(&t.sub, level + INDENT, quiet, mask) { 276 | passed = false; 277 | } 278 | } 279 | TestState::Fail => { 280 | passed = false; 281 | emit_skip(&t.sub, level + INDENT, quiet); 282 | } 283 | // Skipped tests are marked as skip before recursing. They are just emitted and not actually processed. 284 | TestState::Skip => unreachable!(), 285 | } 286 | } 287 | 288 | passed 289 | } 290 | 291 | fn emit_result(res: &TestResult, level: usize, quiet: bool) { 292 | if !quiet { 293 | let msg = match &res.mesg { 294 | Some(m) => format!(": {}", m), 295 | None => "".to_string(), 296 | }; 297 | println!( 298 | "[ {:^4} ] {:width$}- {}{}", 299 | format!("{}", res.stat), 300 | "", 301 | res.name, 302 | msg, 303 | width = level 304 | ) 305 | } 306 | } 307 | 308 | fn test_gen_not_included(test: &Test, level: usize, quiet: bool) { 309 | if !quiet { 310 | let tr_skip = TestResult { 311 | name: test.name.to_string(), 312 | stat: TestState::Skip, 313 | mesg: None, 314 | }; 315 | 316 | println!( 317 | "[ {:^4} ] {:width$}- {}", 318 | format!("{}", tr_skip.stat), 319 | "", 320 | tr_skip.name, 321 | width = level 322 | ); 323 | emit_skip(&test.sub, level + INDENT, quiet); 324 | } 325 | } 326 | 327 | fn emit_skip(tests: &[Test], level: usize, quiet: bool) { 328 | if !quiet { 329 | for t in tests { 330 | let tr_skip = TestResult { 331 | name: t.name.to_string(), 332 | stat: TestState::Skip, 333 | mesg: None, 334 | }; 335 | 336 | println!( 337 | "[ {:^4} ] {:width$}- {}", 338 | format!("{}", tr_skip.stat), 339 | "", 340 | tr_skip.name, 341 | width = level 342 | ); 343 | emit_skip(&t.sub, level + INDENT, quiet); 344 | } 345 | } 346 | } 347 | 348 | fn get_values(reg: u32, cpu: u16) -> Result { 349 | let mut msr = Msr::new(reg, cpu).context("Error Reading MSR")?; 350 | let my_bitfield = SevStatus(msr.read()?); 351 | Ok(my_bitfield) 352 | } 353 | 354 | fn run_msr_check(check_bit: u64, sev_feature: &str, optional_field: bool) -> TestResult { 355 | let mut status = TestState::Fail; 356 | let mut message = "DISABLED".to_string(); 357 | 358 | if check_bit == 1 { 359 | status = TestState::Pass; 360 | message = "ENABLED".to_string(); 361 | } else if optional_field { 362 | status = TestState::Pass; 363 | } 364 | 365 | TestResult { 366 | name: sev_feature.to_string(), 367 | stat: status, 368 | mesg: Some(message), 369 | } 370 | } 371 | -------------------------------------------------------------------------------- /src/preattestation.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | // This file defines the CLI for pre-attestation related processes, such as calculating the measurement or generating an ID-BLOCK 3 | 4 | use super::*; 5 | use base64::{engine::general_purpose, Engine as _}; 6 | use clap_num::maybe_hex; 7 | use sev::{ 8 | firmware::guest::GuestPolicy, 9 | measurement::{ 10 | idblock::{generate_key_digest, snp_calculate_id}, 11 | idblock_types::{FamilyId, ImageId}, 12 | snp::{calc_snp_ovmf_hash, snp_calc_launch_digest, SnpLaunchDigest, SnpMeasurementArgs}, 13 | vcpu_types::{cpu_sig, CpuType}, 14 | vmsa::{GuestFeatures, VMMType}, 15 | }, 16 | }; 17 | use std::{fs::OpenOptions, io::Write, path::PathBuf}; 18 | 19 | #[derive(Subcommand)] 20 | pub enum PreAttestationCmd { 21 | /// Calculate the Measurement of a confidential VM with the supplied parameters 22 | Measurement(measurement::Args), 23 | 24 | /// Calculated the hash of an OVMF file 25 | OvmfHash(ovmf_hash::Args), 26 | 27 | /// Generate an ID-Block and Auth-Block for a confidential VM with the supplied parameters 28 | IdBlock(idblock::Args), 29 | 30 | /// Generate a SEV key digest for the provided openssl key. 31 | KeyDigest(keydigest::Args), 32 | } 33 | 34 | pub fn cmd(cmd: PreAttestationCmd, quiet: bool) -> Result<()> { 35 | match cmd { 36 | PreAttestationCmd::Measurement(args) => measurement::generate_measurement(args, quiet), 37 | PreAttestationCmd::OvmfHash(args) => ovmf_hash::generate_ovmf_hash(args, quiet), 38 | PreAttestationCmd::IdBlock(args) => idblock::generate_id_block(args, quiet), 39 | PreAttestationCmd::KeyDigest(args) => keydigest::calculate_key_digest(args, quiet), 40 | } 41 | } 42 | 43 | mod measurement { 44 | 45 | use std::str::FromStr; 46 | 47 | use super::*; 48 | 49 | #[derive(Parser, Debug)] 50 | pub struct Args { 51 | /// Number of guest vcpus 52 | #[arg(short, long, default_value = "1")] 53 | pub vcpus: u32, 54 | 55 | /// Type of guest vcpu (EPYC, EPYC-v1, EPYC-v2, EPYC-IBPB, EPYC-v3, EPYC-v4, 56 | /// EPYC-Rome, EPYC-Rome-v1, EPYC-Rome-v2, EPYC-Rome-v3, EPYC-Milan, EPYC- 57 | /// Milan-v1, EPYC-Milan-v2, EPYC-Genoa, EPYC-Genoa-v1) 58 | #[arg(long, value_name = "vcpu-type", 59 | conflicts_with_all = ["vcpu_sig", "vcpu_family", "vcpu_model", "vcpu_stepping"], 60 | required_unless_present_any(["vcpu_sig", "vcpu_family", "vcpu_model", "vcpu_stepping"], 61 | ), ignore_case = true)] 62 | pub vcpu_type: Option, 63 | 64 | /// Guest vcpu signature value 65 | #[arg(long, value_name = "vcpu-sig", conflicts_with_all = ["vcpu_type", "vcpu_family", "vcpu_model", "vcpu_stepping"])] 66 | pub vcpu_sig: Option, 67 | 68 | /// Guest vcpu family 69 | #[arg(long, value_name = "vcpu-family", conflicts_with_all = ["vcpu_type", "vcpu_sig"], requires_all = ["vcpu_model", "vcpu_stepping"])] 70 | pub vcpu_family: Option, 71 | 72 | /// Guest vcpu model 73 | #[arg(long, value_name = "vcpu-model", conflicts_with_all = ["vcpu_type", "vcpu_sig"], requires_all = ["vcpu_family", "vcpu_stepping"])] 74 | pub vcpu_model: Option, 75 | 76 | /// Guest vcpu stepping. 77 | #[arg(long, value_name = "vcpu-stepping", conflicts_with_all = ["vcpu_type", "vcpu_sig"], requires_all = ["vcpu_family", "vcpu_model"])] 78 | pub vcpu_stepping: Option, 79 | 80 | /// Type of guest vmm (QEMU, ec2, KRUN) 81 | #[arg(long, short = 't', value_name = "vmm-type", ignore_case = true)] 82 | pub vmm_type: Option, 83 | 84 | /// OVMF file to calculate measurement from 85 | #[arg(short, long, value_name = "ovmf", required = true)] 86 | pub ovmf: PathBuf, 87 | 88 | /// Kernel file to calculate measurement from 89 | #[arg(short, long, value_name = "kernel")] 90 | pub kernel: Option, 91 | 92 | /// Initrd file to calculate measurement from 93 | #[arg(short, long, value_name = "initrd", requires = "kernel")] 94 | pub initrd: Option, 95 | 96 | /// Kernel command line to calculate measurement from 97 | #[arg(short, long, value_name = "append", requires = "kernel")] 98 | pub append: Option, 99 | 100 | /// Hex representation of the guest kernel features expected to be included, defaults to 0x1 101 | #[arg(short, long, value_name = "guest-features", value_parser=maybe_hex::)] 102 | pub guest_features: Option, 103 | 104 | /// Precalculated hash of the OVMF binary 105 | #[arg( 106 | long, 107 | value_name = "ovmf-hash", 108 | conflicts_with = "ovmf", 109 | required_unless_present = "ovmf" 110 | )] 111 | pub ovmf_hash: Option, 112 | 113 | ///Choose output format (base64, hex). 114 | #[arg( 115 | long, 116 | short = 'f', 117 | value_name = "output-format", 118 | default_value = "hex", 119 | ignore_case = true 120 | )] 121 | pub output_format: String, 122 | 123 | /// Optional file path where measurement value can be stored in 124 | #[arg(short = 'm', long, value_name = "measurement-file")] 125 | pub measurement_file: Option, 126 | } 127 | 128 | pub fn generate_measurement(args: Args, quiet: bool) -> Result<()> { 129 | // Get VCPU type from either string, signature or family, model and step. 130 | let vcpu_type = if let Some(v_type) = args.vcpu_type { 131 | CpuType::try_from(v_type.as_str())? 132 | } else if let Some(sig) = args.vcpu_sig { 133 | CpuType::try_from(sig)? 134 | } else if let Some(family) = args.vcpu_family { 135 | let sig = cpu_sig( 136 | family, 137 | args.vcpu_model.unwrap(), 138 | args.vcpu_stepping.unwrap(), 139 | ); 140 | CpuType::try_from(sig)? 141 | } else { 142 | return Err(anyhow::anyhow!("No VCPU Type provided")); 143 | }; 144 | 145 | let guest_features = match args.guest_features { 146 | Some(gf) => GuestFeatures(gf), 147 | None => GuestFeatures::default(), 148 | }; 149 | 150 | let append: Option<&str> = args.append.as_deref(); 151 | 152 | let ovmf_hash_str: Option<&str> = args.ovmf_hash.as_deref(); 153 | 154 | let vmm_type = match args.vmm_type { 155 | Some(vmm_type) => Some(VMMType::from_str(vmm_type.as_str())?), 156 | None => None, 157 | }; 158 | 159 | let collected_args = SnpMeasurementArgs { 160 | vcpus: args.vcpus, 161 | vcpu_type, 162 | ovmf_file: args.ovmf, 163 | guest_features, 164 | kernel_file: args.kernel, 165 | initrd_file: args.initrd, 166 | append, 167 | ovmf_hash_str, 168 | vmm_type, 169 | }; 170 | 171 | let launch_digest = match snp_calc_launch_digest(collected_args) { 172 | Ok(ld) => { 173 | if args.output_format == "hex" { 174 | format!("0x{}", ld.get_hex_ld()) 175 | } else { 176 | general_purpose::STANDARD.encode(ld.get_hex_ld().as_bytes()) 177 | } 178 | } 179 | Err(e) => return Err(anyhow::anyhow!("Error calculating the measurement:{e}")), 180 | }; 181 | 182 | // If measurement file is provided, store measurement value in the file 183 | if let Some(measurement_file) = args.measurement_file { 184 | let mut file = OpenOptions::new() 185 | .create(true) 186 | .truncate(true) 187 | .write(true) 188 | .open(measurement_file)?; 189 | 190 | file.write_all(launch_digest.as_bytes()) 191 | .expect("Unable to write data"); 192 | } 193 | 194 | // Print measurement 195 | if !quiet { 196 | println!("{}", launch_digest); 197 | } 198 | 199 | Ok(()) 200 | } 201 | } 202 | 203 | mod ovmf_hash { 204 | use super::*; 205 | 206 | #[derive(Parser)] 207 | pub struct Args { 208 | /// Path to OVMF file to calculate hash from 209 | #[arg(short, long, value_name = "ovmf", required = true)] 210 | pub ovmf: PathBuf, 211 | 212 | /// Choose output format (base64, hex). Defaults to hex 213 | #[arg( 214 | short = 'f', 215 | long, 216 | value_name = "output-format", 217 | default_value = "hex", 218 | ignore_case = true 219 | )] 220 | pub output_format: String, 221 | 222 | /// Optional file where hash value can be stored in 223 | #[arg(long, value_name = "hash-file")] 224 | pub hash_file: Option, 225 | } 226 | pub fn generate_ovmf_hash(args: Args, quiet: bool) -> Result<()> { 227 | let ovmf_hash = match calc_snp_ovmf_hash(args.ovmf) { 228 | Ok(ld) => { 229 | if args.output_format == "hex" { 230 | ld.get_hex_ld() 231 | } else { 232 | general_purpose::STANDARD.encode(ld.get_hex_ld().as_bytes()) 233 | } 234 | } 235 | Err(e) => return Err(anyhow::anyhow!("Error calculating the measurement:{e}")), 236 | }; 237 | 238 | if let Some(hash_file) = args.hash_file { 239 | let mut file = OpenOptions::new() 240 | .create(true) 241 | .truncate(true) 242 | .write(true) 243 | .open(hash_file)?; 244 | 245 | file.write_all(ovmf_hash.as_bytes()) 246 | .expect("Unable to write data"); 247 | } 248 | 249 | if !quiet { 250 | println!("{}", ovmf_hash); 251 | } 252 | 253 | Ok(()) 254 | } 255 | } 256 | 257 | mod idblock { 258 | use hex::FromHex; 259 | 260 | use super::*; 261 | 262 | #[derive(Parser)] 263 | pub struct Args { 264 | /// Path to the Id-Block key 265 | #[arg(value_name = "id-block-key", required = true)] 266 | pub id_block_key: PathBuf, 267 | 268 | /// Path to the Auth-Block key 269 | #[arg(value_name = "auth-key", required = true)] 270 | pub auth_key: PathBuf, 271 | 272 | /// Guest launch measurement in either Base64 encoding or hex (if hex prefix with 0x) 273 | #[arg(value_name = "launch-digest", required = true)] 274 | pub launch_digest: String, 275 | 276 | /// Family ID of the guest provided by the guest owner. Has to be 16 characters. 277 | #[arg(short, long, value_name = "family-id")] 278 | pub family_id: Option, 279 | 280 | /// Image ID of the guest provided by the guest owner. Has to be 16 characters. 281 | #[arg(short = 'm', long, value_name = "image-id")] 282 | pub image_id: Option, 283 | 284 | /// Id-Block version. Currently only version 1 is available 285 | #[arg(short, long, value_name = "version")] 286 | pub version: Option, 287 | 288 | /// SVN of the guest 289 | #[arg(short, long, value_name = "svn")] 290 | pub svn: Option, 291 | 292 | /// Launch policy of the guest. Can provide in decimal or hex format. 293 | #[arg(short, long, value_name = "policy", value_parser=maybe_hex::)] 294 | pub policy: Option, 295 | 296 | /// Optional file where the Id-Block value can be stored in 297 | #[arg(short, long, value_name = "id-block-file")] 298 | pub id_file: Option, 299 | 300 | /// Optional file where the Auth-Block value can be stored in 301 | #[arg(short, long, value_name = "auth-info-file")] 302 | pub auth_file: Option, 303 | } 304 | 305 | pub fn generate_id_block(args: Args, quiet: bool) -> Result<()> { 306 | let ld = 307 | if &args.launch_digest[..args.launch_digest.char_indices().nth(2).unwrap().0] == "0x" { 308 | SnpLaunchDigest::new(Vec::from_hex(&args.launch_digest[2..])?.try_into()?) 309 | } else { 310 | SnpLaunchDigest::new( 311 | general_purpose::STANDARD 312 | .decode(args.launch_digest)? 313 | .try_into()?, 314 | ) 315 | }; 316 | 317 | let family_id = match args.family_id { 318 | Some(family) => { 319 | if family.chars().count() == 16 { 320 | Some(FamilyId::new(family.as_bytes().try_into()?)) 321 | } else { 322 | return Err(anyhow::anyhow!("Invalid Family Id length!")); 323 | } 324 | } 325 | None => None, 326 | }; 327 | 328 | let image_id = match args.image_id { 329 | Some(image) => { 330 | if image.chars().count() == 16 { 331 | Some(ImageId::new(image.as_bytes().try_into()?)) 332 | } else { 333 | return Err(anyhow::anyhow!("Invalid Image Id length!")); 334 | } 335 | } 336 | None => None, 337 | }; 338 | 339 | let policy = args.policy.map(GuestPolicy); 340 | 341 | let measurements = snp_calculate_id( 342 | Some(ld), 343 | family_id, 344 | image_id, 345 | args.svn, 346 | policy, 347 | args.id_block_key, 348 | args.auth_key, 349 | )?; 350 | 351 | // Formatted in Base-64 since it's the format QEMU takes. 352 | let id_block_string = 353 | general_purpose::STANDARD.encode(bincode::serialize(&measurements.id_block)?); 354 | let id_auth_string = 355 | general_purpose::STANDARD.encode(bincode::serialize(&measurements.id_auth)?); 356 | 357 | // If Id-Block file is provided, store Id-Block value in the file 358 | if let Some(id_file) = args.id_file { 359 | let mut file = OpenOptions::new() 360 | .create(true) 361 | .truncate(true) 362 | .write(true) 363 | .open(id_file)?; 364 | 365 | file.write_all(id_block_string.as_bytes()) 366 | .expect("Unable to write data"); 367 | } 368 | 369 | // If Auth-Block file is provided, store Auth-Block value in the file 370 | if let Some(auth_file) = args.auth_file { 371 | let mut file = OpenOptions::new() 372 | .create(true) 373 | .truncate(true) 374 | .write(true) 375 | .open(auth_file)?; 376 | 377 | file.write_all(id_auth_string.as_bytes()) 378 | .expect("Unable to write data"); 379 | } 380 | 381 | if !quiet { 382 | println!("ID-BLOCK:"); 383 | println!("{}", id_block_string); 384 | println!("AUTH-BLOCK:"); 385 | println!("{}", id_auth_string); 386 | } 387 | Ok(()) 388 | } 389 | } 390 | 391 | mod keydigest { 392 | use super::*; 393 | 394 | #[derive(Parser)] 395 | pub struct Args { 396 | /// Path to key to generate hash for 397 | #[arg(value_name = "key", required = true)] 398 | pub key: PathBuf, 399 | 400 | /// File to store the key digest in 401 | #[arg(short = 'd', long, value_name = "key-digest-file")] 402 | pub key_digest_file: Option, 403 | } 404 | 405 | pub fn calculate_key_digest(args: Args, quiet: bool) -> Result<()> { 406 | let kd = generate_key_digest(args.key)?; 407 | 408 | let key_digest_string = hex::encode::>(kd.try_into().unwrap()); 409 | 410 | if let Some(key_digest_file) = args.key_digest_file { 411 | let mut file = OpenOptions::new() 412 | .create(true) 413 | .truncate(true) 414 | .write(true) 415 | .open(key_digest_file)?; 416 | 417 | file.write_all(key_digest_string.as_bytes()) 418 | .expect("Unable to write data"); 419 | } 420 | 421 | if !quiet { 422 | println!("Key Digest:"); 423 | println!("{}", key_digest_string); 424 | } 425 | Ok(()) 426 | } 427 | } 428 | -------------------------------------------------------------------------------- /src/report.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | // This file defines the CLI for requesting attestation reports. It contains functions for requesting attestation reports and saving them to files. Additionally, it includes code for reading and parsing attestation reports. 3 | 4 | use super::*; 5 | 6 | use std::{ 7 | fs::{self, File, OpenOptions}, 8 | io::{Read, Write}, 9 | path::PathBuf, 10 | }; 11 | 12 | use anyhow::{anyhow, Result}; 13 | use rand::{thread_rng, RngCore}; 14 | use sev::firmware::guest::{AttestationReport, Firmware}; 15 | 16 | // Read a bin-formatted attestation report. 17 | pub fn read_report(att_report_path: PathBuf) -> Result { 18 | let mut attestation_file = fs::File::open(att_report_path)?; 19 | 20 | let mut report_bytes = Vec::new(); 21 | attestation_file 22 | .read_to_end(&mut report_bytes) 23 | .context("Failed to read the report bytes.")?; 24 | 25 | let attestation_report = AttestationReport::from_bytes(&report_bytes) 26 | .context("Failed to build report from the raw bytes. Report could be malformed.")?; 27 | 28 | Ok(attestation_report) 29 | } 30 | 31 | // Create 64 random bytes of data for attestation report request 32 | pub fn create_random_request() -> [u8; 64] { 33 | let mut data = [0u8; 64]; 34 | thread_rng().fill_bytes(&mut data); 35 | data 36 | } 37 | 38 | /// Report command to request an attestation report. 39 | #[derive(Parser)] 40 | pub struct ReportArgs { 41 | /// File to write the attestation report to. 42 | #[arg(value_name = "att-report-path", required = true)] 43 | pub att_report_path: PathBuf, 44 | 45 | /// Use random data for attestation report request. Writes data 46 | /// to ./random-request-file.txt by default, use --request to specify 47 | /// where to write data. 48 | #[arg(short, long, default_value_t = false, conflicts_with = "platform")] 49 | pub random: bool, 50 | 51 | /// Specify an integer VMPL level between 0 and 3 that the Guest is running on. 52 | #[arg(short, long, default_value = "1", value_name = "vmpl")] 53 | pub vmpl: Option, 54 | 55 | /// Provide file with data for attestation-report request. If provided 56 | /// with random flag, then the random data will be written in the 57 | /// provided path. 58 | #[arg(value_name = "request-file", required = true)] 59 | pub request_file: PathBuf, 60 | 61 | /// Expect that the 64-byte report data will already be provided by the platform provider. 62 | #[arg(short, long, conflicts_with = "random")] 63 | pub platform: bool, 64 | } 65 | 66 | impl ReportArgs { 67 | pub fn verify(&self, hyperv: bool) -> Result<()> { 68 | if self.random && self.platform { 69 | return Err(anyhow!( 70 | "--random and --platform both enabled (not allowed). Consult man page." 71 | )); 72 | } 73 | 74 | if self.random && hyperv { 75 | return Err(anyhow!( 76 | "--random enabled yet Hyper-V guest detected (not allowed). Consult man page." 77 | )); 78 | } 79 | 80 | if self.platform && !hyperv { 81 | return Err(anyhow!("--platform enabled yet Hyper-V guest not detected (not allowed). Consult man page.")); 82 | } 83 | 84 | Ok(()) 85 | } 86 | } 87 | 88 | #[cfg(feature = "hyperv")] 89 | fn request_hardware_report( 90 | _data: Option<[u8; 64]>, 91 | vmpl: Option, 92 | ) -> Result { 93 | hyperv::report::get(vmpl.unwrap_or(0)) 94 | } 95 | 96 | #[cfg(not(feature = "hyperv"))] 97 | fn request_hardware_report(data: Option<[u8; 64]>, vmpl: Option) -> Result { 98 | let mut fw = Firmware::open().context("unable to open /dev/sev-guest")?; 99 | Ok(AttestationReport::from_bytes( 100 | fw.get_report(None, data, vmpl) 101 | .context("unable to fetch attestation report")? 102 | .as_slice(), 103 | )?) 104 | } 105 | 106 | // Request attestation report and write it into a file 107 | pub fn get_report(args: ReportArgs, hv: bool) -> Result<()> { 108 | args.verify(hv)?; 109 | 110 | let data: Option<[u8; 64]> = if args.random { 111 | Some(create_random_request()) 112 | } else if args.platform { 113 | None 114 | } else { 115 | /* 116 | * Read from the request file. 117 | */ 118 | let mut bytes = [0u8; 64]; 119 | let mut file = File::open(&args.request_file)?; 120 | file.read_exact(&mut bytes) 121 | .context("unable to read 64 bytes from REQUEST_FILE")?; 122 | 123 | Some(bytes) 124 | }; 125 | 126 | let report = request_hardware_report(data, args.vmpl)?; 127 | 128 | /* 129 | * Serialize and write attestation report. 130 | */ 131 | let mut file = OpenOptions::new() 132 | .create(true) 133 | .truncate(true) 134 | .write(true) 135 | .open(&args.att_report_path)?; 136 | 137 | report.write_bytes(&mut file)?; 138 | 139 | /* 140 | * Write reports report data (only for --random or --platform). 141 | */ 142 | if args.random { 143 | reqdata_write(args.request_file, &report).context("unable to write random request data")?; 144 | } else if args.platform { 145 | reqdata_write(args.request_file, &report) 146 | .context("unable to write platform request data")?; 147 | } 148 | 149 | Ok(()) 150 | } 151 | 152 | fn reqdata_write(name: PathBuf, report: &AttestationReport) -> Result<()> { 153 | let mut file = OpenOptions::new() 154 | .create(true) 155 | .truncate(true) 156 | .write(true) 157 | .open(name) 158 | .context("unable to create or write to request data file")?; 159 | 160 | write_hex(&mut file, report.report_data.as_slice()) 161 | .context("unable to write report data to REQUEST_FILE") 162 | } 163 | 164 | pub fn write_hex(file: &mut File, data: &[u8]) -> Result<()> { 165 | let mut line_counter = 0; 166 | for val in data { 167 | // Make it blocks for easier read 168 | if line_counter.eq(&16) { 169 | writeln!(file)?; 170 | line_counter = 0; 171 | } 172 | 173 | write!(file, "{:02x}", val)?; 174 | line_counter += 1; 175 | } 176 | Ok(()) 177 | } 178 | -------------------------------------------------------------------------------- /src/verify.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | // This file includes subcommands for verifying certificate chains and attestation reports. Submodules `certificate_chain` and `attestation` contain the verification logic for certificates and attestation reports, respectively. 3 | 4 | use super::*; 5 | 6 | use certs::{convert_path_to_cert, CertPaths}; 7 | 8 | use fetch::{get_processor_model, ProcType}; 9 | 10 | use std::{ 11 | io::ErrorKind, 12 | path::{Path, PathBuf}, 13 | }; 14 | 15 | use openssl::{ecdsa::EcdsaSig, sha::Sha384}; 16 | use sev::certs::snp::Chain; 17 | 18 | #[derive(Subcommand)] 19 | pub enum VerifyCmd { 20 | /// Verify the certificate chain. 21 | Certs(certificate_chain::Args), 22 | 23 | /// Verify the attestation report. 24 | Attestation(attestation::Args), 25 | } 26 | 27 | pub fn cmd(cmd: VerifyCmd, quiet: bool) -> Result<()> { 28 | match cmd { 29 | VerifyCmd::Certs(args) => certificate_chain::validate_cc(args, quiet), 30 | VerifyCmd::Attestation(args) => attestation::verify_attestation(args, quiet), 31 | } 32 | } 33 | 34 | // Find a certificate in specified directory according to its extension 35 | pub fn find_cert_in_dir(dir: &Path, cert: &str) -> Result { 36 | if dir.join(format!("{cert}.pem")).exists() { 37 | Ok(dir.join(format!("{cert}.pem"))) 38 | } else if dir.join(format!("{cert}.der")).exists() { 39 | Ok(dir.join(format!("{cert}.der"))) 40 | } else { 41 | return Err(anyhow::anyhow!("{cert} certificate not found in directory")); 42 | } 43 | } 44 | 45 | mod certificate_chain { 46 | use sev::certs::snp::Verifiable; 47 | 48 | use super::*; 49 | 50 | #[derive(Parser)] 51 | pub struct Args { 52 | /// Path to directory containing certificate chain." 53 | #[arg(value_name = "certs-dir", required = true)] 54 | pub certs_dir: PathBuf, 55 | } 56 | 57 | // Function to validate certificate chain 58 | pub fn validate_cc(args: Args, quiet: bool) -> Result<()> { 59 | let ark_path = find_cert_in_dir(&args.certs_dir, "ark")?; 60 | let (mut vek_type, mut sign_type): (&str, &str) = ("vcek", "ask"); 61 | let (vek_path, ask_path) = match find_cert_in_dir(&args.certs_dir, "vlek") { 62 | Ok(vlek_path) => { 63 | (vek_type, sign_type) = ("vlek", "asvk"); 64 | (vlek_path, find_cert_in_dir(&args.certs_dir, sign_type)?) 65 | } 66 | Err(_) => ( 67 | find_cert_in_dir(&args.certs_dir, vek_type)?, 68 | find_cert_in_dir(&args.certs_dir, sign_type)?, 69 | ), 70 | }; 71 | 72 | // Get a cert chain from directory 73 | let cert_chain: Chain = CertPaths { 74 | ark_path, 75 | ask_path, 76 | vek_path, 77 | } 78 | .try_into()?; 79 | 80 | let ark = cert_chain.ca.ark; 81 | let ask = cert_chain.ca.ask; 82 | let vek = cert_chain.vek; 83 | 84 | // Verify each signature and print result in console 85 | match (&ark, &ark).verify() { 86 | Ok(()) => { 87 | if !quiet { 88 | println!("The AMD ARK was self-signed!"); 89 | } 90 | } 91 | Err(e) => match e.kind() { 92 | ErrorKind::Other => return Err(anyhow::anyhow!("The AMD ARK is not self-signed!")), 93 | _ => { 94 | return Err(anyhow::anyhow!( 95 | "Failed to verify the ARK cerfificate: {:?}", 96 | e 97 | )) 98 | } 99 | }, 100 | } 101 | 102 | match (&ark, &ask).verify() { 103 | Ok(()) => { 104 | if !quiet { 105 | println!( 106 | "The AMD {} was signed by the AMD ARK!", 107 | sign_type.to_uppercase() 108 | ); 109 | } 110 | } 111 | Err(e) => match e.kind() { 112 | ErrorKind::Other => { 113 | return Err(anyhow::anyhow!( 114 | "The AMD {} was not signed by the AMD ARK!", 115 | sign_type.to_uppercase() 116 | )) 117 | } 118 | _ => return Err(anyhow::anyhow!("Failed to verify ASK certificate: {:?}", e)), 119 | }, 120 | } 121 | 122 | match (&ask, &vek).verify() { 123 | Ok(()) => { 124 | if !quiet { 125 | println!( 126 | "The {} was signed by the AMD {}!", 127 | vek_type.to_uppercase(), 128 | sign_type.to_uppercase() 129 | ); 130 | } 131 | } 132 | Err(e) => match e.kind() { 133 | ErrorKind::Other => { 134 | return Err(anyhow::anyhow!( 135 | "The {} was not signed by the AMD {}!", 136 | vek_type.to_uppercase(), 137 | sign_type.to_uppercase(), 138 | )) 139 | } 140 | _ => return Err(anyhow::anyhow!("Failed to verify VEK certificate: {:?}", e)), 141 | }, 142 | } 143 | Ok(()) 144 | } 145 | } 146 | 147 | mod attestation { 148 | use super::*; 149 | 150 | use asn1_rs::{oid, FromDer, Oid}; 151 | 152 | use x509_parser::{self, certificate::X509Certificate, prelude::X509Extension, x509::X509Name}; 153 | 154 | use sev::{ 155 | certs::snp::Certificate, 156 | firmware::{guest::AttestationReport, host::CertType}, 157 | }; 158 | 159 | enum SnpOid { 160 | BootLoader, 161 | Tee, 162 | Snp, 163 | Ucode, 164 | HwId, 165 | Fmc, 166 | } 167 | 168 | // OID extensions for the VCEK, will be used to verify attestation report 169 | impl SnpOid { 170 | fn oid(&self) -> Oid { 171 | match self { 172 | SnpOid::BootLoader => oid!(1.3.6 .1 .4 .1 .3704 .1 .3 .1), 173 | SnpOid::Tee => oid!(1.3.6 .1 .4 .1 .3704 .1 .3 .2), 174 | SnpOid::Snp => oid!(1.3.6 .1 .4 .1 .3704 .1 .3 .3), 175 | SnpOid::Ucode => oid!(1.3.6 .1 .4 .1 .3704 .1 .3 .8), 176 | SnpOid::HwId => oid!(1.3.6 .1 .4 .1 .3704 .1 .4), 177 | SnpOid::Fmc => oid!(1.3.6 .1 .4 .1 .3704 .1 .3 .9), 178 | } 179 | } 180 | } 181 | 182 | #[derive(Parser)] 183 | pub struct Args { 184 | /// Path to directory containing VCEK. 185 | #[arg(value_name = "certs-dir", required = true)] 186 | pub certs_dir: PathBuf, 187 | 188 | /// Path to attestation report to use for validation. 189 | #[arg(value_name = "att-report-path", required = true)] 190 | pub att_report_path: PathBuf, 191 | 192 | /// Specify the processor model to verify the attestation report. 193 | #[arg(short, long, value_name = "processor-model", ignore_case = true)] 194 | pub processor_model: Option, 195 | 196 | /// Run the TCB Verification Exclusively. 197 | #[arg(short, long, conflicts_with = "signature")] 198 | pub tcb: bool, 199 | 200 | /// Run the Signature Verification Exclusively. 201 | #[arg(short, long, conflicts_with = "tcb")] 202 | pub signature: bool, 203 | } 204 | 205 | fn verify_attestation_signature( 206 | vcek: Certificate, 207 | att_report: AttestationReport, 208 | quiet: bool, 209 | ) -> Result<()> { 210 | let vek_pubkey = vcek 211 | .public_key() 212 | .context("Failed to get the public key from the VEK.")? 213 | .ec_key() 214 | .context("Failed to convert VEK public key into ECkey.")?; 215 | 216 | // Get the attestation report signature 217 | let ar_signature = EcdsaSig::try_from(&att_report.signature) 218 | .context("Failed to get ECDSA Signature from attestation report.")?; 219 | let mut report_bytes = Vec::new(); 220 | att_report.write_bytes(&mut report_bytes)?; 221 | let signed_bytes = &report_bytes[0x0..0x2A0]; 222 | 223 | let mut hasher: Sha384 = Sha384::new(); 224 | 225 | hasher.update(signed_bytes); 226 | 227 | let base_message_digest: [u8; 48] = hasher.finish(); 228 | 229 | // Verify signature 230 | if ar_signature 231 | .verify(base_message_digest.as_ref(), vek_pubkey.as_ref()) 232 | .context("Failed to verify attestation report signature with VEK public key.")? 233 | { 234 | if !quiet { 235 | println!("VEK signed the Attestation Report!"); 236 | } 237 | } else { 238 | return Err(anyhow::anyhow!("VEK did NOT sign the Attestation Report!")); 239 | } 240 | 241 | Ok(()) 242 | } 243 | 244 | // Check the cert extension byte to value 245 | fn check_cert_bytes(ext: &X509Extension, val: &[u8]) -> bool { 246 | match ext.value[0] { 247 | // Integer 248 | 0x2 => { 249 | if ext.value[1] != 0x1 && ext.value[1] != 0x2 { 250 | panic!("Invalid octet length encountered!"); 251 | } else if let Some(byte_value) = ext.value.last() { 252 | byte_value == &val[0] 253 | } else { 254 | false 255 | } 256 | } 257 | // Octet String 258 | 0x4 => { 259 | if ext.value[1] != 0x40 { 260 | panic!("Invalid octet length encountered!"); 261 | } else if ext.value[2..].len() != 0x40 { 262 | panic!("Invalid size of bytes encountered!"); 263 | } else if val.len() != 0x40 { 264 | panic!("Invalid certificate harward id length encountered!") 265 | } 266 | 267 | &ext.value[2..] == val 268 | } 269 | // Legacy and others. 270 | _ => { 271 | // Keep around for a bit for old VCEK without x509 DER encoding. 272 | if ext.value.len() == 0x40 && val.len() == 0x40 { 273 | ext.value == val 274 | } else { 275 | panic!("Invalid type encountered!"); 276 | } 277 | } 278 | } 279 | } 280 | 281 | fn parse_common_name(field: &X509Name<'_>) -> Result { 282 | if let Some(val) = field 283 | .iter_common_name() 284 | .next() 285 | .and_then(|cn| cn.as_str().ok()) 286 | { 287 | match val.to_lowercase() { 288 | x if x.contains("ark") => Ok(CertType::ARK), 289 | x if x.contains("ask") | x.contains("sev") => Ok(CertType::ASK), 290 | x if x.contains("vcek") => Ok(CertType::VCEK), 291 | x if x.contains("vlek") => Ok(CertType::VLEK), 292 | x if x.contains("crl") => Ok(CertType::CRL), 293 | _ => Err(anyhow::anyhow!("Unknown certificate type encountered!")), 294 | } 295 | } else { 296 | Err(anyhow::anyhow!( 297 | "Certificate Subject Common Name is Unknown!" 298 | )) 299 | } 300 | } 301 | 302 | fn verify_attestation_tcb( 303 | vcek: Certificate, 304 | att_report: AttestationReport, 305 | proc_model: ProcType, 306 | quiet: bool, 307 | ) -> Result<()> { 308 | let vek_der = vcek.to_der().context("Could not convert VEK to der.")?; 309 | let (_, vek_x509) = X509Certificate::from_der(&vek_der) 310 | .context("Could not create X509Certificate from der")?; 311 | 312 | // Collect extensions from VEK 313 | let extensions: std::collections::HashMap = vek_x509 314 | .extensions_map() 315 | .context("Failed getting VEK oids.")?; 316 | 317 | let common_name: CertType = parse_common_name(vek_x509.subject())?; 318 | 319 | // Compare bootloaders 320 | if let Some(cert_bl) = extensions.get(&SnpOid::BootLoader.oid()) { 321 | if !check_cert_bytes(cert_bl, &att_report.reported_tcb.bootloader.to_le_bytes()) { 322 | return Err(anyhow::anyhow!( 323 | "Report TCB Boot Loader and Certificate Boot Loader mismatch encountered." 324 | )); 325 | } 326 | if !quiet { 327 | println!( 328 | "Reported TCB Boot Loader from certificate matches the attestation report." 329 | ); 330 | } 331 | } 332 | 333 | // Compare TEE information 334 | if let Some(cert_tee) = extensions.get(&SnpOid::Tee.oid()) { 335 | if !check_cert_bytes(cert_tee, &att_report.reported_tcb.tee.to_le_bytes()) { 336 | return Err(anyhow::anyhow!( 337 | "Report TCB TEE and Certificate TEE mismatch encountered." 338 | )); 339 | } 340 | if !quiet { 341 | println!("Reported TCB TEE from certificate matches the attestation report."); 342 | } 343 | } 344 | 345 | // Compare SNP information 346 | if let Some(cert_snp) = extensions.get(&SnpOid::Snp.oid()) { 347 | if !check_cert_bytes(cert_snp, &att_report.reported_tcb.snp.to_le_bytes()) { 348 | return Err(anyhow::anyhow!( 349 | "Report TCB SNP and Certificate SNP mismatch encountered." 350 | )); 351 | } 352 | if !quiet { 353 | println!("Reported TCB SNP from certificate matches the attestation report."); 354 | } 355 | } 356 | 357 | // Compare Microcode information 358 | if let Some(cert_ucode) = extensions.get(&SnpOid::Ucode.oid()) { 359 | if !check_cert_bytes(cert_ucode, &att_report.reported_tcb.microcode.to_le_bytes()) { 360 | return Err(anyhow::anyhow!( 361 | "Report TCB Microcode and Certificate Microcode mismatch encountered." 362 | )); 363 | } 364 | if !quiet { 365 | println!("Reported TCB Microcode from certificate matches the attestation report."); 366 | } 367 | } 368 | 369 | // Compare HWID information only on VCEK 370 | if common_name == CertType::VCEK { 371 | if let Some(cert_hwid) = extensions.get(&SnpOid::HwId.oid()) { 372 | if !check_cert_bytes(cert_hwid, &*att_report.chip_id) { 373 | return Err(anyhow::anyhow!( 374 | "Report TCB ID and Certificate ID mismatch encountered." 375 | )); 376 | } 377 | if !quiet { 378 | println!("Chip ID from certificate matches the attestation report."); 379 | } 380 | } 381 | } 382 | 383 | if proc_model == ProcType::Turin { 384 | if att_report.version < 3 { 385 | return Err(anyhow::anyhow!( 386 | "Turin Attestation is not supported in version 2 of the report." 387 | )); 388 | } 389 | if let Some(cert_fmc) = extensions.get(&SnpOid::Fmc.oid()) { 390 | let fmc = if let Some(fmc) = att_report.reported_tcb.fmc { 391 | fmc 392 | } else { 393 | return Err(anyhow::anyhow!( 394 | "Attestation report TCB FMC is not present in the report. it is expecter for a {} model.", proc_model 395 | )); 396 | }; 397 | 398 | if !check_cert_bytes(cert_fmc, fmc.to_le_bytes().as_slice()) { 399 | return Err(anyhow::anyhow!( 400 | "Report TCB FMC and Certificate FMC mismatch encountered." 401 | )); 402 | } 403 | if !quiet { 404 | println!("Reported TCB FMC from certificate matches the attestation report."); 405 | } 406 | } 407 | } 408 | 409 | Ok(()) 410 | } 411 | 412 | pub fn verify_attestation(args: Args, quiet: bool) -> Result<()> { 413 | // Get attestation report 414 | let att_report = if !args.att_report_path.exists() { 415 | return Err(anyhow::anyhow!("No attestation report was found. Provide an attestation report to request VEK from the KDS.")); 416 | } else { 417 | report::read_report(args.att_report_path.clone()) 418 | .context("Could not open attestation report")? 419 | }; 420 | 421 | let proc_model = if let Some(proc_model) = args.processor_model { 422 | proc_model 423 | } else { 424 | let att_report = report::read_report(args.att_report_path.clone()) 425 | .context("Could not open attestation report")?; 426 | get_processor_model(att_report)? 427 | }; 428 | 429 | // Get VEK and its public key. 430 | let (vek_path, vek_type) = match find_cert_in_dir(&args.certs_dir, "vlek") { 431 | Ok(vlek_path) => (vlek_path, "vlek"), 432 | Err(_) => (find_cert_in_dir(&args.certs_dir, "vcek")?, "vcek"), 433 | }; 434 | 435 | // Get VEK and grab its public key 436 | let vek = convert_path_to_cert(&vek_path, vek_type)?; 437 | 438 | if args.tcb || args.signature { 439 | if args.tcb { 440 | verify_attestation_tcb(vek.clone(), att_report, proc_model, quiet)?; 441 | } 442 | if args.signature { 443 | verify_attestation_signature(vek, att_report, quiet)?; 444 | } 445 | } else { 446 | verify_attestation_tcb(vek.clone(), att_report, proc_model, quiet)?; 447 | verify_attestation_signature(vek, att_report, quiet)?; 448 | } 449 | 450 | Ok(()) 451 | } 452 | 453 | #[cfg(test)] 454 | mod tests { 455 | use super::*; 456 | use x509_parser::{self, certificate::X509Certificate}; 457 | 458 | /// Important note that this is NOT a valid certificate, 459 | /// and the signature will NOT match at all. 460 | fn cert_and_hw_id_legacy() -> ([u8; 1361], [u8; 64]) { 461 | ( 462 | [ 463 | 0x30, 0x82, 0x05, 0x4d, 0x30, 0x82, 0x02, 0xfc, 0xa0, 0x03, 0x02, 0x01, 0x02, 464 | 0x02, 0x01, 0x00, 0x30, 0x46, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 465 | 0x01, 0x01, 0x0a, 0x30, 0x39, 0xa0, 0x0f, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 466 | 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0xa1, 0x1c, 0x30, 0x1a, 467 | 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x08, 0x30, 0x0d, 468 | 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 469 | 0xa2, 0x03, 0x02, 0x01, 0x30, 0xa3, 0x03, 0x02, 0x01, 0x01, 0x30, 0x7b, 0x31, 470 | 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x0b, 0x45, 0x6e, 0x67, 471 | 0x69, 0x6e, 0x65, 0x65, 0x72, 0x69, 0x6e, 0x67, 0x31, 0x0b, 0x30, 0x09, 0x06, 472 | 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x14, 0x30, 0x12, 0x06, 473 | 0x03, 0x55, 0x04, 0x07, 0x0c, 0x0b, 0x53, 0x61, 0x6e, 0x74, 0x61, 0x20, 0x43, 474 | 0x6c, 0x61, 0x72, 0x61, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x08, 475 | 0x0c, 0x02, 0x43, 0x41, 0x31, 0x1f, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x04, 0x0a, 476 | 0x0c, 0x16, 0x41, 0x64, 0x76, 0x61, 0x6e, 0x63, 0x65, 0x64, 0x20, 0x4d, 0x69, 477 | 0x63, 0x72, 0x6f, 0x20, 0x44, 0x65, 0x76, 0x69, 0x63, 0x65, 0x73, 0x31, 0x12, 478 | 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x09, 0x53, 0x45, 0x56, 0x2d, 479 | 0x4d, 0x69, 0x6c, 0x61, 0x6e, 0x30, 0x1e, 0x17, 0x0d, 0x32, 0x33, 0x30, 0x32, 480 | 0x30, 0x33, 0x32, 0x32, 0x34, 0x31, 0x35, 0x35, 0x5a, 0x17, 0x0d, 0x33, 0x30, 481 | 0x30, 0x32, 0x30, 0x33, 0x32, 0x32, 0x34, 0x31, 0x35, 0x35, 0x5a, 0x30, 0x7a, 482 | 0x31, 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x0b, 0x45, 0x6e, 483 | 0x67, 0x69, 0x6e, 0x65, 0x65, 0x72, 0x69, 0x6e, 0x67, 0x31, 0x0b, 0x30, 0x09, 484 | 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x14, 0x30, 0x12, 485 | 0x06, 0x03, 0x55, 0x04, 0x07, 0x0c, 0x0b, 0x53, 0x61, 0x6e, 0x74, 0x61, 0x20, 486 | 0x43, 0x6c, 0x61, 0x72, 0x61, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 487 | 0x08, 0x0c, 0x02, 0x43, 0x41, 0x31, 0x1f, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x04, 488 | 0x0a, 0x0c, 0x16, 0x41, 0x64, 0x76, 0x61, 0x6e, 0x63, 0x65, 0x64, 0x20, 0x4d, 489 | 0x69, 0x63, 0x72, 0x6f, 0x20, 0x44, 0x65, 0x76, 0x69, 0x63, 0x65, 0x73, 0x31, 490 | 0x11, 0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x08, 0x53, 0x45, 0x56, 491 | 0x2d, 0x56, 0x43, 0x45, 0x4b, 0x30, 0x76, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 492 | 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22, 0x03, 493 | 0x62, 0x00, 0x04, 0x70, 0x5b, 0xf7, 0x2b, 0xaa, 0xb4, 0x71, 0xed, 0xbe, 0x34, 494 | 0x4b, 0xbf, 0xaf, 0x15, 0xa3, 0xa2, 0x94, 0x1b, 0xc1, 0x54, 0x54, 0x1c, 0xec, 495 | 0x54, 0x25, 0xac, 0xa8, 0x27, 0xb2, 0x83, 0xd3, 0x9d, 0xdb, 0x68, 0xf9, 0xea, 496 | 0x6b, 0x37, 0x64, 0x6c, 0x5c, 0x92, 0x05, 0x7f, 0x5a, 0x9f, 0x10, 0xe9, 0x07, 497 | 0xfb, 0x33, 0x66, 0x51, 0xe0, 0x91, 0xc2, 0x9f, 0x4f, 0x48, 0xbd, 0x4d, 0x44, 498 | 0x14, 0xb4, 0x89, 0xdd, 0x5b, 0x8e, 0xb0, 0x69, 0x60, 0x75, 0x75, 0x84, 0x2e, 499 | 0x9d, 0x93, 0x1a, 0x7d, 0x95, 0xad, 0xd3, 0xb7, 0xa4, 0x8c, 0x78, 0xad, 0xf5, 500 | 0x5c, 0x9f, 0x56, 0x2e, 0x39, 0x83, 0xdc, 0xc9, 0xa3, 0x82, 0x01, 0x17, 0x30, 501 | 0x82, 0x01, 0x13, 0x30, 0x10, 0x06, 0x09, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x9c, 502 | 0x78, 0x01, 0x01, 0x04, 0x03, 0x02, 0x01, 0x00, 0x30, 0x17, 0x06, 0x09, 0x2b, 503 | 0x06, 0x01, 0x04, 0x01, 0x9c, 0x78, 0x01, 0x02, 0x04, 0x0a, 0x16, 0x08, 0x4d, 504 | 0x69, 0x6c, 0x61, 0x6e, 0x2d, 0x42, 0x30, 0x30, 0x11, 0x06, 0x0a, 0x2b, 0x06, 505 | 0x01, 0x04, 0x01, 0x9c, 0x78, 0x01, 0x03, 0x01, 0x04, 0x03, 0x02, 0x01, 0x03, 506 | 0x30, 0x11, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x9c, 0x78, 0x01, 0x03, 507 | 0x02, 0x04, 0x03, 0x02, 0x01, 0x00, 0x30, 0x11, 0x06, 0x0a, 0x2b, 0x06, 0x01, 508 | 0x04, 0x01, 0x9c, 0x78, 0x01, 0x03, 0x04, 0x04, 0x03, 0x02, 0x01, 0x00, 0x30, 509 | 0x11, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x9c, 0x78, 0x01, 0x03, 0x05, 510 | 0x04, 0x03, 0x02, 0x01, 0x00, 0x30, 0x11, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 511 | 0x01, 0x9c, 0x78, 0x01, 0x03, 0x06, 0x04, 0x03, 0x02, 0x01, 0x00, 0x30, 0x11, 512 | 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x9c, 0x78, 0x01, 0x03, 0x07, 0x04, 513 | 0x03, 0x02, 0x01, 0x00, 0x30, 0x11, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 514 | 0x9c, 0x78, 0x01, 0x03, 0x03, 0x04, 0x03, 0x02, 0x01, 0x0a, 0x30, 0x12, 0x06, 515 | 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x9c, 0x78, 0x01, 0x03, 0x08, 0x04, 0x04, 516 | 0x02, 0x02, 0x00, 0xa9, 0x30, 0x4d, 0x06, 0x09, 0x2b, 0x06, 0x01, 0x04, 0x01, 517 | 0x9c, 0x78, 0x01, 0x04, 0x04, 0x40, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 518 | 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 519 | 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 520 | 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 521 | 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 522 | 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x30, 0x46, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 523 | 0xf7, 0x0d, 0x01, 0x01, 0x0a, 0x30, 0x39, 0xa0, 0x0f, 0x30, 0x0d, 0x06, 0x09, 524 | 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0xa1, 0x1c, 525 | 0x30, 0x1a, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x08, 526 | 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 527 | 0x05, 0x00, 0xa2, 0x03, 0x02, 0x01, 0x30, 0xa3, 0x03, 0x02, 0x01, 0x01, 0x03, 528 | 0x82, 0x02, 0x01, 0x00, 0x31, 0xf0, 0x71, 0xa1, 0xc2, 0x35, 0xee, 0x9f, 0xb5, 529 | 0x87, 0x0d, 0x2e, 0xe9, 0xa2, 0x28, 0x47, 0x1d, 0xb2, 0x5b, 0xfd, 0x74, 0x58, 530 | 0xa2, 0xc9, 0x85, 0xac, 0x4e, 0xad, 0x59, 0x9a, 0xba, 0x93, 0xfb, 0xc0, 0x12, 531 | 0xc3, 0x4b, 0xf5, 0x10, 0x5a, 0xd9, 0xbe, 0x75, 0x1f, 0xeb, 0x5f, 0xed, 0x86, 532 | 0x3f, 0xe7, 0xca, 0xb3, 0xd7, 0x98, 0xa8, 0x97, 0x6e, 0xc8, 0x9e, 0xbf, 0x8f, 533 | 0x2e, 0x0f, 0xab, 0xbd, 0xa6, 0xe6, 0xac, 0xe8, 0x42, 0x2d, 0xd3, 0x1c, 0x7f, 534 | 0x4e, 0xd1, 0x07, 0xd8, 0x9b, 0x3a, 0x9d, 0xdc, 0x59, 0xf5, 0x97, 0x59, 0x96, 535 | 0xbd, 0xc6, 0xc1, 0x70, 0x03, 0x4c, 0xc0, 0xce, 0x40, 0xd9, 0xec, 0x41, 0x27, 536 | 0xe5, 0xf2, 0xa5, 0xf5, 0x6f, 0x40, 0x8c, 0xf9, 0x31, 0x62, 0x0d, 0xc8, 0xd1, 537 | 0xf9, 0x5b, 0x2a, 0x8f, 0x20, 0xc5, 0x77, 0xd8, 0x47, 0x68, 0xc9, 0xaa, 0xc9, 538 | 0xd9, 0x3e, 0x43, 0x69, 0x69, 0xae, 0xce, 0xcc, 0x58, 0xc7, 0x3f, 0xdd, 0x2a, 539 | 0xa3, 0x2c, 0x89, 0x8f, 0x1f, 0x57, 0xe1, 0x0b, 0x50, 0x81, 0x0b, 0x61, 0xb2, 540 | 0x97, 0x4f, 0x33, 0xb1, 0xd9, 0x20, 0x21, 0x5f, 0x1f, 0xac, 0xa0, 0x11, 0xc6, 541 | 0xb5, 0xcd, 0xa7, 0x50, 0xe6, 0xe4, 0x83, 0x54, 0x16, 0xe9, 0x03, 0x92, 0x1f, 542 | 0x4e, 0xb1, 0x58, 0xe8, 0xe6, 0xb0, 0x66, 0xf0, 0x00, 0x9f, 0x42, 0x20, 0xb3, 543 | 0x0e, 0x8d, 0xd2, 0x0b, 0x3b, 0x65, 0xfc, 0x6b, 0x4c, 0x69, 0x63, 0x10, 0xa4, 544 | 0xb5, 0x92, 0xaa, 0x16, 0xfb, 0xf3, 0x6b, 0x4d, 0xf7, 0x7c, 0x69, 0x63, 0x51, 545 | 0x0e, 0x5c, 0x5b, 0x5f, 0x66, 0x56, 0x62, 0x8e, 0x56, 0x69, 0xc0, 0x97, 0xa4, 546 | 0x16, 0x68, 0xc0, 0xe6, 0xb1, 0xbe, 0x9f, 0x7b, 0x28, 0x0b, 0x94, 0x71, 0xc4, 547 | 0x70, 0x82, 0xbb, 0x0b, 0xd4, 0x8b, 0x1a, 0xd9, 0x11, 0x78, 0x2c, 0x0d, 0xe2, 548 | 0xaf, 0x92, 0xd5, 0x88, 0xbf, 0x10, 0xf1, 0x0b, 0x6c, 0x05, 0x16, 0x2f, 0xa0, 549 | 0xef, 0x24, 0xf2, 0xf6, 0x90, 0x0a, 0x88, 0xca, 0x76, 0xc2, 0xb0, 0xf0, 0xff, 550 | 0x52, 0x9a, 0x10, 0xc4, 0x4e, 0xed, 0xab, 0x24, 0x30, 0x87, 0x9f, 0xa4, 0x63, 551 | 0x21, 0x1a, 0xb4, 0xc2, 0xc6, 0x8d, 0x13, 0x02, 0xb1, 0xab, 0x5e, 0x2a, 0x45, 552 | 0xd1, 0x22, 0x6e, 0x7a, 0x93, 0xca, 0xf1, 0x87, 0x5d, 0x21, 0x0c, 0xef, 0x84, 553 | 0xac, 0x54, 0xfd, 0x01, 0xe6, 0x77, 0x0a, 0xf1, 0x33, 0x2d, 0xeb, 0x8a, 0x45, 554 | 0xb0, 0xdf, 0x80, 0x56, 0x2d, 0xaf, 0xee, 0x25, 0x29, 0x55, 0xe2, 0xc9, 0xfb, 555 | 0xce, 0x08, 0x4f, 0x39, 0x47, 0x3f, 0x02, 0x41, 0xab, 0x71, 0xac, 0xd2, 0xd1, 556 | 0xf1, 0xb6, 0x4d, 0xc6, 0xe4, 0x1f, 0xf9, 0x9f, 0x11, 0x56, 0x28, 0xe4, 0xef, 557 | 0x99, 0x70, 0x4c, 0x50, 0x07, 0xef, 0x0d, 0xb1, 0xea, 0xc1, 0xad, 0x3c, 0xb0, 558 | 0xcf, 0xe3, 0x2f, 0x41, 0xcf, 0x3b, 0x1b, 0x1a, 0xfb, 0x61, 0xca, 0x12, 0x42, 559 | 0xaf, 0x27, 0x73, 0x91, 0x37, 0x9e, 0xac, 0xd3, 0x0e, 0xe9, 0xb3, 0x18, 0xbd, 560 | 0xf8, 0xbc, 0x39, 0xf8, 0xcb, 0xbb, 0x6b, 0x56, 0x62, 0x1d, 0x22, 0x8c, 0x0a, 561 | 0x76, 0x44, 0xfb, 0x13, 0x71, 0xb9, 0xff, 0xf9, 0xc3, 0x42, 0x89, 0x89, 0x6e, 562 | 0x63, 0x21, 0x6f, 0x47, 0xdd, 0x56, 0x72, 0xd4, 0x59, 0x14, 0x70, 0x98, 0x88, 563 | 0xf7, 0x52, 0xcb, 0x9d, 0x9a, 0xc3, 0x1c, 0x3d, 0x9b, 0xda, 0xad, 0xec, 0xc4, 564 | 0x78, 0xa7, 0x74, 0xa0, 0x01, 0xab, 0x35, 0x46, 0xa0, 0xba, 0xb1, 0x77, 0xff, 565 | 0x88, 0x71, 0xdc, 0x0a, 0xc3, 0x70, 0x12, 0xb3, 0x18, 0x55, 0x01, 0x3d, 0x83, 566 | 0x28, 0xf8, 0xd7, 0x88, 0x43, 0xfa, 0xc7, 0xa2, 0x3f, 0xcd, 0x2b, 0xcb, 0xcf, 567 | 0x7f, 0x57, 0x6d, 0x3a, 0xc8, 0x14, 0x4e, 0x88, 0x8d, 568 | ], 569 | [ 570 | 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 571 | 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 572 | 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 573 | 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 574 | 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 575 | ], 576 | ) 577 | } 578 | 579 | /// Important note that this is NOT a valid certificate, 580 | /// and the signature will NOT match at all. 581 | fn cert_and_hw_id() -> ([u8; 1362], [u8; 64]) { 582 | ( 583 | [ 584 | 0x30, 0x82, 0x05, 0x4e, 0x30, 0x82, 0x02, 0xfd, 0xa0, 0x03, 0x02, 0x01, 0x02, 585 | 0x02, 0x01, 0x00, 0x30, 0x46, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 586 | 0x01, 0x01, 0x0a, 0x30, 0x39, 0xa0, 0x0f, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 587 | 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0xa1, 0x1c, 0x30, 0x1a, 588 | 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x08, 0x30, 0x0d, 589 | 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 590 | 0xa2, 0x03, 0x02, 0x01, 0x30, 0xa3, 0x03, 0x02, 0x01, 0x01, 0x30, 0x7b, 0x31, 591 | 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x0b, 0x45, 0x6e, 0x67, 592 | 0x69, 0x6e, 0x65, 0x65, 0x72, 0x69, 0x6e, 0x67, 0x31, 0x0b, 0x30, 0x09, 0x06, 593 | 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x14, 0x30, 0x12, 0x06, 594 | 0x03, 0x55, 0x04, 0x07, 0x0c, 0x0b, 0x53, 0x61, 0x6e, 0x74, 0x61, 0x20, 0x43, 595 | 0x6c, 0x61, 0x72, 0x61, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x08, 596 | 0x0c, 0x02, 0x43, 0x41, 0x31, 0x1f, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x04, 0x0a, 597 | 0x0c, 0x16, 0x41, 0x64, 0x76, 0x61, 0x6e, 0x63, 0x65, 0x64, 0x20, 0x4d, 0x69, 598 | 0x63, 0x72, 0x6f, 0x20, 0x44, 0x65, 0x76, 0x69, 0x63, 0x65, 0x73, 0x31, 0x12, 599 | 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x09, 0x53, 0x45, 0x56, 0x2d, 600 | 0x4d, 0x69, 0x6c, 0x61, 0x6e, 0x30, 0x1e, 0x17, 0x0d, 0x32, 0x33, 0x30, 0x38, 601 | 0x31, 0x37, 0x31, 0x34, 0x32, 0x37, 0x30, 0x39, 0x5a, 0x17, 0x0d, 0x33, 0x30, 602 | 0x30, 0x38, 0x31, 0x37, 0x31, 0x34, 0x32, 0x37, 0x30, 0x39, 0x5a, 0x30, 0x7a, 603 | 0x31, 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x0b, 0x45, 0x6e, 604 | 0x67, 0x69, 0x6e, 0x65, 0x65, 0x72, 0x69, 0x6e, 0x67, 0x31, 0x0b, 0x30, 0x09, 605 | 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x14, 0x30, 0x12, 606 | 0x06, 0x03, 0x55, 0x04, 0x07, 0x0c, 0x0b, 0x53, 0x61, 0x6e, 0x74, 0x61, 0x20, 607 | 0x43, 0x6c, 0x61, 0x72, 0x61, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 608 | 0x08, 0x0c, 0x02, 0x43, 0x41, 0x31, 0x1f, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x04, 609 | 0x0a, 0x0c, 0x16, 0x41, 0x64, 0x76, 0x61, 0x6e, 0x63, 0x65, 0x64, 0x20, 0x4d, 610 | 0x69, 0x63, 0x72, 0x6f, 0x20, 0x44, 0x65, 0x76, 0x69, 0x63, 0x65, 0x73, 0x31, 611 | 0x11, 0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x08, 0x53, 0x45, 0x56, 612 | 0x2d, 0x56, 0x43, 0x45, 0x4b, 0x30, 0x76, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 613 | 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22, 0x03, 614 | 0x62, 0x00, 0x04, 0x07, 0x79, 0x5c, 0xaa, 0x60, 0x2f, 0x16, 0x5e, 0x8d, 0x37, 615 | 0x46, 0x93, 0x87, 0xc5, 0x06, 0x4a, 0x52, 0x46, 0xc9, 0x72, 0x0b, 0xdb, 0x7a, 616 | 0xd2, 0x15, 0xb2, 0xc6, 0x61, 0x3c, 0x6f, 0x9b, 0x1e, 0xd4, 0x61, 0x48, 0xee, 617 | 0xbd, 0xdd, 0xef, 0x56, 0xc3, 0xb6, 0x40, 0xdf, 0xd0, 0x5e, 0xbb, 0x3c, 0x0c, 618 | 0x77, 0x2e, 0xea, 0x5a, 0xb0, 0xa9, 0x4b, 0x2e, 0x9a, 0x85, 0x92, 0x08, 0x55, 619 | 0x7c, 0x23, 0xc3, 0x2a, 0xe1, 0xac, 0xb0, 0x2f, 0x3d, 0x59, 0x15, 0xe9, 0xbd, 620 | 0x2e, 0x64, 0xb4, 0x37, 0x73, 0xb8, 0x04, 0xd5, 0xd5, 0x1b, 0x11, 0x5e, 0x60, 621 | 0x1a, 0xc1, 0xf3, 0x86, 0x9d, 0x3e, 0x32, 0xe2, 0xa3, 0x82, 0x01, 0x18, 0x30, 622 | 0x82, 0x01, 0x14, 0x30, 0x10, 0x06, 0x09, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x9c, 623 | 0x78, 0x01, 0x01, 0x04, 0x03, 0x02, 0x01, 0x00, 0x30, 0x17, 0x06, 0x09, 0x2b, 624 | 0x06, 0x01, 0x04, 0x01, 0x9c, 0x78, 0x01, 0x02, 0x04, 0x0a, 0x16, 0x08, 0x4d, 625 | 0x69, 0x6c, 0x61, 0x6e, 0x2d, 0x42, 0x30, 0x30, 0x11, 0x06, 0x0a, 0x2b, 0x06, 626 | 0x01, 0x04, 0x01, 0x9c, 0x78, 0x01, 0x03, 0x01, 0x04, 0x03, 0x02, 0x01, 0x00, 627 | 0x30, 0x11, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x9c, 0x78, 0x01, 0x03, 628 | 0x02, 0x04, 0x03, 0x02, 0x01, 0x00, 0x30, 0x11, 0x06, 0x0a, 0x2b, 0x06, 0x01, 629 | 0x04, 0x01, 0x9c, 0x78, 0x01, 0x03, 0x04, 0x04, 0x03, 0x02, 0x01, 0x00, 0x30, 630 | 0x11, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x9c, 0x78, 0x01, 0x03, 0x05, 631 | 0x04, 0x03, 0x02, 0x01, 0x00, 0x30, 0x11, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 632 | 0x01, 0x9c, 0x78, 0x01, 0x03, 0x06, 0x04, 0x03, 0x02, 0x01, 0x00, 0x30, 0x11, 633 | 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x9c, 0x78, 0x01, 0x03, 0x07, 0x04, 634 | 0x03, 0x02, 0x01, 0x00, 0x30, 0x11, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 635 | 0x9c, 0x78, 0x01, 0x03, 0x03, 0x04, 0x03, 0x02, 0x01, 0x00, 0x30, 0x11, 0x06, 636 | 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x9c, 0x78, 0x01, 0x03, 0x08, 0x04, 0x03, 637 | 0x02, 0x01, 0x1e, 0x30, 0x4f, 0x06, 0x09, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x9c, 638 | 0x78, 0x01, 0x04, 0x04, 0x42, 0x04, 0x40, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 639 | 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 640 | 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 641 | 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 642 | 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 643 | 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x30, 0x46, 0x06, 0x09, 0x2a, 0x86, 0x48, 644 | 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0a, 0x30, 0x39, 0xa0, 0x0f, 0x30, 0x0d, 0x06, 645 | 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0xa1, 646 | 0x1c, 0x30, 0x1a, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 647 | 0x08, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 648 | 0x02, 0x05, 0x00, 0xa2, 0x03, 0x02, 0x01, 0x30, 0xa3, 0x03, 0x02, 0x01, 0x01, 649 | 0x03, 0x82, 0x02, 0x01, 0x00, 0x12, 0x41, 0x24, 0x4a, 0xf3, 0xf8, 0xfb, 0x0f, 650 | 0x70, 0x33, 0x9a, 0x0e, 0x36, 0x9e, 0xf5, 0x89, 0xad, 0x85, 0x6b, 0xed, 0xd1, 651 | 0x25, 0x2d, 0x23, 0x89, 0x16, 0x80, 0xcb, 0xee, 0xbd, 0x70, 0x97, 0x92, 0x24, 652 | 0x76, 0x0b, 0xf9, 0x15, 0x9e, 0x8e, 0x4c, 0xb4, 0x9d, 0x61, 0x9d, 0x3d, 0xfe, 653 | 0x3a, 0xf3, 0x36, 0xb4, 0xc8, 0xb7, 0x56, 0xad, 0x1a, 0x1f, 0x35, 0xf5, 0x36, 654 | 0xf9, 0xb5, 0xed, 0x8f, 0x95, 0x0d, 0x37, 0x0f, 0xa8, 0x89, 0xba, 0x1c, 0x96, 655 | 0x91, 0x97, 0x62, 0x4f, 0xc7, 0x93, 0x87, 0x6d, 0x23, 0xdc, 0xc0, 0xbb, 0xcd, 656 | 0x17, 0x38, 0xae, 0xbd, 0x0d, 0xc4, 0xcc, 0xa4, 0x3f, 0xc8, 0x7d, 0x0d, 0x0b, 657 | 0x5c, 0xf1, 0xba, 0x9b, 0x20, 0x29, 0x95, 0xb0, 0x96, 0x02, 0x4d, 0x9d, 0xcd, 658 | 0x82, 0x0a, 0x60, 0x92, 0x51, 0xa1, 0x3c, 0x69, 0xec, 0x27, 0x81, 0x8e, 0x28, 659 | 0xc7, 0x4e, 0x34, 0xbb, 0x9f, 0xb0, 0x49, 0xc7, 0x6e, 0xe6, 0xb7, 0x6b, 0x1f, 660 | 0x91, 0x20, 0x0a, 0x80, 0xd2, 0x9f, 0x67, 0x24, 0xe0, 0x75, 0x40, 0x9b, 0x4a, 661 | 0xdd, 0xeb, 0xab, 0x34, 0x5f, 0x59, 0x3d, 0x3b, 0x06, 0xf0, 0x4d, 0x7d, 0xf9, 662 | 0x26, 0xeb, 0x35, 0xcb, 0x08, 0x35, 0x7b, 0xbf, 0x02, 0x4e, 0xa5, 0x50, 0xf8, 663 | 0x91, 0xf3, 0x60, 0xed, 0x80, 0x0d, 0xe1, 0x7e, 0x2b, 0x86, 0x75, 0x3d, 0x0c, 664 | 0x83, 0xea, 0x64, 0x50, 0x6c, 0xbd, 0xe2, 0x17, 0x6e, 0x45, 0xaa, 0x10, 0xe8, 665 | 0x84, 0xcc, 0xa1, 0x06, 0xb6, 0x8b, 0xa5, 0x96, 0xb0, 0x83, 0xba, 0x61, 0xe6, 666 | 0xa4, 0x14, 0xd3, 0x26, 0xf3, 0x19, 0x31, 0xbe, 0x40, 0x2a, 0x18, 0x53, 0x58, 667 | 0x75, 0x1d, 0x46, 0xe2, 0xfe, 0x47, 0xa3, 0xa9, 0x39, 0x68, 0xee, 0x37, 0x8f, 668 | 0x57, 0xe6, 0x12, 0x92, 0x34, 0xa6, 0x0a, 0x51, 0xcb, 0x4c, 0xce, 0x54, 0xe2, 669 | 0xbe, 0x8b, 0x8c, 0x02, 0xe5, 0x3c, 0x3a, 0x7b, 0x7f, 0x7b, 0x3b, 0x80, 0x44, 670 | 0x98, 0x9c, 0x52, 0x1d, 0x29, 0x42, 0xce, 0x9f, 0x95, 0xc5, 0x79, 0xbe, 0xd8, 671 | 0x06, 0x71, 0xff, 0xa2, 0x0a, 0xe2, 0x21, 0xa9, 0x59, 0xda, 0xac, 0x05, 0xe8, 672 | 0x2e, 0xa5, 0x1f, 0x01, 0xaf, 0xae, 0xc6, 0x90, 0xbb, 0x5d, 0x7b, 0xa9, 0x84, 673 | 0xff, 0x1c, 0x11, 0x78, 0x07, 0x89, 0x0a, 0x09, 0x4f, 0xc8, 0x4c, 0xb1, 0x7e, 674 | 0x68, 0x12, 0xa6, 0x3d, 0xae, 0x6b, 0x69, 0x8d, 0xc9, 0x03, 0x5f, 0x4d, 0x45, 675 | 0x47, 0xde, 0xf0, 0xa5, 0x1a, 0x19, 0x97, 0x37, 0x0e, 0xe8, 0x8a, 0xd2, 0x30, 676 | 0x07, 0xbf, 0xb4, 0x09, 0x80, 0x93, 0xa4, 0x91, 0x28, 0x40, 0xe3, 0x2c, 0xf3, 677 | 0x46, 0xf0, 0x22, 0xb3, 0xb7, 0xc5, 0x92, 0x69, 0x7a, 0x4d, 0xdb, 0xf7, 0x67, 678 | 0x97, 0x6f, 0x83, 0xcf, 0x5d, 0x29, 0x8b, 0x55, 0x72, 0xd3, 0xa2, 0xcb, 0x65, 679 | 0x21, 0x76, 0x84, 0xed, 0x75, 0xd5, 0xf3, 0x74, 0xff, 0xc1, 0x1a, 0x8d, 0x65, 680 | 0xac, 0x4f, 0xb0, 0x8c, 0x87, 0xae, 0x6a, 0xf0, 0xf9, 0x56, 0x23, 0xfc, 0x29, 681 | 0x5a, 0x1c, 0xd4, 0x12, 0xf9, 0x79, 0x66, 0x97, 0xad, 0x95, 0xc1, 0xa9, 0x0e, 682 | 0xf3, 0x2b, 0x94, 0x17, 0xc3, 0xfd, 0x51, 0x1f, 0x94, 0x35, 0xad, 0xa7, 0xf9, 683 | 0x61, 0x57, 0xf3, 0x67, 0x53, 0x17, 0xc7, 0xee, 0x1f, 0x54, 0x11, 0x1a, 0xd4, 684 | 0xc9, 0x33, 0x4b, 0x3a, 0x71, 0x27, 0xd7, 0xbb, 0x9f, 0x96, 0xba, 0xfa, 0x8a, 685 | 0x9c, 0x1e, 0x80, 0x6e, 0xfa, 0xa5, 0xd6, 0xba, 0xd7, 0x92, 0x71, 0xe9, 0x4e, 686 | 0x82, 0xa9, 0x02, 0x2a, 0x3b, 0xb8, 0x4e, 0x01, 0x53, 0x34, 0xa6, 0x70, 0x61, 687 | 0x56, 0x95, 0x1b, 0x59, 0xfe, 0x46, 0x94, 0x84, 0x8c, 0xa2, 0x2a, 0x16, 0x0c, 688 | 0xc2, 0x59, 0x9e, 0xac, 0xca, 0xa9, 0x93, 0xe6, 0x84, 0xf4, 689 | ], 690 | [ 691 | 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 692 | 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 693 | 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 694 | 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 695 | 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 696 | ], 697 | ) 698 | } 699 | 700 | #[test] 701 | fn test_check_cert_bytes_legacy() { 702 | let (legacy_cert_bytes, val) = cert_and_hw_id_legacy(); 703 | 704 | let dummy_x509: X509Certificate = 705 | X509Certificate::from_der(&legacy_cert_bytes).unwrap().1; 706 | let extensions = dummy_x509.extensions_map().unwrap(); 707 | 708 | let ext = extensions.get(&SnpOid::HwId.oid()).unwrap(); 709 | 710 | assert!(check_cert_bytes(ext, &val)); 711 | } 712 | 713 | #[test] 714 | fn test_check_cert_bytes() { 715 | let (cert_bytes, val) = cert_and_hw_id(); 716 | 717 | let dummy_x509: X509Certificate = X509Certificate::from_der(&cert_bytes).unwrap().1; 718 | let extensions = dummy_x509.extensions_map().unwrap(); 719 | 720 | let ext = extensions.get(&SnpOid::HwId.oid()).unwrap(); 721 | 722 | assert!(check_cert_bytes(ext, val.as_slice())); 723 | } 724 | 725 | #[test] 726 | fn test_check_cert_bytes_integer() { 727 | let (cert_bytes, _) = cert_and_hw_id(); 728 | let val = 0x1Eu8; 729 | let dummy_x509: X509Certificate = X509Certificate::from_der(&cert_bytes).unwrap().1; 730 | let extensions = dummy_x509.extensions_map().unwrap(); 731 | let ext = extensions.get(&SnpOid::Ucode.oid()).unwrap(); 732 | assert!(check_cert_bytes(ext, &val.to_ne_bytes())); 733 | } 734 | } 735 | } 736 | --------------------------------------------------------------------------------