File snphost-0.7.0.obscpio of Package snphost

07070100000000000041ED000000000000000000000003691558B000000000000000000000000000000000000000000000001600000000snphost-0.7.0/.github07070100000001000081A4000000000000000000000001691558B0000000EB000000000000000000000000000000000000002100000000snphost-0.7.0/.github/CODEOWNERS# These owners will be the default owners for everything in
# the repo. Unless a later match takes precedence,
# @global-owner1 and @global-owner2 will be requested for
# review when someone opens a pull request.
*       @tylerfanelli
07070100000002000081A4000000000000000000000001691558B000000053000000000000000000000000000000000000002D00000000snphost-0.7.0/.github/auto_assign-issues.ymladdAssignees: true

assignees:
  - DGonzalezVillal
  - tylerfanelli
  - larrydewey
07070100000003000081A4000000000000000000000001691558B000000202000000000000000000000000000000000000002600000000snphost-0.7.0/.github/auto_assign.yml# Set to true to add reviewers to pull requests
addReviewers: true

# Set to true to add assignees to pull requests
addAssignees: true

# A list of reviewers to be added to pull requests (GitHub user name)
reviewers: 
  - DGonzalezVillal
  - tylerfanelli
  - larrydewey

# A list of keywords to be skipped the process that add reviewers if pull requests include it 
skipKeywords:
  - wip
  - WIP

# A number of reviewers added to the pull request
# Set 0 to add all the reviewers (default: 0)
numberOfReviewers: 2
07070100000004000081A4000000000000000000000001691558B000000064000000000000000000000000000000000000002500000000snphost-0.7.0/.github/dependabot.ymlversion: 2
updates:
- package-ecosystem: "cargo"
  directory: "/"
  schedule:
    interval: "daily"
07070100000005000041ED000000000000000000000002691558B000000000000000000000000000000000000000000000002000000000snphost-0.7.0/.github/workflows07070100000006000081A4000000000000000000000001691558B0000000AA000000000000000000000000000000000000002800000000snphost-0.7.0/.github/workflows/dco.ymlname: Sign-off Check

on:
  pull_request:

permissions:  
  contents: read

jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: KineticCafe/actions-dco@v1
07070100000007000081A4000000000000000000000001691558B0000002DD000000000000000000000000000000000000002900000000snphost-0.7.0/.github/workflows/lint.ymlname: lint

on: [push, pull_request]

permissions:  
  contents: read

jobs:
  fmt:
    name: cargo fmt
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt
          toolchain: nightly
      - run: cargo fmt --all -- --check

  clippy:
    name: cargo clippy
    runs-on: ubuntu-latest
    steps:
      - run: sudo apt-get update
      - run: sudo apt-get install -y asciidoctor
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: clippy
          toolchain: 1.85.0
      - run: cargo clippy --locked --all-targets -- -D clippy::all -D unused_imports -D warnings
07070100000008000081A4000000000000000000000001691558B0000002A5000000000000000000000000000000000000002900000000snphost-0.7.0/.github/workflows/test.ymlname: test

on: [push, pull_request]

permissions:  
  contents: read

jobs:
  test:
    name: ${{ matrix.toolchain }} (${{ matrix.profile.name }})
    runs-on: ubuntu-latest
    steps:
      - run: sudo apt-get update
      - run: sudo apt-get install -y asciidoctor
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          toolchain: ${{ matrix.toolchain }}
      - run: cargo test ${{ matrix.profile.flag }}
    strategy:
      fail-fast: false
      matrix:
        toolchain:
          - nightly
          - beta
          - stable
        profile:
          - name: debug
          - name: release
            flag: --release
07070100000009000081A4000000000000000000000001691558B000000014000000000000000000000000000000000000001900000000snphost-0.7.0/.gitignore/target
*.sh
.vscode0707010000000A000081A4000000000000000000000001691558B000005997000000000000000000000000000000000000001900000000snphost-0.7.0/Cargo.lock# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[package]]
name = "aho-corasick"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [
 "memchr",
]

[[package]]
name = "anstream"
version = "0.6.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d96bd03f33fe50a863e394ee9718a706f988b9079b20c3784fb726e7678b62fb"
dependencies = [
 "anstyle",
 "anstyle-parse",
 "anstyle-query",
 "anstyle-wincon",
 "colorchoice",
 "utf8parse",
]

[[package]]
name = "anstyle"
version = "1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bec1de6f59aedf83baf9ff929c98f2ad654b97c9510f4e70cf6f661d49fd5b1"

[[package]]
name = "anstyle-parse"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c75ac65da39e5fe5ab759307499ddad880d724eed2f6ce5b5e8a26f4f387928c"
dependencies = [
 "utf8parse",
]

[[package]]
name = "anstyle-query"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e28923312444cdd728e4738b3f9c9cac739500909bb3d3c94b43551b16517648"
dependencies = [
 "windows-sys 0.52.0",
]

[[package]]
name = "anstyle-wincon"
version = "3.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1cd54b81ec8d6180e24654d0b371ad22fc3dd083b6ff8ba325b72e00c87660a7"
dependencies = [
 "anstyle",
 "windows-sys 0.52.0",
]

[[package]]
name = "anyhow"
version = "1.0.83"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25bdb32cbbdce2b519a9cd7df3a678443100e265d5e25ca763b7572a5104f5f3"

[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"

[[package]]
name = "bitfield"
version = "0.19.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db1bcd90f88eabbf0cadbfb87a45bceeaebcd3b4bc9e43da379cd2ef0162590d"
dependencies = [
 "bitfield-macros",
]

[[package]]
name = "bitfield-macros"
version = "0.19.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3787a07661997bfc05dd3431e379c0188573f78857080cf682e1393ab8e4d64c"
dependencies = [
 "proc-macro2",
 "quote",
 "syn",
]

[[package]]
name = "bitflags"
version = "2.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967"

[[package]]
name = "byteorder"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"

[[package]]
name = "cc"
version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d32a725bc159af97c3e629873bb9f88fb8cf8a4867175f76dc987815ea07c83b"

[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"

[[package]]
name = "clap"
version = "4.5.51"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c26d721170e0295f191a69bd9a1f93efcdb0aff38684b61ab5750468972e5f5"
dependencies = [
 "clap_builder",
 "clap_derive",
]

[[package]]
name = "clap_builder"
version = "4.5.51"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75835f0c7bf681bfd05abe44e965760fea999a5286c6eb2d59883634fd02011a"
dependencies = [
 "anstream",
 "anstyle",
 "clap_lex",
 "strsim",
]

[[package]]
name = "clap_derive"
version = "4.5.49"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a0b5487afeab2deb2ff4e03a807ad1a03ac532ff5a2cee5d86884440c7f7671"
dependencies = [
 "heck",
 "proc-macro2",
 "quote",
 "syn",
]

[[package]]
name = "clap_lex"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d"

[[package]]
name = "colorchoice"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7"

[[package]]
name = "colorful"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97af0562545a7d7f3d9222fcf909963bec36dcb502afaacab98c6ffac8da47ce"

[[package]]
name = "curl"
version = "0.4.49"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "79fc3b6dd0b87ba36e565715bf9a2ced221311db47bd18011676f24a6066edbc"
dependencies = [
 "curl-sys",
 "libc",
 "openssl-probe",
 "openssl-sys",
 "schannel",
 "socket2",
 "windows-sys 0.59.0",
]

[[package]]
name = "curl-sys"
version = "0.4.83+curl-8.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5830daf304027db10c82632a464879d46a3f7c4ba17a31592657ad16c719b483"
dependencies = [
 "cc",
 "libc",
 "libz-sys",
 "openssl-sys",
 "pkg-config",
 "vcpkg",
 "windows-sys 0.59.0",
]

[[package]]
name = "dirs"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"
dependencies = [
 "dirs-sys",
]

[[package]]
name = "dirs-sys"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
dependencies = [
 "libc",
 "option-ext",
 "redox_users",
 "windows-sys 0.60.0",
]

[[package]]
name = "env_logger"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cd405aab171cb85d6735e5c8d9db038c17d3ca007a4d2c25f337935c3d90580"
dependencies = [
 "humantime",
 "is-terminal",
 "log",
 "regex",
 "termcolor",
]

[[package]]
name = "foreign-types"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
dependencies = [
 "foreign-types-shared",
]

[[package]]
name = "foreign-types-shared"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"

[[package]]
name = "getrandom"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94b22e06ecb0110981051723910cbf0b5f5e09a2062dd7663334ee79a9d1286c"
dependencies = [
 "cfg-if",
 "libc",
 "wasi",
]

[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"

[[package]]
name = "hermit-abi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024"

[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"

[[package]]
name = "humantime"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"

[[package]]
name = "iocuddle"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8972d5be69940353d5347a1344cb375d9b457d6809b428b05bb1ca2fb9ce007"

[[package]]
name = "is-terminal"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f23ff5ef2b80d608d61efee834934d862cd92461afc0560dedf493e4c033738b"
dependencies = [
 "hermit-abi",
 "libc",
 "windows-sys 0.52.0",
]

[[package]]
name = "itoa"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"

[[package]]
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"

[[package]]
name = "libc"
version = "0.2.177"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976"

[[package]]
name = "libredox"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d"
dependencies = [
 "bitflags",
 "libc",
]

[[package]]
name = "libz-sys"
version = "1.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e143b5e666b2695d28f6bca6497720813f699c9602dd7f5cac91008b8ada7f9"
dependencies = [
 "cc",
 "libc",
 "pkg-config",
 "vcpkg",
]

[[package]]
name = "log"
version = "0.4.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c"

[[package]]
name = "memchr"
version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d"

[[package]]
name = "msru"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15a014208ef068fd9eed02eceb063ecba151d9922de4f8b4bb3703ff3d2a3eaa"

[[package]]
name = "once_cell"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"

[[package]]
name = "openssl"
version = "0.10.64"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95a0481286a310808298130d22dd1fef0fa571e05a8f44ec801801e84b216b1f"
dependencies = [
 "bitflags",
 "cfg-if",
 "foreign-types",
 "libc",
 "once_cell",
 "openssl-macros",
 "openssl-sys",
]

[[package]]
name = "openssl-macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
dependencies = [
 "proc-macro2",
 "quote",
 "syn",
]

[[package]]
name = "openssl-probe"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"

[[package]]
name = "openssl-src"
version = "300.5.0+3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8ce546f549326b0e6052b649198487d91320875da901e7bd11a06d1ee3f9c2f"
dependencies = [
 "cc",
]

[[package]]
name = "openssl-sys"
version = "0.9.102"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c597637d56fbc83893a35eb0dd04b2b8e7a50c91e64e9493e398b5df4fb45fa2"
dependencies = [
 "cc",
 "libc",
 "openssl-src",
 "pkg-config",
 "vcpkg",
]

[[package]]
name = "option-ext"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"

[[package]]
name = "pkg-config"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec"

[[package]]
name = "proc-macro2"
version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
dependencies = [
 "unicode-ident",
]

[[package]]
name = "quote"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [
 "proc-macro2",
]

[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
 "getrandom",
]

[[package]]
name = "rdrand"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d92195228612ac8eed47adbc2ed0f04e513a4ccb98175b6f2bd04d963b533655"
dependencies = [
 "rand_core",
]

[[package]]
name = "redox_users"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd6f9d3d47bdd2ad6945c5015a226ec6155d0bcdfd8f7cd29f86b71f8de99d2b"
dependencies = [
 "getrandom",
 "libredox",
 "thiserror",
]

[[package]]
name = "regex"
version = "1.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c"
dependencies = [
 "aho-corasick",
 "memchr",
 "regex-automata",
 "regex-syntax",
]

[[package]]
name = "regex-automata"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea"
dependencies = [
 "aho-corasick",
 "memchr",
 "regex-syntax",
]

[[package]]
name = "regex-syntax"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56"

[[package]]
name = "ryu"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"

[[package]]
name = "schannel"
version = "0.1.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fbc91545643bcf3a0bbb6569265615222618bdf33ce4ffbbd13c4bbd4c093534"
dependencies = [
 "windows-sys 0.52.0",
]

[[package]]
name = "serde"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
 "serde_core",
 "serde_derive",
]

[[package]]
name = "serde_core"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
dependencies = [
 "serde_derive",
]

[[package]]
name = "serde_derive"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
 "proc-macro2",
 "quote",
 "syn",
]

[[package]]
name = "serde_json"
version = "1.0.145"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c"
dependencies = [
 "itoa",
 "memchr",
 "ryu",
 "serde",
 "serde_core",
]

[[package]]
name = "sev"
version = "7.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2ff74d7e7d1cc172f3a45adec74fbeee928d71df095b85aaaf66eb84e1e31e6"
dependencies = [
 "base64",
 "bitfield",
 "bitflags",
 "byteorder",
 "dirs",
 "hex",
 "iocuddle",
 "lazy_static",
 "libc",
 "openssl",
 "rdrand",
 "static_assertions",
 "uuid",
]

[[package]]
name = "snphost"
version = "0.7.0"
dependencies = [
 "anyhow",
 "clap",
 "colorful",
 "curl",
 "env_logger",
 "hex",
 "libc",
 "msru",
 "serde",
 "serde_json",
 "sev",
]

[[package]]
name = "socket2"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "233504af464074f9d066d7b5416c5f9b894a5862a6506e306f7b816cdd6f1807"
dependencies = [
 "libc",
 "windows-sys 0.59.0",
]

[[package]]
name = "static_assertions"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"

[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"

[[package]]
name = "syn"
version = "2.0.102"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6397daf94fa90f058bd0fd88429dd9e5738999cca8d701813c80723add80462"
dependencies = [
 "proc-macro2",
 "quote",
 "unicode-ident",
]

[[package]]
name = "termcolor"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
dependencies = [
 "winapi-util",
]

[[package]]
name = "thiserror"
version = "2.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708"
dependencies = [
 "thiserror-impl",
]

[[package]]
name = "thiserror-impl"
version = "2.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d"
dependencies = [
 "proc-macro2",
 "quote",
 "syn",
]

[[package]]
name = "unicode-ident"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"

[[package]]
name = "utf8parse"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a"

[[package]]
name = "uuid"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8c5f0a0af699448548ad1a2fbf920fb4bee257eae39953ba95cb84891a0446a"
dependencies = [
 "serde",
]

[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"

[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"

[[package]]
name = "winapi-util"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d4cc384e1e73b93bafa6fb4f1df8c41695c8a91cf9c4c64358067d15a7b6c6b"
dependencies = [
 "windows-sys 0.52.0",
]

[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
 "windows-targets 0.52.6",
]

[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
 "windows-targets 0.52.6",
]

[[package]]
name = "windows-sys"
version = "0.60.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e5de29ca9cfd0b9822d586cfdcb4e2fe54d71011b33212473628cef1b23a0fe"
dependencies = [
 "windows-targets 0.53.1",
]

[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
 "windows_aarch64_gnullvm 0.52.6",
 "windows_aarch64_msvc 0.52.6",
 "windows_i686_gnu 0.52.6",
 "windows_i686_gnullvm 0.52.6",
 "windows_i686_msvc 0.52.6",
 "windows_x86_64_gnu 0.52.6",
 "windows_x86_64_gnullvm 0.52.6",
 "windows_x86_64_msvc 0.52.6",
]

[[package]]
name = "windows-targets"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30357ec391cde730f8fbfcdc29adc47518b06504528df977ab5af02ef23fdee9"
dependencies = [
 "windows_aarch64_gnullvm 0.53.0",
 "windows_aarch64_msvc 0.53.0",
 "windows_i686_gnu 0.53.0",
 "windows_i686_gnullvm 0.53.0",
 "windows_i686_msvc 0.53.0",
 "windows_x86_64_gnu 0.53.0",
 "windows_x86_64_gnullvm 0.53.0",
 "windows_x86_64_msvc 0.53.0",
]

[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"

[[package]]
name = "windows_aarch64_gnullvm"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764"

[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"

[[package]]
name = "windows_aarch64_msvc"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c"

[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"

[[package]]
name = "windows_i686_gnu"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3"

[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"

[[package]]
name = "windows_i686_gnullvm"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11"

[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"

[[package]]
name = "windows_i686_msvc"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d"

[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"

[[package]]
name = "windows_x86_64_gnu"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba"

[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"

[[package]]
name = "windows_x86_64_gnullvm"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57"

[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"

[[package]]
name = "windows_x86_64_msvc"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486"
0707010000000B000081A4000000000000000000000001691558B000000505000000000000000000000000000000000000001900000000snphost-0.7.0/Cargo.toml[package]
name = "snphost"
version = "0.7.0"
authors = ["The VirTEE Project Developers"]
edition = "2021"
license = "Apache-2.0"
homepage = "https://github.com/virtee/snphost"
repository = "https://github.com/virtee/snphost"
description = "Administrative utility for AMD SEV-SNP"
readme = "README.md"
keywords = ["amd", "sev", "snp"]
categories = ["os", "os::linux-apis", "parsing", "cryptography", "hardware-support"]
exclude = [ ".gitignore", ".github/*" ]
rust-version = "1.85.0"

[badges]
# See https://doc.rust-lang.org/cargo/reference/manifest.html#the-badges-section
github = { repository = "virtee/snphost", workflow = "test" }
#github = { repository = "virtee/snphost", workflow = "lint" }
maintenance = { status = "actively-developed" }
is-it-maintained-issue-resolution = { repository = "virtee/snphost" }
is-it-maintained-open-issues = { repository = "virtee/snphost" }

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow = "1.0.83"
sev = { version = "7.1.0", features = ['openssl']}
env_logger = "0.10.1"
clap = { version = "4.5", features = [ "derive" ] }
colorful = "0.2.2"
libc = "0.2.177"
curl = "0.4"
msru = "0.2.0"
hex = "0.4"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
0707010000000C000081A4000000000000000000000001691558B000002C5D000000000000000000000000000000000000001600000000snphost-0.7.0/LICENSE                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
0707010000000D000081A4000000000000000000000001691558B000003947000000000000000000000000000000000000001800000000snphost-0.7.0/README.md# snphost

`snphost` is a Command Line Interface (CLI) utility designed for administrators managing AMD SEV-SNP enabled host systems. This tool facilitates interaction with the AMD SEV-SNP firmware device, enabling various operations such as certificate management and attestation processes.

- [Usage](#usage)
  - [1. help](#1-help)
  - [2. export](#2-export)
  - [3. import](#3-import)
  - [4. ok](#4-ok)
  - [5. fetch](#5-fetch)
  - [6. show](#6-show)
  - [7. commit](#7-commit)
  - [8. config](#8-config)
  - [9. verify](#9-verify)
  - [10. vlek-load](#10-vlek-load)
- [Building](#building)
  - [Ubuntu Dependencies](#ubuntu-dependencies)
  - [RHEL and Compatible Distributions Dependencies](#rhel-and-compatible-distributions-dependencies)
  - [openSUSE and Compatible Distributions Dependencies](#opensuse-and-compatible-distributions-dependencies)
- [Common Workflows](#common-workflows)
- [Reporting Bugs](#reporting-bugs)

## Usage

### 1. `help`

Every `snphost` command and subcommand comes with a `--help` option that provides a description of its usage.

**Usage:**

```bash
snphost --help
```

or for a specific subcommand:

```bash
snphost <subcommand> --help
```

### 2. `export`

Deserializes a GHCB formatted cert chain file into individual certificates. The user must specify the desired encoding format (`der` or `pem`) for the certificates, the file where the `GHCB` cert chain is stored in, and the target directory path where to store the deserialized certs. This command is useful for looking at the individual certs that will be used for an extended attestation.

**Usage:**

```bash
snphost export [der|pem] CERT-FILE DIR-PATH
```

**Example:**

```bash
snphost export pem ghcb-certs.bin ./certs
```

### 3. `import`

Converts a certificate chain into a GHCB formatted file for extended attestation. This formatted file can then be provided to QEMU to perform extended attestation on guests. Currently, only the `ASK`, `ASVK`, `ARK`, `VCEK`, and `VLEK` certificates are supported for serialization.

**Usage:**

```bash
snphost import DIR-PATH CERT-FILE
```

**Example:**

```bash
snphost import ./certs ghcb-certs.bin
```
### 4. `ok`

Probes host system to confirm SEV-SNP support.

**Usage:**

```sh
snphost ok
```

### 5. `fetch`

Command to request certificates from the KDS.

**Usage:**

```bash
snphost fetch <subcommand>
```

**Subcommands:**

#### 1. `ca` 

Fetches the Certificate Authority (CA) chain corresponding to the host CPU generation and writes the encoded certificates to the specified directory. Users must specify the desired encoding format (`der` or `pem`). The `--endorser` argument specifies the type of endorsement certificate chain to pull, either VCEK or VLEK (Defaults to VCEK)

**Usage:**

```bash
snphost fetch ca [der|pem] DIR-PATH [--endorser vcek|vlek]
```

**Example:**

```bash
snphost fetch ca pem ./certs -e vcek
```

#### 2. `vek`

Fetches the Versioned Endorsement Key (VEK) corresponding to the host CPU generation and writes the encoded certificate to the specified directory. Users must specify the desired encoding format (`der` or `pem`). The URL of the VEK can be explicitly set. If not explicitly set, the URL will be generated based on firmware data.

**Usage:**

```bash
snphost fetch vek [der|pem] DIR-PATH [url] [--endorser vcek|vlek] [--client-cert <CERT-PATH>] [--private-key <KEY-PATH>]
```

**Example:**

```bash
snphost fetch vek pem ./certs --endorser vcek
```

#### 3. `crl`
Fetches the latest Certificate Revocation List (CRL) for the host CPU generation. The `--endorser` argument specifies the type of attestation signing key (defaults to VCEK).

```sh
snphost fetch crl DIR-PATH [--endorser vcek|vlek]
```

**Example:**

```bash
snphost fetch crl ./crl-dir -e vcek
```

#### 4. `hashsticks`
Fetches the VLEK hashsticks for the machines with identical host CPU generation and the reported TCB version as the host, then saves them to a file called "hashsticks". Users must specify the path to client certificate and the client private key. If there is no `--hwid ${hwid}` or `--json /path/to/json` option specified, the command downloads and prepares the binary VLEK hashstick for the machine running this command unless option `--result ${filename}` is used, which saves the unprocessed KDS response to as `${filename}` under directory `${CERT-PATH}` instead. If option `--hwid ${hwid}` is specified, the command downloads and prepares the VLEK hashstick for the specified hwid. Unprocessed KDS response are also available through option `--result ${filename}`, no binary hashstick will be saved. If option `--json /path/to/json` is specified, the command uses the provided file, which contains a list of hwid whose hashsticks will be fetched, as the request body to query KDS. Unlike no option or `--hwid ${hwid}` option, the whole response from the server will be saved. Users will need to process the response themselves. Users may still use option `--result <filename>` to change the name of the output file. Option `--hwid` and `--json` are mutually exclusive. 

```sh
snphost fetch hashsticks DIR-PATH CERT-PATH KEY-PATH [--hwid <hwid>] [--json <hwid-json>] [--result <filename>]
```
A hwID JSON is needed for option `--json` should contain a JSON structure with an array of hwIDs, an example can be found below
```console
"hwids": [
    "29ea45c..b9a451",
    "46e2c6e..11364f",
]

```

**Example:**

```bash
snphost fetch hashsticks ./hashsticks-dir ./client-cert.pem ./client.key
```

### 6. `show`
Display information about the SEV-SNP platform.

**Usage:**
```sh
snphost show <subcommands>
```

**Subcommands:**

#### 1. `guests`
Lists all active guests.

**Usage:**
```sh
snphost show guests
```

#### 2. `identifier`
Displays the unique CPU identifier.

**Usage:**
```sh
snphost show identifier
```

#### 3. `tcb`
Shows the current platform and reported Trusted Computing Base (TCB) version.

**Usage:**
```sh
snphost show tcb
```

#### 4. `vcek-url`
Displays the URL for fetching VCEK.

**Usage:**
```sh
snphost show vcek-url
```

#### 5. `vlek-url`
Displays the URL for fetching VLEK.

**Usage:**
```sh
snphost show vlek-url
```

#### 6. `hashsticks-url`
Displays the URL for fetching VLEK hashsticks.

**Usage:**
```sh
snphost show hashsticks-url
```

#### 7. `version`

Prints the platform's SEV-SNP firmware version`.

**Usage:**
```sh
snphost show version
```

### 7. `commit`
This command commits the current firmware and SNP platform config versions to the PSP.

**Note: This can't be undone and will not allow rollbacks to older versions.**

**Usage:**
```sh
snphost commit
```

### 8. `config`
Subcommands to manage the host machine's configuration.

**Usage:**
```sh
snphost config <subcommand>
```

**Subcommands**

#### 1. `set`
This command allows the user to change the config of the SNP platform. The user can provide the desired versions of the different TCB paramerters they would like to modify. The command will change the reported values by the PSP. In order to have this changes commited, the user would have to use snphost commit. The user can also provide a new mask-chip value that will change the mask chip bit field values in the config. 

**Usage:**
```sh
snphost config set BOOTLOADER TEE SNP-FW MICROCODE MASK-CHIP [FMC]
```

**Example:**
```sh
snphost config set 10 0 23 25 0
```

#### 2.`reset`
This command resets the SEV-SNP platform. This will clear all persistent data managed by the platform and reset the platform configuration to its last committed version.

**Usage:**
```sh
snphost config reset 
```

**Example:**
```sh
snphost config reset
```

### 9. `verify`

Verify components that can be used in different SNP attestation workflows.

**Usage:**
```sh
snphost verify <subcommand>
```

**Subcommands:**

#### 1. `certs`
Verifies a certificate chain to make sure the correct signatures are applied to each certificate in the chain.

**Usage:**
```bash
snphost verify certs DIR-PATH
```

**Example:**
```bash
snphost verify ./certs
```

#### 2.  `vlek-hashtick`
Verifies thet the TCB values in a vlek-hashstick are valid. This let's a user know that the provided hashstick is valid before trying to loaded in the system.

**Usage:**
```bash
snphost verify vlek-hashtick HASHSTICK-PATH
```

**Example:**
```bash
snphost verify vlek-hashtick hashstick.bin
```

### 10. `vlek-load`
Loads a vlek-hashstick binary into the system so that users can do attestation with a valid VLEK.

**Usage:**
```bash
snphost vlek-load HASHSTICK-FILE
```

**Example:**
```bash
snphost vlek-load hashstick.bin
```

## Building

Some packages may need to be installed on the host system in order to build snphost.

```bash
#Rust Installation
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source "$HOME/.cargo/env"
```

### Ubuntu Dependencies

```bash
sudo apt install build-essential
```

### RHEL and its compatible distributions Dependencies

```bash
sudo dnf groupinstall "Development Tools" "Development Libraries"
```

### openSUSE and its compatible distributions Dependencies

```bash
sudo zypper in -t pattern "devel_basis"
```

After installing the necessary dependencies, clone the `snphost` repository and build the project:

```bash
git clone https://github.com/virtee/snphost.git
cargo build --release
cd snphost/target/release
```

The compiled binary will be located in the `target/release` directory.

## Common Workflows

This section outlines common workflows for configuring and using `snphost` effectively on a host system with AMD SEV-SNP enabled.

### 1. Changing the SNP Configuration

To change the configuration of the SNP firmware, use the `config set` command followed by `commit`.

**Usage:**
```bash
snphost config set BOOTLOADER TEE SNP-FW MICROCODE MASK-CHIP
```
In Turin and higher generations use,
```bash
snphost config set BOOTLOADER TEE SNP-FW MICROCODE MASK-CHIP FMC
```

This command is used to configure the TCB parameters and the Mask Chip value for the AMD SEV-SNP platform. The configuration consists of two main parts: setting the TCB values and setting the Mask Chip value.

#### Part 1. TCB Parameters

BOOTLOADER, TEE, SNP-FW, MICROCODE, FMC (Optional and applicable only to Turin and newer chips.)
To view the current values of these fields, you can run:
```bash
snphost show tcb
```

**Example Output:**

```bash
Reported TCB: TCB Version:
  Microcode:   25
  SNP:         23
  TEE:         0
  Boot Loader: 10
  FMC:         None

Platform TCB: TCB Version:
  Microcode:   25
  SNP:         23
  TEE:         0
  Boot Loader: 10
  FMC:         None
```
With the config set command, you can change these values to an older version, but not to a newer version. Attempting to set a newer version will result in a failure.
Further, the config set command will change the Reported TCB. The Platform TCB will change only when you commit your changes.

#### Part 2. Mask Chip ID

The Mask Chip can be set to a value between 0 and 3, corresponding to its binary counterpart:
```bash
0 - 00
1 - 01
2 - 10
3 - 11
```
These values toggle the MASK-CHIP-KEY and MASK-CHIP-ID settings:

```bash
Bit 0: MASK-CHIP-ID
Bit 1: MASK-CHIP-KEY
```
For example, if you pass 2:

```bash
Bit 0 is 0, meaning MASK-CHIP-ID is disabled.
Bit 1 is 1, meaning MASK-CHIP-KEY is enabled.
```

To set the TCB parameters and Mask Chip, you can use the following command:

**Example:**
```bash
snphost config set 10 0 23 25 0
```

In this example,
```bash
10 is the Bootloader version.
0 is the TEE version.
23 is the SNP Firmware level.
25 is the Microcode level.
0 is the Mask Chip value which disables both mask chip id and mask chip key.
```
This command will update the values.

To commit these changes to firmware, you must use the snphost commit command by running:

```bash
snphost commit
```
*Note: Commit changes config permanently. You can't roll back to your previous version. Do Not commit values unless you are absolutely sure.*

---

### 2. Resetting Config Changes

To discard uncommitted configuration changes and revert to the last committed state:

```bash
snphost config reset
```

**Workflow:**

```bash
snphost config set 10 0 23 25 0
# decide to discard changes
snphost config reset
```

This is useful for reverting accidental or experimental changes before they are made permanent.

---

### 3. Extended Attestation Flow

*Note: This was the workflow used to set-up the host for extended attestation, this functionality is currently unavailable in upstream kernel, and it's subject to change*

This flow demonstrates fetching host certificates, verifying the certs, importing them into the correct gchb format, and passing them to QEMU for extended guest attestation.

```bash
# Fetch certificates from KDS
snphost fetch ca pem ./certs
snphost fetch vek pem ./certs

# Verify the certificate chain (optional but recommended)
snphost verify ./certs

# Serialize to GHCB format for QEMU
snphost import ./certs ghcb-certs.bin

# (Optional) To inspect GHCB-formatted file contents:
snphost export pem ghcb-certs.bin ./decoded-certs
```

**Use with QEMU:**

You can now pass `ghcb-certs.bin` to QEMU via the `sev-snp-certs` option:

```bash
qemu-system-x86_64 \
  ... \
  -object sev-snp-guest,id=sev0,sev-snp-certs=ghcb-certs.bin \
  ...
```

The certificates can now be retrieved in the guest using extended attestation.

---

### Setting up a VLEK

This flow shows how a user would set-up their system to use a VLEK from the host side using the snphost tool:

```bash
### Request the vlek hashstick
### This will place the binary hashsticks file in the hashsticks-dir
snphost fetch hashsticks ./hashsticks-dir ./client-cert.pem ./client.key

### (Optional) Verfiy the hashstick
snphost verify vlek-hashstick ./hashsticks-dir/hashsticks

### Load the hashstick
snphost vlek-load ./hashsticks-dir/hashsticks
```
*Note: In order to complete this process, the user needs to register their machines with AMD in order for AMD to generate a VLEK seed for their servers and then provide them with the appropriate client key and certificate. Please reach out to one of our maintainers to point you in the right direction for this set-up process*


## Reporting Bugs

If you encounter any issues or bugs while using `snphost`, please report them by opening an issue by clicking [here](https://github.com/virtee/snphost/issues). Provide a detailed description of the problem, including steps to reproduce the issue and any relevant system information. This will help the maintainers address the problem more effectively.

---

*Note: This README is structured similarly to the [snpguest README](https://github.com/virtee/snpguest/blob/main/README.md) to maintain consistency across related projects.*
0707010000000E000081A4000000000000000000000001691558B000000636000000000000000000000000000000000000001700000000snphost-0.7.0/build.rs// SPDX-License-Identifier: Apache-2.0

use std::path::Path;
use std::{env, fs, io, process};

const COMMANDS: [&str; 1] = ["snphost"];

fn main() {
    let outdir = match env::var_os("OUT_DIR") {
        Some(outdir) => outdir,
        None => {
            panic!("OUT_DIR environment variable not defined.");
        }
    };
    fs::create_dir_all(&outdir).unwrap();

    for command in COMMANDS {
        if let Err(err) = generate_man_page(&outdir, command) {
            println!(
                "failed to generate man page: {} (is asciidoctor installed?)",
                err
            );
        }
    }
}

fn generate_man_page<P: AsRef<Path>>(outdir: P, command: &str) -> io::Result<()> {
    // If asciidoctor isn't installed, fallback to asciidoc.
    if let Err(err) = process::Command::new("asciidoctor").output() {
        eprintln!("Error from running 'asciidoctor': {}", err);
        return Err(err);
    }

    let outdir = outdir.as_ref();
    let outfile = outdir.join(format!("{}.1", command));
    let cwd = env::current_dir()?;
    let txt_path = cwd.join("docs").join(format!("{}.1.adoc", command));

    let result = process::Command::new("asciidoctor")
        .arg("--doctype")
        .arg("manpage")
        .arg("--backend")
        .arg("manpage")
        .arg("--out-file")
        .arg(&outfile)
        .arg(&txt_path)
        .spawn()?
        .wait()?;
    if !result.success() {
        let msg = format!("'asciidoctor' failed with exit code {:?}", result.code());
        return Err(io::Error::new(io::ErrorKind::Other, msg));
    }
    Ok(())
}
0707010000000F000041ED000000000000000000000002691558B000000000000000000000000000000000000000000000001300000000snphost-0.7.0/docs07070100000010000081A4000000000000000000000001691558B000001EE4000000000000000000000000000000000000002200000000snphost-0.7.0/docs/snphost.1.adocsnphost(1)
==========

NAME
----
snphost - Command line tool for managing the AMD SEV-SNP environment.


SYNOPSIS
--------
*snphost* [GLOBAL_OPTIONS] [_COMMAND_] [_COMMAND_ARGS_] +
*snphost* [_-h, --help_] +
*snphost* *command* *--help*


DESCRIPTION
-----------
snphost is a CLI utility for managing and interacting with the AMD SEV-SNP
firmware device of a host system.


GLOBAL OPTIONS
--------------
*-q, --quiet*:: Don't print any output to the console.


COMMANDS
--------
*snphost export*::
        usage: snphost export [der, pem] CERT-FILE DIR-PATH

        This command exports the SEV-SNP certificate chain to the directory
        provided by DIR-PATH. User has to provide the CERT-FILE where the certs
        are currently stored in (in GHCB format). The user must also specify if 
        they want the certs to be exported in PEM or DER certificate format. These are the only
        two encoding formats supported in this tool. Currently only AMD chain certificates (ARK, ASK, VCEK and VLEK)
        are supported for export.

  options:
        -h, --help      Show a help message.

*snphost import*::
	usage: snphost import DIR-PATH CERT-FILE

        This command imports serialized SEV-SNP certificates to the specified CERT-FILE.
        This CERT-FILE can then be provided to QEMU to perform extended attestation on guest.
        Currently, only the ASK, ARK, VCEK and VLEK are supported to serialize in the tool. 
        Note that there are a few user requirements for this command to work as intended.

        All certificates must be located in the same directory with specific
        names:
                ARK certificate => ark.{pem, der}
                ASK certificate => ask.{pem, der}
                VCEK certificate => vcek.{pem, der}
                VLEK certificate => vlek.{pem, der}

        Not all certificates are needed in the directory, only the ones that a
        user is looking to import to the CERT-FILE.

  options:
        -h, --help      Show a help message

*snphost ok*::
	usage: snphost ok

        This command probes the processor, sysfs, and KVM for AMD SEV-SNP
        related capabilities on the host and emits the results.

 options:
    -h, --help          Show a help message

*snphost commit*::
	usage: snphost commit

        This command commits the current firmware and SNP platform config versions to the PSP.
        This can't be undone and will not allow rollbacks to older versions.

  options:
        -h, --help      Show a help message.

*snphost config set*::
	usage: snphost config set BOOTLOADER TEE SNP-FW MICROCODE MASK-CHIP

        This command allows the user to change the config of the SNP platform. The user can
        provide the desired versions of the different TCB paramerters they would like to modify.
        The command will change the reported values by the PSP. In order to have this changes commited, the 
        user would have to use snphost commit. The user can also provide a new mask-chip value that 
        will change the mask chip bit field values in the config.

        Explanation of the different parmeters:
        BOOTLOADER: Desired reported bootloader version
        TEE: Desired reported PSP OS version
        SNP-FW: Desired reported SNP Firmware level
        MICROCODE: Desired reported patch level of all the cores
        MASK-CHIP: Change the CHIP ID and CHIP KEY settings by changing the MASK-CHIP bits.
                   Valid values range from 0-3 depending on what bits the user wants enabled.

                   Bit[0] -> CHIP ID: Indicates that the CHIP_ID field in the attestation report
                                      will always be 0.
                   Bit[1] -> MASK KEY: Indicates that the VCEK is not used in attestation and guest
                                       key derivation.

                   For example, if the user would like MASK KEY to be enabled and CHIP ID disabled, 
                   then the they would pass in a 2.
	FMC: Current FMC firmware version

  options:
        -h, --help      Show a help message.

*snphost config reset*::
	usage: snphost config reset

        This command resets the SEV-SNP platform. This will clear all
        persistent data managed by the platform and reset the platform configuration
        to its last committed version.

  options:
        -h, --help      Show a help message.

*snphost show*::
        usage: snphost show [guests, identifier, tcb, vcek-url, version ]

        This command describes the state of the SEV-SNP platform. There are
        several platform details to describe:

        Guest count:            snphost show guests
        Platform identifier:    snphost show identifier
        TCB version:            snphost show tcb
        VCEK URL:               snphost show vcek-url
        Firmware version:       snphost show version

 options:
    -h, --help          Show a help message

*snphost verify certs*::
	usage: snphost verify certs DIR-PATH

        This command verifies the full SEV-SNP certificate authority (CA) chain using the certificates stored in the specified directory.
        There are two possible CA chains that can be verified:
        The VCEK chain: ark, ask, vcek.
        Or the VLEK chain: ark, asvk, vlek.
        If both chains are present, the tool will default to verifying the VLEK chain.
        The certificates mus be named as one of the following: ark, ask, asvk, vlek, vcek.
        Followed by the format in which their stored (cert.pem or cert.der).
        Only PEM and DER formats are supported.

 options:
    -h, --help          Show a help message

*snphost verify vlek-hashstick*::
	usage: snphost verify vlek-hashstick HASHSTICK-PATH

        This command verifies the provided VLEK hashstick against the current system configuration.
        There are 2 verifications the hashstick needs to pass before being loaded.
        One relates to the authentication of the actual wrapped vlek content, but this authentication can only be done at fw level.H15
        The other is the matching the reported TCB version in the VLEK vs the one in the system.
        This command compares the TCB version in the hashstick against the TCB version in the system, making sure these fields match.
        Once the TCB is verified the user can load the vlek hashstick using the vlek-load command.

 options:
    -h, --help          Show a help message

*snphost fetch vcek*::
	usage: snphost fetch vcek [ der, pem ] DIR-PATH [url]

        This command fetches the host system's versioned chip endorsement
        key (VCEK) and writes the encoded certificate to the directory at path
        DIR-PATH. Users must specify which format they would like the
        certificate to be encoded in (DER or PEM). The URL of the VCEK can be
        explicitly set. If not explicitly set, the URL will be generated based
        on firmware data.

 options:
    -h, --help          Show a help message

*snphost fetch crl*::
	usage: snphost fetch crl DIR-PATH

        This command fetches the host system's certificate revokation list
        (CRL) and writes the encoded list to the directory at path DIR-PATH.

 options:
    -h, --help          Show a help message

*snphost vlek-load*::
	usage: snphost vlek-load $HASHSTICK-FILE

        This command attempts to load the provided VLEK-HASHSTICK into the system.
        When requesting a VLEK from the KDS, the user should receive both a VLEK certificate and a Wrapped Hashtick.
        This command uses the hashstick file to initiate the load process.
        If the hashstick fails verification, the command will return an error.
        Users are encouraged to pre-verify the hashstick using the 'verify vlek-hashstick' command.

 options:
    -h, --help          Show a help message

REPORTING BUGS
--------------

Please report all bugs to <https://github.com/virtee/snphost/issues>
07070100000011000041ED000000000000000000000003691558B000000000000000000000000000000000000000000000001200000000snphost-0.7.0/src07070100000012000041ED000000000000000000000003691558B000000000000000000000000000000000000000000000001700000000snphost-0.7.0/src/cert07070100000013000081A4000000000000000000000001691558B000000E5E000000000000000000000000000000000000002100000000snphost-0.7.0/src/cert/export.rs// SPDX-License-Identifier: Apache-2.0

use super::*;
use anyhow::{bail, Context, Result};
use sev::{
    certs::snp::Certificate,
    firmware::host::{CertTableEntry, CertType},
};

use std::{
    fs::File,
    io::{BufReader, Read, Write},
    path::PathBuf,
};

// Convert kernel formatted certs into user readable certificates
fn cert_entries(cert_bytes: &mut [u8]) -> Result<Vec<CertTableEntry>> {
    let certs = CertTableEntry::vec_bytes_to_cert_table(cert_bytes)
        .context("Could not convert bytes to certs")?;
    Ok(certs)
}

#[derive(Parser)]
pub struct Export {
    /// The format the certs will be encoded in (PEM or DER)
    #[arg(value_name = "encoding", required = true)]
    pub encoding_fmt: EncodingFormat,

    /// File where the formatted certificates are stored.
    #[arg(value_name = "cert-file", required = true)]
    pub cert_file: PathBuf,

    /// The directory to write the certificates to
    #[arg(value_name = "dir-path", required = true)]
    pub dir_path: PathBuf,
}

pub fn cmd(export: Export) -> Result<()> {
    let (mut ark, mut ask, mut vcek, mut vlek) = (false, false, false, false);

    std::fs::create_dir_all(export.dir_path.clone()).context(format!(
        "unable to find or create directory {}",
        export.dir_path.display()
    ))?;

    // Read the cert file with the kenrel formatted certs
    let cert_file = File::open(export.cert_file)?;
    let mut reader = BufReader::new(cert_file);
    let mut cert_bytes = Vec::new();

    // Read file into vector.
    reader.read_to_end(&mut cert_bytes)?;

    // Create a vec of CertTableEntry (x509 versioned)
    let entries = cert_entries(&mut cert_bytes)?;

    for e in entries {
        let type_id = match e.cert_type {
            CertType::ARK => {
                if ark {
                    bail!("multiple ARKs found");
                }
                ark = true;

                "ark"
            }
            CertType::ASK => {
                if ask {
                    bail!("multiple ASKs found");
                }
                ask = true;

                // Unless VLEK is encountered, assume VCEK style endorsement with ASK.
                if vlek {
                    "asvk"
                } else {
                    "ask"
                }
            }
            CertType::VLEK => {
                if vlek {
                    bail!("multiple VLEKs found");
                }
                vlek = true;

                "vlek"
            }
            CertType::VCEK => {
                if vcek {
                    bail!("multiple VCEKs found");
                }
                vcek = true;

                "vcek"
            }
            _ => continue,
        };

        let certificate = Certificate::from_bytes(&e.data)?;

        // Verify the certificate is in the requested format.
        let formatted_data: Vec<u8> = match export.encoding_fmt {
            EncodingFormat::Der => certificate.to_der()?,
            EncodingFormat::Pem => certificate.to_pem()?,
        };

        // Build out the expected name of the file.
        let name = format!(
            "{}/{}.{}",
            export.dir_path.display(),
            type_id,
            export.encoding_fmt
        );

        // Create the file for writing and open a file-handle.
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(name.clone())?;

        // Write out the contents of the certificate to the file.
        file.write_all(&formatted_data)
            .context(format!("unable to cert data to file {}", name))?;
    }

    Ok(())
}
07070100000014000041ED000000000000000000000002691558B000000000000000000000000000000000000000000000001D00000000snphost-0.7.0/src/cert/fetch07070100000015000081A4000000000000000000000001691558B000000A43000000000000000000000000000000000000002300000000snphost-0.7.0/src/cert/fetch/ca.rs// SPDX-License-Identifier: Apache-2.0

use super::*;
use anyhow::{Context, Result};
use curl::easy::Easy;
use sev::certs::snp::ca::Chain;
use std::{
    fs::{create_dir_all, OpenOptions},
    io::Write,
    path::PathBuf,
};

use super::super::EncodingFormat;
use crate::processor::ProcessorGeneration;

#[derive(Parser)]
pub struct Ca {
    /// The format the certs are encoded in.
    #[arg(value_name = "encoding", required = true)]
    pub encoding_fmt: EncodingFormat,

    /// The directory to write the certificates to
    #[arg(value_name = "dir-path", required = true)]
    pub dir_path: PathBuf,

    /// Specify which endorsement certificate chain to pull, either VCEK or VLEK.
    #[arg(short, long, value_name = "endorser", default_value_t = Endorsement::Vcek, ignore_case = true)]
    pub endorser: Endorsement,
}

fn write_cert(path: &PathBuf, bytes: &[u8]) -> Result<()> {
    let mut file = OpenOptions::new()
        .create(true)
        .truncate(true)
        .write(true)
        .open(path)?;
    file.write_all(bytes)
        .context("Failed to write certificate!")
}

pub fn cmd(ca: Ca) -> Result<()> {
    let ask_type = match ca.endorser {
        Endorsement::Vlek => "asvk",
        _ => "ask",
    };

    let url: String = ca_chain_url(ca.endorser)?;
    let cert_chain: Chain = fetch(&url)?;

    let ((ask_path, ask_bytes), (ark_path, ark_bytes)) = match ca.encoding_fmt {
        EncodingFormat::Der => (
            (format!("{}.der", ask_type), cert_chain.ask.to_der()?),
            ("ark.der", cert_chain.ark.to_der()?),
        ),
        EncodingFormat::Pem => (
            (format!("{}.pem", ask_type), cert_chain.ask.to_pem()?),
            ("ark.pem", cert_chain.ark.to_pem()?),
        ),
    };

    // Create Directory if not exists first, then write the files.
    if !ca.dir_path.exists() {
        create_dir_all(&ca.dir_path)?;
    }

    write_cert(&ca.dir_path.join(ask_path), &ask_bytes)?;
    write_cert(&ca.dir_path.join(ark_path), &ark_bytes)?;

    Ok(())
}

pub fn fetch(url: &str) -> Result<Chain> {
    let mut handle = Easy::new();
    let mut buf: Vec<u8> = Vec::new();

    handle.url(url)?;
    handle.get(true)?;

    let mut transfer = handle.transfer();
    transfer.write_function(|data| {
        buf.extend_from_slice(data);
        Ok(data.len())
    })?;

    transfer.perform()?;
    drop(transfer);

    Ok(Chain::from_pem_bytes(&buf)?)
}

fn ca_chain_url(endorser: Endorsement) -> Result<String> {
    Ok(format!(
        "https://kdsintf.amd.com/{}/v1/{}/cert_chain",
        endorser,
        ProcessorGeneration::current()?.to_kds_url()
    ))
}
07070100000016000081A4000000000000000000000001691558B0000006F4000000000000000000000000000000000000002400000000snphost-0.7.0/src/cert/fetch/crl.rs// SPDX-License-Identifier: Apache-2.0

use super::*;
use crate::processor::ProcessorGeneration;
use anyhow::{Context, Result};
use curl::easy::Easy;
use std::{
    fs::{create_dir_all, OpenOptions},
    io::Write,
    path::PathBuf,
};

#[derive(Parser)]
pub struct Crl {
    /// The directory to write the CRL to
    #[arg(value_name = "dir-path", required = true)]
    pub dir_path: PathBuf,

    /// Specify which endorsement CRL to pull, either VCEK or VLEK.
    #[arg(short, long, value_name = "endorser", default_value_t = Endorsement::Vcek, ignore_case = true)]
    pub endorser: Endorsement,
}

pub fn cmd(crl: Crl) -> Result<()> {
    let url: String = crl_url(crl.endorser)?;
    let bytes: Vec<u8> = fetch(&url)?;

    // Create Directory if not exists first, then write the files.
    if !crl.dir_path.exists() {
        create_dir_all(&crl.dir_path)?;
    }

    let mut file = OpenOptions::new()
        .create(true)
        .truncate(true)
        .write(true)
        .open(crl.dir_path.join(format!(
            "{}.crl",
            ProcessorGeneration::current()?.to_kds_url()
        )))?;

    file.write_all(&bytes)
        .context("Failed to write CRL to directory specified!")
}

fn crl_url(endorser: Endorsement) -> Result<String> {
    Ok(format!(
        "https://kdsintf.amd.com/{}/v1/{}/crl",
        endorser,
        ProcessorGeneration::current()?.to_kds_url()
    ))
}

pub fn fetch(url: &str) -> Result<Vec<u8>> {
    let mut handle = Easy::new();
    let mut buf: Vec<u8> = Vec::new();

    handle.url(url)?;
    handle.get(true)?;

    let mut transfer = handle.transfer();
    transfer.write_function(|data| {
        buf.extend_from_slice(data);
        Ok(data.len())
    })?;

    transfer.perform()?;
    drop(transfer);

    Ok(buf)
}
07070100000017000081A4000000000000000000000001691558B000001625000000000000000000000000000000000000002B00000000snphost-0.7.0/src/cert/fetch/hashsticks.rs// SPDX-License-Identifier: Apache-2.0

use super::*;

use std::{
    collections::HashMap,
    fs::{create_dir_all, read_to_string, OpenOptions},
    io::{Read, Write},
    path::PathBuf,
};

use crate::{firmware, processor::ProcessorGeneration, snp_platform_status};

use anyhow::{Context, Result};
use curl::easy::{Easy, List};
use hex::decode;
use serde::Deserialize;

#[derive(Parser)]
pub struct Hashsticks {
    /// The path of a directory to store the encoded VEK in
    #[arg(value_name = "path", required = true)]
    pub path: PathBuf,

    /// The path of the client certificate
    #[arg(value_name = "client-cert", required = true)]
    pub client_cert: PathBuf,

    /// The path of the client private key
    #[arg(value_name = "private-key", required = true)]
    pub private_key: PathBuf,

    /// The hwid of the requested hash stick
    #[arg(long, value_name = "hwid", conflicts_with = "json")]
    pub hwid: Option<String>,

    /// The path of the request file to request hashsticks for multiple machines.
    #[arg(long, value_name = "json", conflicts_with = "hwid")]
    pub json: Option<PathBuf>,

    /// The filename of the raw KDS response. When specified, no preprocessing will be done.
    #[arg(short, long, value_name = "result")]
    pub result: Option<String>,
}

// Define a struct to deserialize the JSON response
#[derive(Deserialize, Debug)]
struct KDSResponse {
    results: Vec<HashMap<String, String>>,
}

pub fn cmd(hashsticks: Hashsticks) -> Result<()> {
    let url = vlek_hashsticks_url()?;
    let request_body: String;
    let mut preprocess = false;
    let mut hashsticks_filename = "hashsticks".to_string();

    if let Some(body) = hashsticks.json {
        request_body = read_to_string(&body)?;
    } else if let Some(hwid) = hashsticks.hwid {
        (preprocess, request_body) = (true, format!("{{\"hwids\":[\"{}\"]}}", hwid));
    } else {
        let hwid = firmware()?
            .get_identifier()
            .map_err(|e| anyhow::anyhow!(format!("{:?}", e)))
            .context("error detecting identifier on this machine")?;
        (preprocess, request_body) = (true, format!("{{\"hwids\":[\"{}\"]}}", hwid));
    }

    if let Some(name) = hashsticks.result {
        (preprocess, hashsticks_filename) = (false, name);
    }

    let cert = fetch(
        &hashsticks.client_cert,
        &hashsticks.private_key,
        &url,
        &request_body,
    )
    .context(format!("unable to fetch VLEK hashsticks from {}", url))?;

    let mut hashsticks_bytes: Vec<u8> = Vec::new();
    if preprocess {
        let data = serde_json::from_str::<KDSResponse>(cert.as_str())?;
        if let Some(results) = data.results.first() {
            for (hwid, hashstick) in results {
                if hashstick != "not found" {
                    hashsticks_bytes = decode(hashstick)?;
                } else {
                    eprintln!("{}: {}", hwid, hashstick);
                    return Ok(());
                }
            }
        } else {
            eprintln!("malformatted response from KDS");
            return Ok(());
        }
    } else {
        hashsticks_bytes = cert.into_bytes()
    }

    // Create Directory if not exists first, then write the files.
    if !hashsticks.path.exists() {
        create_dir_all(&hashsticks.path)?;
    }

    let mut file = OpenOptions::new()
        .create(true)
        .truncate(true)
        .write(true)
        .open(hashsticks.path.join(hashsticks_filename))?;

    file.write_all(&hashsticks_bytes)?;

    Ok(())
}

pub fn fetch(cert: &PathBuf, key: &PathBuf, url: &str, body: &str) -> Result<String> {
    let mut handle = Easy::new();
    let mut buf: Vec<u8> = Vec::new();

    handle.ssl_cert(cert)?;
    handle.ssl_key(key)?;
    handle.url(url)?;
    handle.post(true)?;

    let mut headers = List::new();
    headers.append("Content-Type: application/json")?;
    handle.http_headers(headers)?;

    handle.post_field_size(body.len() as u64)?;

    let mut transfer = handle.transfer();
    transfer.read_function(|data| Ok(body.as_bytes().read(data).unwrap_or(0)))?;
    transfer.write_function(|data| {
        buf.extend_from_slice(data);
        Ok(data.len())
    })?;

    transfer.perform()?;
    drop(transfer);

    let response_code = handle.response_code()?;
    let response_body = String::from_utf8(buf)?;
    if response_code == 200 {
        Ok(response_body)
    } else {
        Err(anyhow!(response_body))
    }
}

pub fn vlek_hashsticks_url() -> Result<String> {
    let status = snp_platform_status()?;
    let processor_generation = ProcessorGeneration::current()?;
    let hashsticks_endpoint = format!(
        "https://kdsintf.amd.com:444/vlek/v1/{}/hash_sticks",
        processor_generation.to_kds_url(),
    );
    let parameters = format!(
        "blSPL={:02}&teeSPL={:02}&snpSPL={:02}&ucodeSPL={:02}",
        status.reported_tcb_version.bootloader,
        status.reported_tcb_version.tee,
        status.reported_tcb_version.snp,
        status.reported_tcb_version.microcode
    );

    match processor_generation {
        // Turin+ processors also require the FMC parameter to fetch VCEKs.
        ProcessorGeneration::Turin => {
            if let Some(fmc) = status.reported_tcb_version.fmc {
                Ok(format!(
                    "{}?fmcSPL={:02}&{}",
                    hashsticks_endpoint, fmc, parameters
                ))
            } else {
                Err(anyhow!(
                    "Unable to retrieve FMC value from this Turin generation processor"
                ))
            }
        }
        _ => Ok(format!("{}?{}", hashsticks_endpoint, parameters)),
    }
}
07070100000018000081A4000000000000000000000001691558B0000002D0000000000000000000000000000000000000002400000000snphost-0.7.0/src/cert/fetch/mod.rs// SPDX-License-Identifier: Apache-2.0

use super::*;

pub(crate) mod ca;
pub(crate) mod crl;
pub(crate) mod hashsticks;
pub(crate) mod vek;
use anyhow::Result;

#[derive(Subcommand)]
pub enum Fetch {
    /// Fetches the VCEK from the KDS
    Vek(vek::Vek),

    /// Fetches the CA from the KDS
    Ca(ca::Ca),

    /// Fetches the CRL from the KDS
    Crl(crl::Crl),

    /// Fetches the VLEK hashsticks from the KDS
    Hashsticks(hashsticks::Hashsticks),
}

pub fn cmd(fetch: Fetch) -> Result<()> {
    match fetch {
        Fetch::Vek(vek) => vek::cmd(vek),
        Fetch::Ca(ca) => ca::cmd(ca),
        Fetch::Crl(crl) => crl::cmd(crl),
        Fetch::Hashsticks(hashsticks) => hashsticks::cmd(hashsticks),
    }
}
07070100000019000081A4000000000000000000000001691558B00000111B000000000000000000000000000000000000002400000000snphost-0.7.0/src/cert/fetch/vek.rs// SPDX-License-Identifier: Apache-2.0

use super::*;

use std::{
    fs::{create_dir_all, OpenOptions},
    io::Write,
    path::PathBuf,
};

use crate::{firmware, processor::ProcessorGeneration, snp_platform_status};

use anyhow::{Context, Result};
use curl::easy::Easy;
use sev::certs::snp::Certificate;

#[derive(Parser)]
pub struct Vek {
    /// The format in which to encode the certificate
    #[arg(value_name = "encoding", required = true)]
    encoding_fmt: EncodingFormat,

    /// The path of a directory to store the encoded VEK in
    #[arg(value_name = "path", required = true)]
    path: PathBuf,

    /// The type of the endorsement key
    #[arg(short, long, value_name = "endoser", default_value_t = Endorsement::Vcek, ignore_case = true)]
    endorser: Endorsement,

    /// The path of the client certificate
    #[arg(long, value_name = "client-cert")]
    client_cert: Option<PathBuf>,

    /// The path of the client private key
    #[arg(long, value_name = "private-key")]
    private_key: Option<PathBuf>,

    /// The URL of the VEK. If not explicitly set, the URL will be generated based on firmware data
    #[arg(value_name = "url", required = false)]
    url: Option<String>,
}

pub fn cmd(vek: Vek) -> Result<()> {
    let (vek_type, kds_url) = match vek.endorser {
        Endorsement::Vcek => ("vcek", vek_url(Endorsement::Vcek)?),
        Endorsement::Vlek => ("vlek", vek_url(Endorsement::Vlek)?),
    };
    let url = match vek.url {
        Some(url) => url,
        None => kds_url,
    };
    let cert = fetch(&vek.client_cert, &vek.private_key, &url).context(format!(
        "unable to fetch {} from {}",
        vek_type.to_uppercase(),
        url
    ))?;

    let (vek_name, vek_bytes) = match vek.encoding_fmt {
        EncodingFormat::Der => (format!("{}.der", vek_type), cert.to_der()?),
        EncodingFormat::Pem => (format!("{}.pem", vek_type), cert.to_pem()?),
    };

    // Create Directory if not exists first, then write the files.
    if !vek.path.exists() {
        create_dir_all(&vek.path)?;
    }

    let mut file = OpenOptions::new()
        .create(true)
        .truncate(true)
        .write(true)
        .open(vek.path.join(vek_name))?;

    file.write_all(&vek_bytes)?;

    Ok(())
}

pub fn fetch(cert: &Option<PathBuf>, key: &Option<PathBuf>, url: &str) -> Result<Certificate> {
    let mut handle = Easy::new();
    let mut buf: Vec<u8> = Vec::new();

    if let Some(client_cert) = cert {
        handle.ssl_cert(client_cert)?;
    }

    if let Some(private_key) = key {
        handle.ssl_key(private_key)?;
    }

    handle.url(url)?;
    handle.get(true)?;

    let mut transfer = handle.transfer();
    transfer.write_function(|data| {
        buf.extend_from_slice(data);
        Ok(data.len())
    })?;

    transfer.perform()?;
    drop(transfer);

    Ok(Certificate::from_der(buf.as_slice())?)
}

pub fn vek_url(endorser: Endorsement) -> Result<String> {
    let id = firmware()?
        .get_identifier()
        .map_err(|e| anyhow::anyhow!(format!("{:?}", e)))
        .context("error fetching identifier")?;
    let status = snp_platform_status()?;
    let processor_generation = ProcessorGeneration::current()?;
    let vek_endpoint = if endorser == Endorsement::Vcek {
        format!(
            "https://kdsintf.amd.com/vcek/v1/{}/{}",
            processor_generation.to_kds_url(),
            id
        )
    } else {
        format!(
            "https://kdsintf.amd.com:444/vlek/v1/{}/cert",
            processor_generation.to_kds_url(),
        )
    };
    let parameters = format!(
        "blSPL={:02}&teeSPL={:02}&snpSPL={:02}&ucodeSPL={:02}",
        status.reported_tcb_version.bootloader,
        status.reported_tcb_version.tee,
        status.reported_tcb_version.snp,
        status.reported_tcb_version.microcode
    );

    match processor_generation {
        // Turin+ processors also require the FMC parameter to fetch VCEKs.
        ProcessorGeneration::Turin => {
            if let Some(fmc) = status.reported_tcb_version.fmc {
                Ok(format!("{}?fmcSPL={:02}&{}", vek_endpoint, fmc, parameters))
            } else {
                Err(anyhow!(
                    "Unable to retrieve FMC value from this Turin generation processor"
                ))
            }
        }
        _ => Ok(format!("{}?{}", vek_endpoint, parameters)),
    }
}
0707010000001A000081A4000000000000000000000001691558B000000AC1000000000000000000000000000000000000002100000000snphost-0.7.0/src/cert/import.rs// SPDX-License-Identifier: Apache-2.0

use super::*;

use sev::firmware::host::{CertTableEntry, CertType};
use std::{
    fs::{read, read_dir, DirEntry, File},
    io::Write,
    path::PathBuf,
};

use anyhow::{bail, Context, Result};

#[derive(Parser)]
pub struct Import {
    /// The directory where the certificates are stored
    #[arg(value_name = "dir-path", required = true)]
    pub dir_path: PathBuf,

    /// File where the formatted certificates will be stored.
    #[arg(value_name = "cert-file", required = true)]
    pub cert_file: PathBuf,
}

pub fn cmd(import: Import) -> Result<()> {
    if !import.dir_path.exists() {
        bail!(format!("path {} does not exist", import.dir_path.display()));
    }

    let mut table: Vec<CertTableEntry> = vec![];

    // For each cert in the directory convert into a kernel formatted cert and write into file
    for dir_entry in read_dir(import.dir_path.clone())? {
        match dir_entry {
            Ok(de) => table_add_entry(de, &mut table)?,
            Err(_) => {
                bail!(format!(
                    "unable to read directory at path {}",
                    import.dir_path.display()
                ))
            }
        }
    }

    let cert_bytes = CertTableEntry::cert_table_to_vec_bytes(&table)
        .context("Failed to convert certificates to GHCB bytes specification.")?;

    // Write cert into directory
    let mut file = if import.cert_file.exists() {
        std::fs::OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(import.cert_file)
            .context("Unable to overwrite kernel cert file contents")?
    } else {
        File::create(import.cert_file).context("Unable to create kernel cert file")?
    };

    file.write(&cert_bytes)
        .context(format!("unable to write data to file {:?}", file))?;

    Ok(())
}

fn table_add_entry(de: DirEntry, table: &mut Vec<CertTableEntry>) -> Result<()> {
    match entry_get_type(&de.path())? {
        Some(cert_type) => {
            let data = read(de.path())?;

            table.push(CertTableEntry::new(cert_type, data));

            Ok(())
        }
        None => Ok(()),
    }
}

fn entry_get_type(path: &PathBuf) -> Result<Option<CertType>> {
    let file_name_string = path
        .file_name()
        .context(format!("unable to read file at path {:?}", path))?
        .to_string_lossy()
        .into_owned();

    let subs: Vec<&str> = file_name_string.split('.').collect();
    match subs[0] {
        "ark" => Ok(Some(CertType::ARK)),
        "ask" => Ok(Some(CertType::ASK)),
        "asvk" => Ok(Some(CertType::ASK)),
        "vlek" => Ok(Some(CertType::VLEK)),
        "vcek" => Ok(Some(CertType::VCEK)),
        _ => Ok(None),
    }
}
0707010000001B000081A4000000000000000000000001691558B000000706000000000000000000000000000000000000001E00000000snphost-0.7.0/src/cert/mod.rs// SPDX-License-Identifier: Apache-2.0

use super::*;

pub(crate) mod export;
pub(crate) mod fetch;
pub(crate) mod import;
pub(crate) mod verify;

use std::str::FromStr;

use anyhow::{anyhow, Error};

#[derive(ValueEnum, Copy, Clone)]
pub enum EncodingFormat {
    /// Certificates are encoded in DER format
    Der,

    /// Certificates are encoded in PEM format
    Pem,
}

impl std::fmt::Display for EncodingFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Der => "der",
                Self::Pem => "pem",
            }
        )
    }
}

impl FromStr for EncodingFormat {
    type Err = Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "der" => Ok(Self::Der),
            "pem" => Ok(Self::Pem),
            _ => Err(anyhow!("unrecognized certificate encoding format")),
        }
    }
}

#[derive(ValueEnum, Clone, PartialEq)]
pub enum Endorsement {
    /// Versioned Chip Enforsement Key (VCEK)
    Vcek,

    /// Versioned Loaded Enforsement Key (VLEK)
    Vlek,
}

impl std::fmt::Display for Endorsement {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Vcek => "vcek",
                Self::Vlek => "vlek",
            }
        )
    }
}

impl FromStr for Endorsement {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> std::prelude::v1::Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "vcek" => Ok(Self::Vcek),
            "vlek" => Ok(Self::Vlek),
            _ => Err(anyhow::anyhow!("Endorsement type not found!")),
        }
    }
}
0707010000001C000081A4000000000000000000000001691558B000001670000000000000000000000000000000000000002100000000snphost-0.7.0/src/cert/verify.rs// SPDX-License-Identifier: Apache-2.0

use super::*;

use anyhow::{anyhow, Context, Result};
use std::{
    fs::read,
    path::{Path, PathBuf},
};

use colorful::*;
use sev::certs::snp::{ca, Certificate, Chain, Verifiable};

#[derive(Subcommand)]
pub enum Verify {
    /// Verify the certificate chain.
    Certs(certificate_chain::Args),

    /// Verify the VLEK hashstick.
    VlekHashstick(vlek_hashstick::Args),
}

pub fn cmd(verify: Verify, quiet: bool) -> Result<()> {
    match verify {
        Verify::Certs(args) => certificate_chain::cmd(args, quiet),
        Verify::VlekHashstick(args) => vlek_hashstick::cmd(args, quiet),
    }
}

pub fn find_cert_in_dir(dir: &Path, cert: &str) -> Result<PathBuf, anyhow::Error> {
    if dir.join(format!("{cert}.pem")).exists() {
        Ok(dir.join(format!("{cert}.pem")))
    } else if dir.join(format!("{cert}.der")).exists() {
        Ok(dir.join(format!("{cert}.der")))
    } else {
        Err(anyhow::anyhow!("{cert} certificate not found in directory"))
    }
}
mod certificate_chain {

    use super::*;

    #[derive(Parser)]
    pub struct Args {
        /// Path to directory containing certificates.
        #[arg(value_name = "dir-path", required = true)]
        pub dir_path: PathBuf,
    }

    pub fn cmd(verify: Args, quiet: bool) -> Result<()> {
        let ark_path = find_cert_in_dir(&verify.dir_path, "ark")?;
        let (mut vek_type, mut sign_type): (&str, &str) = ("vcek", "ask");
        let (vek_path, ask_path) = match find_cert_in_dir(&verify.dir_path, "vlek") {
            Ok(vlek_path) => {
                (vek_type, sign_type) = ("vlek", "asvk");
                (vlek_path, find_cert_in_dir(&verify.dir_path, sign_type)?)
            }
            Err(_) => (
                find_cert_in_dir(&verify.dir_path, vek_type)?,
                find_cert_in_dir(&verify.dir_path, sign_type)?,
            ),
        };

        // Get a cert chain from directory
        let cert_chain = chain(ark_path, ask_path, vek_path, vek_type, sign_type)?;

        let ark = (&cert_chain.ca.ark, "ARK");
        let ask = (&cert_chain.ca.ask, sign_type);
        let vek = (&cert_chain.vek, vek_type);

        let mut err = true;

        if !quiet {
            println!("\n • = self signed, ⬑ = signs, •̷ = invalid self sign, ⬑̸ = invalid signs\n");
        }

        err |= status(ark, ark, true, quiet);
        err |= status(ark, ask, false, quiet);
        err |= status(ask, vek, false, quiet);

        match err {
            true => Ok(()),
            false => Err(anyhow!("SEV-SNP/CA certificate verification failed")),
        }
    }

    fn status<'a, S>(
        signer: (&'a S, &str),
        signee: (&'a S, &str),
        self_signed: bool,
        quiet: bool,
    ) -> bool
    where
        (&'a S, &'a S): Verifiable,
    {
        let res = (signer.0, signee.0).verify().is_ok();

        if !quiet {
            println!("{}", ssym(res, self_signed, signer.1, signee.1));
        }

        res
    }

    fn ssym(res: bool, self_signed: bool, signer: &str, signee: &str) -> String {
        let sym = match (res, self_signed) {
            (true, true) => "•".green(),
            (true, false) => "⬑".green(),
            (false, true) => "•̷".red(),
            (false, false) => "⬑̸".red(),
        };

        match self_signed {
            true => format!("{} {}", signer, sym),
            false => format!("{} {} {}", signer, sym, signee),
        }
    }

    fn chain(
        ark_path: PathBuf,
        ask_path: PathBuf,
        vek_path: PathBuf,
        vek_type: &str,
        sign_type: &str,
    ) -> Result<Chain> {
        Ok(Chain {
            ca: ca::Chain {
                ark: cert(ark_path, "ARK")?,
                ask: cert(ask_path, sign_type)?,
            },
            vek: cert(vek_path, vek_type)?,
        })
    }

    fn cert(path: PathBuf, name: &str) -> Result<Certificate> {
        Certificate::from_bytes(
            &read(path.clone()).context(format!("unable to read {}", path.display()))?,
        )
        .context(format!(
            "unable to parse {} certificate from {}",
            name,
            path.display()
        ))
    }
}

mod vlek_hashstick {
    use super::*;
    use sev::{firmware::host::WrappedVlekHashstick, parser::ByteParser, Generation};

    #[derive(Parser)]
    pub struct Args {
        /// Path to the VLEK hashstick file.
        #[arg(value_name = "hashstick-file", required = true)]
        pub hashstick_file: PathBuf,
    }

    pub fn cmd(args: Args, quiet: bool) -> Result<()> {
        if !args.hashstick_file.exists() {
            return Err(anyhow::anyhow!(
                "path {} does not exist",
                args.hashstick_file.display()
            ));
        }

        let hashstick_bytes =
            read(&args.hashstick_file).context("Failed to read VLEK hashshtick file")?;

        let generation = Generation::identify_host_generation()?;

        let hashstick = WrappedVlekHashstick::from_bytes_with(&hashstick_bytes, generation)
            .context("Failed to parse VLEK hashshtick")?;

        // Verify the VLEK hashstick
        let reported_tcb = snp_platform_status()?.reported_tcb_version;

        if hashstick.tcb_version != reported_tcb {
            return Err(anyhow::anyhow!(
                "VLEK hashstick TCB version:\n {} \ndoes not match reported TCB version:\n {}",
                hashstick.tcb_version,
                reported_tcb
            ));
        } else if !quiet {
            println!(
                "VLEK hashstick TCB version:\n {} \nmatches reported TCB version:\n {}",
                hashstick.tcb_version, reported_tcb
            );
        }

        Ok(())
    }
}
0707010000001D000081A4000000000000000000000001691558B000000B6B000000000000000000000000000000000000001C00000000snphost-0.7.0/src/config.rs// SPDX-License-Identifier: Apache-2.0

use super::*;
use crate::processor::ProcessorGeneration;
use anyhow::anyhow;

// Different config commands
#[derive(Subcommand)]
pub enum ConfigCmd {
    /// Change the Platform Config (TCB and Mask chip) to the provided values
    Set(set::Args),

    /// Reset the SEV-SNP Config to the last comitted version
    Reset,
}

pub fn cmd(cmd: ConfigCmd) -> Result<()> {
    match cmd {
        ConfigCmd::Set(args) => set::set_config(args),
        ConfigCmd::Reset => reset::reset_config(),
    }
}

mod set {
    use super::*;

    #[derive(Parser)]
    pub struct Args {
        /// Bootloader version
        /// (Unsigned 8-bit Integer)
        #[arg(value_name = "bootloader", required = true)]
        pub bootloader: u8,

        /// PSP OS version (Unsigned 8-bit Integer)
        #[arg(value_name = "tee", required = true)]
        pub tee: u8,

        /// Version of the SNP firmware (Unsigned 8-bit Integer)
        #[arg(value_name = "snp-fw", required = true)]
        pub snp_fw: u8,

        /// Microcode Patch level of all the cores (Unsigned 8-bit Integer)
        #[arg(value_name = "microcode", required = true)]
        pub microcode: u8,

        /// Change mask chip bit field (Unsigned 32-bit Integer) values by providing decimal representation of desired change (0-3). Bit[0]: CHIP_ID, Bit[1]: CHIP_KEY. Both are disabled by default
        #[arg(value_name = "mask-chip", required = true)]
        mask_chip: u32,

        /// FMC firmware version.
        #[arg(value_name = "fmc", required = false)]
        fmc: Option<u8>,
    }

    pub fn set_config(args: Args) -> Result<()> {
        let fmc = match ProcessorGeneration::current()? {
            ProcessorGeneration::Turin => {
                let Some(fmc) = args.fmc else {
                    return Err(anyhow!(
                        "Turin generation processor requires FMC version when setting TCB"
                    ));
                };

                Some(fmc)
            }
            _ => None,
        };

        // Create Tcb with provided values
        let tcb = TcbVersion::new(fmc, args.bootloader, args.tee, args.snp_fw, args.microcode);

        // Create Mask Chip with provided value
        let mask_chip = MaskId(args.mask_chip);

        // Create new Config
        let config = Config::new(tcb, mask_chip);

        // Change Config
        let mut fw = firmware()?;
        fw.snp_set_config(config)
            .map_err(|e| anyhow::anyhow!(format!("{:?}", e)))
            .context("Error setting a new snp config")
    }
}

mod reset {
    use super::*;
    pub fn reset_config() -> Result<()> {
        let mut fw = firmware()?;

        // Provide confing to set_config with all 0s
        fw.snp_set_config(Config::default())
            .map_err(|e| anyhow::anyhow!(format!("{:?}", e)))
            .context("Error resetting SEV-SNP configuration")
    }
}
0707010000001E000081A4000000000000000000000001691558B000000B59000000000000000000000000000000000000001A00000000snphost-0.7.0/src/main.rs// SPDX-License-Identifier: Apache-2.0

#![deny(clippy::all)]

mod cert;
mod config;
mod processor;
mod show;

mod ok;
mod vlek_load;

use cert::{export, fetch, import, verify};

use anyhow::{Context, Result};
use clap::{arg, Parser, Subcommand, ValueEnum};
use sev::firmware::host::*;

#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct SnpHost {
    #[command(subcommand)]
    pub cmd: SnpHostCmd,

    /// Don't print anything to the console
    #[arg(short, long, default_value_t = false)]
    pub quiet: bool,
}

#[allow(clippy::large_enum_variant)]
/// Utilities for managing the SEV-SNP environment
#[derive(Subcommand)]
enum SnpHostCmd {
    /// Display information about the SEV-SNP platform
    #[command(subcommand)]
    Show(show::Show),

    /// Export a certificate chain from a kernel format file to a given directory
    Export(export::Export),

    /// Import a certificate chain to a file
    Import(import::Import),

    /// Probe system for SEV-SNP support
    Ok,

    /// Modify the SNP configuration
    #[command(subcommand)]
    Config(config::ConfigCmd),

    /// Verify a certificate chain
    #[command(subcommand)]
    Verify(verify::Verify),

    /// Retrieve content from the AMD Key Distribution Server (KDS)
    #[command(subcommand)]
    Fetch(fetch::Fetch),

    /// Commit current firmware and TCB versions to PSP
    Commit,

    /// Load a VLEK to the system.
    VlekLoad(vlek_load::VlekLoad),
}

// Commit command
mod commit {
    use super::*;
    pub fn cmd() -> Result<()> {
        firmware()?.snp_commit()?;
        Ok(())
    }
}

fn firmware() -> Result<Firmware> {
    Firmware::open().context("unable to open /dev/sev")
}

fn snp_platform_status() -> Result<SnpPlatformStatus> {
    firmware()?
        .snp_platform_status()
        .map_err(|e| anyhow::anyhow!(format!("{:?}", e)))
        .context("unable to retrieve SNP platform status")
}

fn sev_platform_status() -> Result<Status> {
    firmware()?
        .platform_status()
        .map_err(|e| anyhow::anyhow!(format!("{:?}", e)))
        .context("unable to retrieve SEV platform status")
}

fn main() -> Result<()> {
    env_logger::init();

    let snphost = SnpHost::parse();
    let result = match snphost.cmd {
        SnpHostCmd::Show(show) => show::cmd(show),
        SnpHostCmd::Export(export) => export::cmd(export),
        SnpHostCmd::Import(import) => import::cmd(import),
        SnpHostCmd::Ok => ok::cmd(snphost.quiet),
        SnpHostCmd::Config(subcmd) => config::cmd(subcmd),
        SnpHostCmd::Verify(verify) => verify::cmd(verify, snphost.quiet),
        SnpHostCmd::Fetch(fetch) => fetch::cmd(fetch),
        SnpHostCmd::Commit => commit::cmd(),
        SnpHostCmd::VlekLoad(load) => vlek_load::cmd(load),
    };

    if !snphost.quiet {
        if let Err(ref e) = result {
            eprintln!("ERROR: {}", e);
        }
    }

    result
}
0707010000001F000081A4000000000000000000000001691558B0000082E8000000000000000000000000000000000000001800000000snphost-0.7.0/src/ok.rs// SPDX-License-Identifier: Apache-2.0

use super::*;

use std::{
    arch::x86_64,
    fmt,
    fs::{self, File},
    mem::{transmute, MaybeUninit},
    os::unix::io::AsRawFd,
    str::from_utf8,
};

use colorful::*;

use msru::{Accessor, Msr};

type TestFn = dyn Fn() -> TestResult;

// SEV generation-specific bitmasks.
const SEV_MASK: usize = 1;
const ES_MASK: usize = 1 << 1;
const SNP_MASK: usize = 1 << 2;

struct Test {
    name: &'static str,
    gen_mask: usize,
    run: Box<TestFn>,
    sub: Vec<Test>,
}

struct TestResult {
    name: String,
    stat: TestState,
    mesg: Option<String>,
}

#[derive(PartialEq, Eq)]
enum TestState {
    Pass,
    Skip,
    Fail,
}

enum SevGeneration {
    Sev,
    Es,
    Snp,
}

impl fmt::Display for TestState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            TestState::Pass => format!("{}", "PASS".green()),
            TestState::Skip => format!("{}", "SKIP".yellow()),
            TestState::Fail => format!("{}", "FAIL".red()),
        };

        write!(f, "{}", s)
    }
}

enum SnpStatusTest {
    Tcb,
    Rmp,
    AliasCheck,
    Snp,
}

enum SevStatusTests {
    Sev,
    Firmware,
    SevEs,
}

impl fmt::Display for SnpStatusTest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            SnpStatusTest::Tcb => "Comparing TCB values",
            SnpStatusTest::Rmp => "RMP table initialized",
            SnpStatusTest::AliasCheck => "Alias check",
            SnpStatusTest::Snp => "SNP initialized",
        };
        write!(f, "{}", s)
    }
}

impl fmt::Display for SevStatusTests {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            SevStatusTests::Sev => "SEV initialized",
            SevStatusTests::Firmware => "SEV firmware version",
            SevStatusTests::SevEs => "SEV-ES initialized",
        };
        write!(f, "{}", s)
    }
}

fn collect_tests() -> Vec<Test> {
    let tests = vec![
        Test {
            name: "AMD CPU",
            gen_mask: SEV_MASK,
            run: Box::new(|| {
                let res = unsafe { x86_64::__cpuid(0x0000_0000) };
                let name: [u8; 12] = unsafe { transmute([res.ebx, res.edx, res.ecx]) };
                let name = from_utf8(&name[..]).unwrap_or("ERROR_FOUND");

                let stat = if name == "AuthenticAMD" {
                    TestState::Pass
                } else {
                    TestState::Fail
                };

                TestResult {
                    name: "AMD CPU".to_string(),
                    stat,
                    mesg: None,
                }
            }),
            sub: vec![
                Test {
                    name: "Microcode support",
                    gen_mask: SEV_MASK,
                    run: Box::new(|| {
                        let cpu_name = {
                            let mut bytestr = Vec::with_capacity(48);
                            for cpuid in 0x8000_0002_u32..=0x8000_0004_u32 {
                                let cpuid = unsafe { x86_64::__cpuid(cpuid) };
                                let mut bytes: Vec<u8> =
                                    [cpuid.eax, cpuid.ebx, cpuid.ecx, cpuid.edx]
                                        .iter()
                                        .flat_map(|r| r.to_le_bytes().to_vec())
                                        .collect();
                                bytestr.append(&mut bytes);
                            }
                            String::from_utf8(bytestr)
                                .unwrap_or_else(|_| "ERROR_FOUND".to_string())
                                .trim()
                                .to_string()
                        };

                        let stat = if cpu_name.to_uppercase().contains("EPYC") {
                            TestState::Pass
                        } else {
                            TestState::Fail
                        };

                        TestResult {
                            name: "Microcode support".to_string(),
                            stat,
                            mesg: None,
                        }
                    }),
                    sub: vec![],
                },
                Test {
                    name: "Secure Memory Encryption (SME)",
                    gen_mask: SEV_MASK,
                    run: Box::new(|| {
                        let res = unsafe { x86_64::__cpuid(0x8000_001f) };

                        let stat = if (res.eax & 0x1) != 0 {
                            TestState::Pass
                        } else {
                            TestState::Fail
                        };

                        TestResult {
                            name: "Secure Memory Encryption (SME)".to_string(),
                            stat,
                            mesg: None,
                        }
                    }),
                    sub: vec![Test {
                        name: "SME",
                        gen_mask: SEV_MASK,
                        run: Box::new(sme_test),
                        sub: vec![],
                    }],
                },
                Test {
                    name: "Secure Encrypted Virtualization (SEV)",
                    gen_mask: SEV_MASK,
                    run: Box::new(|| {
                        let res = unsafe { x86_64::__cpuid(0x8000_001f) };

                        let stat = if ((res.eax & 0x1) << 1) != 0 {
                            TestState::Pass
                        } else {
                            TestState::Fail
                        };

                        TestResult {
                            name: "Secure Encrypted Virtualization (SEV)".to_string(),
                            stat,
                            mesg: None,
                        }
                    }),
                    sub: vec![
                        Test {
                            name: "SEV Firmware Version",
                            gen_mask: SNP_MASK,
                            run: Box::new(|| sev_ioctl(SevStatusTests::Firmware)),
                            sub: vec![],
                        },
                        Test {
                            name: "Encrypted State (SEV-ES)",
                            gen_mask: ES_MASK,
                            run: Box::new(|| {
                                let res = unsafe { x86_64::__cpuid(0x8000_001f) };

                                let stat = if ((res.eax & 0x1) << 3) != 0 {
                                    TestState::Pass
                                } else {
                                    TestState::Fail
                                };

                                TestResult {
                                    name: "Encrypted State (SEV-ES)".to_string(),
                                    stat,
                                    mesg: None,
                                }
                            }),
                            sub: vec![Test {
                                name: "SEV-ES initialized",
                                gen_mask: ES_MASK,
                                run: Box::new(|| sev_ioctl(SevStatusTests::SevEs)),
                                sub: vec![],
                            }],
                        },
                        Test {
                            name: "SEV initialized",
                            gen_mask: SNP_MASK,
                            run: Box::new(|| sev_ioctl(SevStatusTests::Sev)),
                            sub: vec![],
                        },
                        Test {
                            name: "Secure Nested Paging (SEV-SNP)",
                            gen_mask: SNP_MASK,
                            run: Box::new(|| {
                                let res = unsafe { x86_64::__cpuid(0x8000_001f) };

                                let stat = if ((res.eax & 0x1) << 4) != 0 {
                                    TestState::Pass
                                } else {
                                    TestState::Fail
                                };

                                TestResult {
                                    name: "Secure Nested Paging (SEV-SNP)".to_string(),
                                    stat,
                                    mesg: None,
                                }
                            }),
                            sub: vec![
                                Test {
                                    name: "VM Permission Levels",
                                    gen_mask: SNP_MASK,
                                    run: Box::new(|| {
                                        let res = unsafe { x86_64::__cpuid(0x8000_001f) };

                                        let stat = if ((res.eax & 0x1) << 5) != 0 {
                                            TestState::Pass
                                        } else {
                                            TestState::Fail
                                        };

                                        TestResult {
                                            name: "VM Permission Levels".to_string(),
                                            stat,
                                            mesg: None,
                                        }
                                    }),
                                    sub: vec![Test {
                                        name: "Number of VMPLs",
                                        gen_mask: SNP_MASK,
                                        run: Box::new(|| {
                                            let res = unsafe { x86_64::__cpuid(0x8000_001f) };
                                            let num_vmpls = (res.ebx & 0xF000) >> 12;

                                            TestResult {
                                                name: "Number of VMPLs".to_string(),
                                                stat: TestState::Pass,
                                                mesg: Some(format!("{}", num_vmpls)),
                                            }
                                        }),
                                        sub: vec![],
                                    }],
                                },
                                Test {
                                    name: "SEV-SNP",
                                    gen_mask: SNP_MASK,
                                    run: Box::new(snp_test),
                                    sub: vec![],
                                },
                                Test {
                                    name: "SNP initialized",
                                    gen_mask: SNP_MASK,
                                    run: Box::new(|| snp_ioctl(SnpStatusTest::Snp)),
                                    sub: vec![
                                        Test {
                                            name: "Read RMP tables",
                                            gen_mask: SNP_MASK,
                                            run: Box::new(get_rmp_address),
                                            sub: vec![],
                                        },
                                        Test {
                                            name: "RMP table initialized",
                                            gen_mask: SNP_MASK,
                                            run: Box::new(|| snp_ioctl(SnpStatusTest::Rmp)),
                                            sub: vec![],
                                        },
                                        Test {
                                            name: "Alias check",
                                            gen_mask: SNP_MASK,
                                            run: Box::new(|| snp_ioctl(SnpStatusTest::AliasCheck)),
                                            sub: vec![],
                                        },
                                    ],
                                },
                            ],
                        },
                        Test {
                            name: "Physical address bit reduction",
                            gen_mask: SEV_MASK,
                            run: Box::new(|| {
                                let res = unsafe { x86_64::__cpuid(0x8000_001f) };
                                let field = (res.ebx & 0b1111_1100_0000) >> 6;

                                TestResult {
                                    name: "Physical address bit reduction".to_string(),
                                    stat: TestState::Pass,
                                    mesg: Some(format!("{}", field)),
                                }
                            }),
                            sub: vec![],
                        },
                        Test {
                            name: "C-bit location",
                            gen_mask: SEV_MASK,
                            run: Box::new(|| {
                                let res = unsafe { x86_64::__cpuid(0x8000_001f) };
                                let field = res.ebx & 0b11_1111;

                                TestResult {
                                    name: "C-bit location".to_string(),
                                    stat: TestState::Pass,
                                    mesg: Some(format!("{}", field)),
                                }
                            }),
                            sub: vec![],
                        },
                        Test {
                            name: "Number of encrypted guests supported simultaneously",
                            gen_mask: SEV_MASK,
                            run: Box::new(|| {
                                let res = unsafe { x86_64::__cpuid(0x8000_001f) };
                                let field = res.ecx;

                                TestResult {
                                    name: "Number of encrypted guests supported simultaneously"
                                        .to_string(),
                                    stat: TestState::Pass,
                                    mesg: Some(format!("{}", field)),
                                }
                            }),
                            sub: vec![],
                        },
                        Test {
                            name: "Minimum ASID value for SEV-enabled, SEV-ES disabled guest",
                            gen_mask: SEV_MASK,
                            run: Box::new(|| {
                                let res = unsafe { x86_64::__cpuid(0x8000_001f) };
                                let field = res.edx;

                                TestResult {
                                    name:
                                        "Minimum ASID value for SEV-enabled, SEV-ES disabled guest"
                                            .to_string(),
                                    stat: TestState::Pass,
                                    mesg: Some(format!("{}", field)),
                                }
                            }),
                            sub: vec![],
                        },
                        Test {
                            name: "/dev/sev readable",
                            gen_mask: SEV_MASK,
                            run: Box::new(dev_sev_r),
                            sub: vec![],
                        },
                        Test {
                            name: "/dev/sev writable",
                            gen_mask: SEV_MASK,
                            run: Box::new(dev_sev_w),
                            sub: vec![],
                        },
                    ],
                },
                Test {
                    name: "Page flush MSR",
                    gen_mask: SEV_MASK,
                    run: Box::new(|| {
                        let res = unsafe { x86_64::__cpuid(0x8000_001f) };

                        let msr_flag = if ((res.eax & 0x1) << 2) != 0 {
                            "ENABLED".green()
                        } else {
                            "DISABLED".yellow()
                        };

                        let name = format!("Page flush MSR: {}", msr_flag);

                        TestResult {
                            name,
                            /*
                             * Page flush MSR can be enabled/disabled.
                             * Therefore, if the flag is disabled, it doesn't
                             * necessarily mean that Page flush MSR *isn't*
                             * supported, but rather that it is supported yet
                             * currently disabled. So instead of returning
                             * TestState::Fail (indicating that Page flush MSR
                             * isn't supported), return TestState::Pass and
                             * indicate to the caller whether it is enabled or
                             * disabled.
                             */
                            stat: TestState::Pass,
                            mesg: None,
                        }
                    }),
                    sub: vec![],
                },
            ],
        },
        Test {
            name: "KVM Support",
            gen_mask: SEV_MASK,
            run: Box::new(has_kvm_support),
            sub: vec![
                Test {
                    name: "SEV enabled in KVM",
                    gen_mask: SEV_MASK,
                    run: Box::new(|| sev_enabled_in_kvm(SevGeneration::Sev)),
                    sub: vec![],
                },
                Test {
                    name: "SEV-ES enabled in KVM",
                    gen_mask: ES_MASK,
                    run: Box::new(|| sev_enabled_in_kvm(SevGeneration::Es)),
                    sub: vec![],
                },
                Test {
                    name: "SEV-SNP enabled in KVM",
                    gen_mask: SNP_MASK,
                    run: Box::new(|| sev_enabled_in_kvm(SevGeneration::Snp)),
                    sub: vec![],
                },
            ],
        },
        Test {
            name: "memlock limit",
            gen_mask: SEV_MASK,
            run: Box::new(memlock_rlimit),
            sub: vec![],
        },
        Test {
            name: "Compare TCB values",
            gen_mask: SNP_MASK,
            run: Box::new(|| snp_ioctl(SnpStatusTest::Tcb)),
            sub: vec![],
        },
    ];

    tests
}

const INDENT: usize = 2;

pub fn cmd(quiet: bool) -> Result<()> {
    let tests = collect_tests();

    if run_test(&tests, 0, quiet, SEV_MASK | ES_MASK | SNP_MASK) {
        Ok(())
    } else {
        Err(anyhow::anyhow!(
            "One or more tests in snphost ok reported a failure"
        ))
    }
}

fn run_test(tests: &[Test], level: usize, quiet: bool, mask: usize) -> bool {
    let mut passed = true;

    for t in tests {
        // Skip tests that aren't included in the specified generation.
        if (t.gen_mask & mask) != t.gen_mask {
            test_gen_not_included(t, level, quiet);
            continue;
        }

        let res = (t.run)();
        emit_result(&res, level, quiet);
        match res.stat {
            TestState::Pass => {
                if !run_test(&t.sub, level + INDENT, quiet, mask) {
                    passed = false;
                }
            }
            TestState::Fail => {
                passed = false;
                emit_skip(&t.sub, level + INDENT, quiet);
            }
            // Skipped tests are marked as skip before recursing. They are just emitted and not actually processed.
            TestState::Skip => unreachable!(),
        }
    }

    passed
}

fn emit_result(res: &TestResult, level: usize, quiet: bool) {
    if !quiet {
        let msg = match &res.mesg {
            Some(m) => format!(": {}", m),
            None => "".to_string(),
        };
        println!(
            "[ {:^4} ] {:width$}- {}{}",
            format!("{}", res.stat),
            "",
            res.name,
            msg,
            width = level
        )
    }
}

fn test_gen_not_included(test: &Test, level: usize, quiet: bool) {
    if !quiet {
        let tr_skip = TestResult {
            name: test.name.to_string(),
            stat: TestState::Skip,
            mesg: None,
        };

        println!(
            "[ {:^4} ] {:width$}- {}",
            format!("{}", tr_skip.stat),
            "",
            tr_skip.name,
            width = level
        );
        emit_skip(&test.sub, level + INDENT, quiet);
    }
}

fn emit_skip(tests: &[Test], level: usize, quiet: bool) {
    if !quiet {
        for t in tests {
            let tr_skip = TestResult {
                name: t.name.to_string(),
                stat: TestState::Skip,
                mesg: None,
            };

            println!(
                "[ {:^4} ] {:width$}- {}",
                format!("{}", tr_skip.stat),
                "",
                tr_skip.name,
                width = level
            );
            emit_skip(&t.sub, level + INDENT, quiet);
        }
    }
}

fn dev_sev_r() -> TestResult {
    let (stat, mesg) = match dev_sev_rw(fs::OpenOptions::new().read(true)) {
        Ok(_) => (TestState::Pass, None),
        Err(e) => (TestState::Fail, Some(format!("Not readable: {}", e))),
    };

    TestResult {
        name: "/dev/sev readable".to_string(),
        stat,
        mesg,
    }
}

fn dev_sev_w() -> TestResult {
    let (stat, mesg) = match dev_sev_rw(fs::OpenOptions::new().write(true)) {
        Ok(_) => (TestState::Pass, None),
        Err(e) => (TestState::Fail, Some(format!("Not writable: {}", e))),
    };

    TestResult {
        name: "/dev/sev writable".to_string(),
        stat,
        mesg,
    }
}

fn dev_sev_rw(file: &fs::OpenOptions) -> Result<()> {
    let path = "/dev/sev";

    match file.open(path) {
        Ok(_) => Ok(()),
        Err(e) => Err(anyhow::Error::new(Box::new(e))),
    }
}

fn has_kvm_support() -> TestResult {
    let path = "/dev/kvm";

    let (stat, mesg) = match File::open(path) {
        Ok(kvm) => {
            let api_version = unsafe { libc::ioctl(kvm.as_raw_fd(), 0xAE00, 0) };
            if api_version < 0 {
                (
                    TestState::Fail,
                    "Error - accessing KVM device node failed".to_string(),
                )
            } else {
                (TestState::Pass, format!("API version: {}", api_version))
            }
        }
        Err(e) => (TestState::Fail, format!("Error reading {}: ({})", path, e)),
    };

    TestResult {
        name: "KVM supported".to_string(),
        stat,
        mesg: Some(mesg),
    }
}

fn sev_enabled_in_kvm(gen: SevGeneration) -> TestResult {
    let path_loc = match gen {
        SevGeneration::Sev => "/sys/module/kvm_amd/parameters/sev",
        SevGeneration::Es => "/sys/module/kvm_amd/parameters/sev_es",
        SevGeneration::Snp => "/sys/module/kvm_amd/parameters/sev_snp",
    };
    let path = std::path::Path::new(path_loc);

    let (stat, mesg) = if path.exists() {
        match std::fs::read_to_string(path_loc) {
            Ok(result) => {
                if result.trim() == "1" || result.trim() == "Y" {
                    (TestState::Pass, None)
                } else {
                    (
                        TestState::Fail,
                        Some(format!(
                            "Error - contents read from {}: {}",
                            path_loc,
                            result.trim()
                        )),
                    )
                }
            }
            Err(e) => (
                TestState::Fail,
                Some(format!("Error - (unable to read {}): {}", path_loc, e,)),
            ),
        }
    } else {
        (
            TestState::Fail,
            Some(format!("Error - {} does not exist", path_loc)),
        )
    };

    TestResult {
        name: match gen {
            SevGeneration::Sev => "SEV enabled in KVM",
            SevGeneration::Es => "SEV-ES enabled in KVM",
            SevGeneration::Snp => "SEV-SNP enabled in KVM",
        }
        .to_string(),
        stat,
        mesg,
    }
}

fn memlock_rlimit() -> TestResult {
    let mut rlimit = MaybeUninit::uninit();
    let res = unsafe { libc::getrlimit(libc::RLIMIT_MEMLOCK, rlimit.as_mut_ptr()) };

    let (stat, mesg) = if res == 0 {
        let r = unsafe { rlimit.assume_init() };

        (
            TestState::Pass,
            format!("Soft: {} | Hard: {}", r.rlim_cur, r.rlim_max),
        )
    } else {
        (
            TestState::Fail,
            "Unable to retrieve memlock resource limits".to_string(),
        )
    };

    TestResult {
        name: "Memlock resource limit".to_string(),
        stat,
        mesg: Some(mesg),
    }
}

fn msr_bit_read(reg: u32, cpu: u16) -> Result<u64, anyhow::Error> {
    let mut msr = Msr::new(reg, cpu).context("Error Reading MSR")?;
    let raw_value = msr.read()?;
    Ok(raw_value)
}

fn sme_test() -> TestResult {
    let raw_value = match msr_bit_read(0xC0010010, 0) {
        Ok(raw) => raw,
        Err(e) => {
            return TestResult {
                name: "SME".to_string(),
                stat: TestState::Fail,
                mesg: format!("MSR read failed: {}", e).into(),
            }
        }
    };
    let (testres, mesg) = match (raw_value >> 23) & 1 {
        1 => (TestState::Pass, "Enabled in MSR"),
        0 => (TestState::Fail, "Disabled in MSR"),
        _ => unreachable!(),
    };
    TestResult {
        name: "SME".to_string(),
        stat: testres,
        mesg: Some(mesg.to_string()),
    }
}

fn snp_test() -> TestResult {
    let raw_value = match msr_bit_read(0xC0010010, 0) {
        Ok(raw) => raw,
        Err(e) => {
            return TestResult {
                name: "SNP".to_string(),
                stat: TestState::Fail,
                mesg: format!("MSR read failed: {}", e).into(),
            }
        }
    };
    let (testres, mesg) = match (raw_value >> 24) & 1 {
        1 => (TestState::Pass, "Enabled in MSR"),
        0 => (TestState::Fail, "Disabled in MSR"),
        _ => unreachable!(),
    };
    TestResult {
        name: "SNP".to_string(),
        stat: testres,
        mesg: Some(mesg.to_string()),
    }
}

fn get_rmp_address() -> TestResult {
    let rmp_base = match msr_bit_read(0xC0010132, 0) {
        Ok(raw) => raw,
        Err(e) => {
            return TestResult {
                name: "Reading RMP table".to_string(),
                stat: TestState::Fail,
                mesg: format!("Failed to read the desired MSR: {}", e).into(),
            }
        }
    };
    let rmp_end = match msr_bit_read(0xC0010133, 0) {
        Ok(raw) => raw,
        Err(e) => {
            return TestResult {
                name: "Reading RMP table".to_string(),
                stat: TestState::Fail,
                mesg: format!("Failed to read the desired MSR: {}", e).into(),
            }
        }
    };
    if rmp_base == 0 || rmp_end == 0 {
        TestResult {
            name: "Reading RMP table".to_string(),
            stat: TestState::Fail,
            mesg: Some("RMP table was not read successfully".into()),
        }
    } else {
        TestResult {
            name: "RMP table addresses".to_string(),
            stat: TestState::Pass,
            mesg: format!("0x{:x} - 0x{:x}", rmp_base, rmp_end).into(),
        }
    }
}

fn snp_ioctl(test: SnpStatusTest) -> TestResult {
    let status = match snp_platform_status() {
        Ok(stat) => stat,
        Err(e) => {
            return TestResult {
                name: test.to_string(),
                stat: TestState::Fail,
                mesg: Some(format!("Failed to get SNP Platform status {e}")),
            }
        }
    };

    match test {
        SnpStatusTest::Tcb => {
            if status.platform_tcb_version == status.reported_tcb_version {
                TestResult{
                            name: format!("{}", SnpStatusTest::Tcb),
                            stat: TestState::Pass,
                            mesg: format!("TCB versions match \n\n Platform TCB version: {} \n Reported TCB version: {}", 
                                        status.platform_tcb_version, status.reported_tcb_version).into()
                        }
            } else {
                TestResult {
                    name: format!("{}", SnpStatusTest::Tcb),
                    stat: TestState::Fail,
                    mesg: format!("The TCB versions did NOT match \n\n Platform TCB version: {} \n Reported TCB version: {}", 
                                    status.platform_tcb_version, status.reported_tcb_version).into(),
                }
            }
        }
        SnpStatusTest::Rmp => {
            if status.is_rmp_init.is_rmp_init() {
                TestResult {
                    name: format!("{}", SnpStatusTest::Rmp),
                    stat: TestState::Pass,
                    mesg: None,
                }
            } else {
                TestResult {
                    name: format!("{}", SnpStatusTest::Rmp),
                    stat: TestState::Fail,
                    mesg: None,
                }
            }
        }
        SnpStatusTest::AliasCheck => {
            if status.is_rmp_init.alias_check_complete() {
                TestResult {
                    name: format!("{}", SnpStatusTest::AliasCheck),
                    stat: TestState::Pass,
                    mesg: Some(
                        "Completed since last system update, no aliasing addresses".to_string(),
                    ),
                }
            } else {
                TestResult {
                    name: format!("{}", SnpStatusTest::AliasCheck),
                    stat: TestState::Fail,
                    mesg: None,
                }
            }
        }
        SnpStatusTest::Snp => {
            if status.state == 1 {
                TestResult {
                    name: format!("{}", SnpStatusTest::Snp),
                    stat: TestState::Pass,
                    mesg: None,
                }
            } else {
                TestResult {
                    name: format!("{}", SnpStatusTest::Snp),
                    stat: TestState::Fail,
                    mesg: None,
                }
            }
        }
    }
}

fn sev_ioctl(test: SevStatusTests) -> TestResult {
    let status = match sev_platform_status() {
        Ok(stat) => stat,
        Err(e) => {
            return TestResult {
                name: test.to_string(),
                stat: TestState::Fail,
                mesg: Some(format!("Failed to get SEV Platform Status {e}")),
            }
        }
    };
    match test {
        SevStatusTests::Sev => {
            if status.state == State::Working {
                TestResult {
                    name: format!("{}", SevStatusTests::Sev),
                    stat: TestState::Pass,
                    mesg: Some("Initialized, currently running a guest".to_string()),
                }
            } else if status.state == State::Initialized {
                TestResult {
                    name: format!("{}", SevStatusTests::Sev),
                    stat: TestState::Pass,
                    mesg: Some("Initialized, no guests running".to_string()),
                }
            } else {
                TestResult {
                    name: format!("{}", SevStatusTests::Sev),
                    stat: TestState::Fail,
                    mesg: Some("Uninitialized".to_string()),
                }
            }
        }

        SevStatusTests::Firmware => {
            if status.build.version == 0.into() {
                TestResult {
                    name: format!("{}", SevStatusTests::Firmware),
                    stat: TestState::Fail,
                    mesg: Some(format!(
                        "Invalid Firmware version: {}",
                        status.build.version
                    )),
                }
            } else if status.build.version.minor < 51 {
                TestResult {
                    name: format!("{}", SevStatusTests::Firmware),
                    stat: TestState::Fail,
                    mesg: format!(
                        "SEV firmware version needs to be at least 1.51, 
                            current firmware version: {}",
                        status.build.version
                    )
                    .into(),
                }
            } else {
                TestResult {
                    name: format!("{}", SevStatusTests::Firmware),
                    stat: TestState::Pass,
                    mesg: format!("{}", status.build.version).into(),
                }
            }
        }

        SevStatusTests::SevEs => {
            let res = match (status.flags.bits() >> 8) & 1 {
                1 => TestState::Pass,
                0 => TestState::Fail,
                _ => unreachable!(),
            };
            TestResult {
                name: format!("{}", SevStatusTests::SevEs),
                stat: res,
                mesg: None,
            }
        }
    }
}
07070100000020000081A4000000000000000000000001691558B000000CFB000000000000000000000000000000000000001F00000000snphost-0.7.0/src/processor.rs// SPDX-License-Identifier: Apache-2.0

use anyhow::{anyhow, Result};
use std::arch::x86_64;

pub enum ProcessorGeneration {
    Milan,
    Genoa,
    Bergamo,
    Siena,
    Turin,
}

impl ProcessorGeneration {
    // Get the SEV generation of the processor currently running on the machine.
    // To do this, we execute a CPUID (label 0x80000001) and read the EAX
    // register as an array of bytes (each byte representing 8 bits of a 32-bit
    // value, thus the array is 4 bytes long). The formatting for these values is
    // as follows:
    //
    //  Base model:         bits 4:7
    //  Base family:        bits 8:11
    //  Extended model:     bits 16:19
    //  Extended family:    bits 20:27
    //
    // Extract the bit values from the array, and use them to calculate the MODEL
    // and FAMILY of the processor.
    //
    // The family calculation is as follows:
    //
    //      FAMILY = Base family + Extended family
    //
    // The model calculation is a follows:
    //
    //      MODEL = Base model | (Extended model << 4)
    //
    // Compare these values with the models and families of known processor generations to
    // determine which generation the current processor is a part of.
    pub(crate) fn current() -> Result<Self> {
        let cpuid = unsafe { x86_64::__cpuid(0x8000_0001) };

        // Bits 31:28 are used to differentiate between Bergamo and Siena machines.
        let socket = (cpuid.ebx & 0xF0000000u32) >> 0x1C;

        let bytes: Vec<u8> = cpuid.eax.to_le_bytes().to_vec();

        let base_model = (bytes[0] & 0xF0) >> 4;
        let base_family = bytes[1] & 0x0F;

        let ext_model = bytes[2] & 0x0F;

        let ext_family = {
            let low = (bytes[2] & 0xF0) >> 4;
            let high = (bytes[3] & 0x0F) << 4;

            low | high
        };

        let model = (ext_model << 4) | base_model;
        let family = base_family + ext_family;

        match family {
            0x19 => match model {
                0x0..=0xF => Ok(Self::Milan),
                0x10..=0x1F => Ok(Self::Genoa),
                0xA0..=0xAF => match socket {
                    0x4 => Ok(Self::Bergamo),
                    0x8 => Ok(Self::Siena),
                    _ => Err(anyhow!("processor is not of a known SEV-SNP generation")),
                },
                _ => Err(anyhow!("processor is not of a known SEV-SNP model")),
            },
            0x1A => match model {
                0x0..=0x11 => Ok(Self::Turin),
                _ => Err(anyhow!("processor is not of a known SEV-SNP model")),
            },
            _ => Err(anyhow!("processor is not of a known SEV-SNP family")),
        }
    }

    pub(crate) fn to_kds_url(&self) -> String {
        match self {
            Self::Genoa | Self::Bergamo | Self::Siena => &Self::Genoa,
            _ => self,
        }
        .to_string()
    }
}

impl std::fmt::Display for ProcessorGeneration {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Milan => "Milan",
                Self::Genoa => "Genoa",
                Self::Bergamo => "Bergamo",
                Self::Siena => "Siena",
                Self::Turin => "Turin",
            }
        )
    }
}
07070100000021000081A4000000000000000000000001691558B0000005FF000000000000000000000000000000000000001A00000000snphost-0.7.0/src/show.rs// SPDX-License-Identifier: Apache-2.0

use super::*;

use cert::{fetch::hashsticks::vlek_hashsticks_url, fetch::vek::vek_url, Endorsement};

#[derive(Subcommand)]
pub enum Show {
    /// Show the current number of guests
    Guests,

    /// Show the platform identifier
    Identifier,

    /// Show the current platform and reported TCB version
    Tcb,

    /// Show the VCEK DER download URL
    VcekUrl,

    /// Show the VLEK DER download URL
    VlekUrl,

    /// Show the VLEK hashsticks download URL
    HashsticksURL,

    /// Show the platform's firmware version
    Version,
}

pub fn cmd(show: Show) -> Result<()> {
    let status = snp_platform_status()?;

    match show {
        Show::Guests => println!("{}", status.guest_count),
        Show::Identifier => {
            let id = firmware()?
                .get_identifier()
                .map_err(|e| anyhow::anyhow!(format!("{:?}", e)))
                .context("error fetching identifier")?;

            println!("{}", id);
        }
        Show::Tcb => println!(
            "Reported TCB: {}\nPlatform TCB: {}",
            status.reported_tcb_version, status.platform_tcb_version
        ),
        Show::VcekUrl => {
            let url = vek_url(Endorsement::Vcek)?;

            println!("{}", url);
        }
        Show::VlekUrl => println!("{}", vek_url(Endorsement::Vlek)?),
        Show::HashsticksURL => println!("{}", vlek_hashsticks_url()?),
        Show::Version => println!("{}.{}", status.version.0, status.version.1),
    }

    Ok(())
}
07070100000022000081A4000000000000000000000001691558B000000495000000000000000000000000000000000000001F00000000snphost-0.7.0/src/vlek_load.rs// SPDX-License-Identifier: Apache-2.0

use super::*;
use sev::{firmware::host::WrappedVlekHashstick, parser::ByteParser, Generation};
use std::{fs::read, path::PathBuf};

use anyhow::{bail, Context, Result};

#[derive(Parser)]
pub struct VlekLoad {
    /// File where the VLEK hashshtick is stored.
    #[arg(value_name = "hashstick-file", required = true)]
    pub hashstick_file: PathBuf,
}

pub fn cmd(vlek_load: VlekLoad) -> Result<()> {
    if !vlek_load.hashstick_file.exists() {
        bail!(format!(
            "path {} does not exist",
            vlek_load.hashstick_file.display()
        ));
    }

    let hashstick_bytes =
        read(&vlek_load.hashstick_file).context("Failed to read VLEK hashshtick file")?;

    let generation = Generation::identify_host_generation()?;

    let hashstick = WrappedVlekHashstick::from_bytes_with(&hashstick_bytes, generation)
        .context("Failed to parse VLEK hashshtick")?;

    // Load the VLEK hashshtick into the firmware.
    let mut fw = firmware()?;

    fw.snp_vlek_load(hashstick)
        .map_err(|e| anyhow::anyhow!(format!("{:}", e)))
        .context("Error loading VLEK hashshtick")?;

    Ok(())
}
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!278 blocks
openSUSE Build Service is sponsored by