File snphost-0.2.0~0.obscpio of Package snphost

07070100000000000041ED0000000000000000000000026545C04F00000000000000000000000000000000000000000000001800000000snphost-0.2.0~0/.github07070100000001000081A40000000000000000000000016545C04F000000EB000000000000000000000000000000000000002300000000snphost-0.2.0~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
07070100000002000081A40000000000000000000000016545C04F00000030000000000000000000000000000000000000002F00000000snphost-0.2.0~0/.github/auto_assign-issues.ymladdAssignees: true

assignees:
  - tylerfanelli
07070100000003000081A40000000000000000000000016545C04F00000211000000000000000000000000000000000000002800000000snphost-0.2.0~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
  - ryansavino

# 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
07070100000004000081A40000000000000000000000016545C04F00000064000000000000000000000000000000000000002700000000snphost-0.2.0~0/.github/dependabot.ymlversion: 2
updates:
- package-ecosystem: "cargo"
  directory: "/"
  schedule:
    interval: "daily"
07070100000005000041ED0000000000000000000000026545C04F00000000000000000000000000000000000000000000002200000000snphost-0.2.0~0/.github/workflows07070100000006000081A40000000000000000000000016545C04F0000033E000000000000000000000000000000000000002B00000000snphost-0.2.0~0/.github/workflows/lint.ymlon: [push, pull_request]
name: lint
jobs:
  fmt:
    name: cargo fmt
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions-rs/toolchain@v1
        with:
          components: rustfmt
          toolchain: nightly
          profile: minimal
          override: true
      - uses: actions-rs/cargo@v1
        with:
          command: fmt
          args: --all -- --check

  clippy:
    name: cargo clippy
    runs-on: ubuntu-latest
    steps:
      - run: sudo apt-get install -y asciidoctor
      - uses: actions/checkout@v2
      - uses: actions-rs/toolchain@v1
        with:
          components: clippy
          toolchain: nightly
          profile: minimal
          override: true
      - uses: actions-rs/cargo@v1
        with:
          command: clippy
          args: -- -D warnings
07070100000007000081A40000000000000000000000016545C04F000002B4000000000000000000000000000000000000002B00000000snphost-0.2.0~0/.github/workflows/test.ymlon: [push, pull_request]
name: test
jobs:
  test:
    name: ${{ matrix.toolchain }} (${{ matrix.profile.name }})
    runs-on: ubuntu-latest
    steps:
      - run: sudo apt-get install -y asciidoctor
      - uses: actions/checkout@v2
      - uses: actions-rs/toolchain@v1
        with:
          toolchain: ${{ matrix.toolchain }}
          override: true
      - uses: actions-rs/cargo@v1
        with:
          command: test
          args: ${{ matrix.profile.flag }}
    strategy:
      fail-fast: false
      matrix:
        toolchain:
          - nightly
          - beta
          - stable
        profile:
          - name: debug
          - name: release
            flag: --release
07070100000008000081A40000000000000000000000016545C04F00000018000000000000000000000000000000000000001B00000000snphost-0.2.0~0/.gitignore/target
Cargo.lock
*.sh
07070100000009000081A40000000000000000000000016545C04F00000485000000000000000000000000000000000000001B00000000snphost-0.2.0~0/Cargo.toml[package]
name = "snphost"
version = "0.2.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.56"

[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.71"
sev = { version = "1.2.0", features = [ "openssl" ] }
env_logger = "0.9.0"
structopt = "0.3.26"
colorful = "0.2.2"
libc = "0.2.139"
curl = "0.4"
0707010000000A000081A40000000000000000000000016545C04F00002C5D000000000000000000000000000000000000001800000000snphost-0.2.0~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.
0707010000000B000081A40000000000000000000000016545C04F000000B2000000000000000000000000000000000000001A00000000snphost-0.2.0~0/README.md# snphost
Management CLI for SEV-SNP host system administrators

Please consult `docs/snphost.1.adoc` for an overview of `snphost` and
descriptions of each `snphost` subcommand.
0707010000000C000081A40000000000000000000000016545C04F00000636000000000000000000000000000000000000001900000000snphost-0.2.0~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(())
}
0707010000000D000041ED0000000000000000000000026545C04F00000000000000000000000000000000000000000000001500000000snphost-0.2.0~0/docs0707010000000E000081A40000000000000000000000016545C04F00000FB1000000000000000000000000000000000000002400000000snphost-0.2.0~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] DIR-PATH

        This command exports the SEV-SNP certificate chain to the directory
        provided by DIR-PATH. User must specify if the certificates currently
        stored on the PSP are encoded in DER or PEM format. These are the only
        two encoding formats supported in this tool.

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

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

        This command imports serialized SEV-SNP certificates to the host's PSP.
        Currently, only the ASK, ARK, and VCEK are able to be imported to the
        PSP. 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}

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

  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 reset*::
	usage: snphost reset

        This command resets the SEV-SNP platform. This will clear all
        persistent data managed by the platform.

  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*::
	usage: snphost verify ARK-PATH ASK-PATH VCEK-PATH

        This command verifies the full SEV-SNP/CA certificate chain.
        Certificates must be encoded in PEM format.

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

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

        This command fetches the host system's CA certificate chain and writes
        the encoded certificates to the directory at path DIR-PATH. Users must
        specify which format they would like the certificate to be encoded
        in (DER or PEM).

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

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

        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).

 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


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

Please report all bugs to <https://github.com/virtee/snphost/issues>
0707010000000F000041ED0000000000000000000000026545C04F00000000000000000000000000000000000000000000001400000000snphost-0.2.0~0/src07070100000010000041ED0000000000000000000000026545C04F00000000000000000000000000000000000000000000001900000000snphost-0.2.0~0/src/cert07070100000011000081A40000000000000000000000016545C04F00000B7A000000000000000000000000000000000000002300000000snphost-0.2.0~0/src/cert/export.rs// SPDX-License-Identifier: Apache-2.0

use super::EncodingFormat;
use anyhow::{bail, Context, Result};
use sev::{certs::snp::Certificate, firmware::host::CertType};
use structopt::StructOpt;

use std::{io::Write, path::PathBuf};

use crate::cert_entries;

fn identify_cert(buf: &[u8]) -> EncodingFormat {
    const PEM_START: &[u8] = b"-----BEGIN CERTIFICATE-----";
    match buf {
        PEM_START => EncodingFormat::Pem,
        _ => EncodingFormat::Der,
    }
}

#[derive(StructOpt)]
pub struct Export {
    #[structopt(about = "The format the certs are encoded in (PEM or DER)")]
    pub encoding_fmt: EncodingFormat,

    #[structopt(about = "The directory to write the certificates to")]
    pub dir_path: PathBuf,
}

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

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

    let entries = cert_entries()?;
    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;

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

                "vcek"
            }
            _ => continue,
        };

        // Attempt to identify the current format of the certificate in
        // hypervisor memory and build a Certificate from it.
        let certificate: Certificate = match identify_cert(&e.data[..27]) {
            EncodingFormat::Der => Certificate::from_der(&e.data)?,
            EncodingFormat::Pem => Certificate::from_pem(&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.to_string()
        );

        // Create the file for writing and open a file-handle.
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create(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(())
}
07070100000012000041ED0000000000000000000000026545C04F00000000000000000000000000000000000000000000001F00000000snphost-0.2.0~0/src/cert/fetch07070100000013000081A40000000000000000000000016545C04F000008B6000000000000000000000000000000000000002500000000snphost-0.2.0~0/src/cert/fetch/ca.rs// SPDX-License-Identifier: Apache-2.0

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

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

#[derive(StructOpt)]
pub struct Ca {
    #[structopt(about = "The format the certs are encoded in (PEM or DER)")]
    pub encoding_fmt: EncodingFormat,

    #[structopt(about = "The directory to write the certificates to")]
    pub dir_path: PathBuf,
}

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

pub fn cmd(ca: Ca) -> Result<()> {
    let url: String = ca_chain_url()?;
    let cert_chain: Chain = fetch(&url)?;

    let ((ask_path, ask_bytes), (ark_path, ark_bytes)) = match ca.encoding_fmt {
        EncodingFormat::Der => (
            ("ask.der", cert_chain.ask.to_der()?),
            ("ark.der", cert_chain.ark.to_der()?),
        ),
        EncodingFormat::Pem => (
            ("ask.pem", 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 {
        ask: Certificate::from_pem(&buf[..2325])?,
        ark: Certificate::from_pem(&buf[2325..])?,
    })
}

fn ca_chain_url() -> Result<String> {
    Ok(format!(
        "https://kdsintf.amd.com/vcek/v1/{}/cert_chain",
        ProcessorGeneration::current()?.to_string()
    ))
}
07070100000014000081A40000000000000000000000016545C04F000005C9000000000000000000000000000000000000002600000000snphost-0.2.0~0/src/cert/fetch/crl.rs// SPDX-License-Identifier: Apache-2.0

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

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

#[derive(StructOpt)]
pub struct Crl {
    #[structopt(about = "The directory to write the CRL to")]
    pub dir_path: PathBuf,
}

pub fn cmd(crl: Crl) -> Result<()> {
    let url: String = crl_url()?;
    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)
        .write(true)
        .open(crl.dir_path.join(format!(
            "{}.crl",
            ProcessorGeneration::current()?.to_string()
        )))?;

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

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)
}
07070100000015000081A40000000000000000000000016545C04F00000263000000000000000000000000000000000000002600000000snphost-0.2.0~0/src/cert/fetch/mod.rs// SPDX-License-Identifier: Apache-2.0

pub(crate) mod ca;
pub(crate) mod crl;
pub(crate) mod vcek;
use anyhow::Result;
use structopt::StructOpt;

#[derive(StructOpt)]
pub enum Fetch {
    #[structopt(about = "Fetches the VCEK from the KDS")]
    Vcek(vcek::Vcek),

    #[structopt(about = "Fetches the CA from the KDS")]
    Ca(ca::Ca),

    #[structopt(about = "Fetches the CRL from the KDS")]
    Crl(crl::Crl),
}

pub fn cmd(fetch: Fetch) -> Result<()> {
    match fetch {
        Fetch::Vcek(vcek) => vcek::cmd(vcek),
        Fetch::Ca(ca) => ca::cmd(ca),
        Fetch::Crl(crl) => crl::cmd(crl),
    }
}
07070100000016000081A40000000000000000000000016545C04F00000917000000000000000000000000000000000000002700000000snphost-0.2.0~0/src/cert/fetch/vcek.rs// SPDX-License-Identifier: Apache-2.0

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

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

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

use super::super::EncodingFormat;

#[derive(StructOpt)]
pub struct Vcek {
    #[structopt(about = "The format in which to encode the certificate")]
    encoding_fmt: EncodingFormat,

    #[structopt(about = "The path of a directory to store the encoded VCEK in")]
    path: PathBuf,
}

pub fn cmd(vcek: Vcek) -> Result<()> {
    let url = vcek_url()?;
    let cert = fetch(&url).context(format!("unable to fetch VCEK from {}", url))?;

    let (vcek_name, vcek_bytes) = match vcek.encoding_fmt {
        EncodingFormat::Der => ("vcek.der", cert.to_der()?),
        EncodingFormat::Pem => ("vcek.pem", cert.to_pem()?),
    };

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

    let mut file = OpenOptions::new()
        .create(true)
        .write(true)
        .open(vcek.path.join(vcek_name))?;

    file.write_all(&vcek_bytes)?;

    Ok(())
}

pub fn fetch(url: &str) -> Result<Certificate> {
    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(Certificate::from_der(buf.as_slice())?)
}

pub fn vcek_url() -> Result<String> {
    let id = firmware()?
        .get_identifier()
        .map_err(|e| anyhow::anyhow!(format!("{:?}", e)))
        .context("error fetching identifier")?;
    let status = platform_status()?;
    let gen = ProcessorGeneration::current()?;

    Ok(format!("https://kdsintf.amd.com/vcek/v1/{}/{}?blSPL={:02}&teeSPL={:02}&snpSPL={:02}&ucodeSPL={:02}",
                         gen.to_string(), id, status.platform_tcb_version.bootloader,
                         status.platform_tcb_version.tee,
                         status.platform_tcb_version.snp,
                         status.platform_tcb_version.microcode))
}
07070100000017000081A40000000000000000000000016545C04F00000725000000000000000000000000000000000000002300000000snphost-0.2.0~0/src/cert/import.rs// SPDX-License-Identifier: Apache-2.0

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

use crate::firmware;

use structopt::StructOpt;

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

#[derive(StructOpt)]
pub struct Import {
    #[structopt(about = "The directory to find the encoded certificates")]
    pub path: PathBuf,
}

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

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

    for dir_entry in read_dir(import.path.clone())? {
        match dir_entry {
            Ok(de) => table_add_entry(de, &mut table)?,
            Err(_) => {
                bail!(format!(
                    "unable to read directory at path {}",
                    import.path.display()
                ))
            }
        }
    }

    firmware()?.snp_set_ext_config(ExtConfig::new_certs_only(table))?;

    Ok(())
}

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

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

    Ok(())
}

fn entry_get_type(path: &PathBuf) -> Result<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(CertType::ARK),
        "ask" => Ok(CertType::ASK),
        "vcek" => Ok(CertType::VCEK),
        _ => Err(anyhow!(
            "unable to determine certificate type of path {:?}",
            path
        )),
    }
}
07070100000018000081A40000000000000000000000016545C04F0000039A000000000000000000000000000000000000002000000000snphost-0.2.0~0/src/cert/mod.rs// SPDX-License-Identifier: Apache-2.0

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

use std::str::FromStr;

use structopt::StructOpt;

use anyhow::{anyhow, Error};

#[derive(StructOpt)]
pub enum EncodingFormat {
    #[structopt(about = "Certificates are encoded in DER format")]
    Der,

    #[structopt(about = "Certificates are encoded in PEM format")]
    Pem,
}

impl ToString for EncodingFormat {
    fn to_string(&self) -> String {
        match self {
            Self::Der => "der".to_string(),
            Self::Pem => "pem".to_string(),
        }
    }
}

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")),
        }
    }
}
07070100000019000081A40000000000000000000000016545C04F00000964000000000000000000000000000000000000002300000000snphost-0.2.0~0/src/cert/verify.rs// SPDX-License-Identifier: Apache-2.0

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

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

#[derive(StructOpt)]
pub struct Verify {
    #[structopt(about = "The path to the ARK certificate")]
    ark: PathBuf,

    #[structopt(about = "The path to the ASK certificate")]
    ask: PathBuf,

    #[structopt(about = "The path to the VCEK certificate")]
    vcek: PathBuf,
}

pub fn cmd(verify: Verify, quiet: bool) -> Result<()> {
    let chain = chain(verify)?;

    let (ark, ask, vcek) = (
        (&chain.ca.ark, "ARK"),
        (&chain.ca.ask, "ASK"),
        (&chain.vcek, "VCEK"),
    );

    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, vcek, 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(verify: Verify) -> Result<Chain> {
    Ok(Chain {
        ca: ca::Chain {
            ark: cert(verify.ark, "ARK")?,
            ask: cert(verify.ask, "ASK")?,
        },
        vcek: cert(verify.vcek, "VCEK")?,
    })
}

fn cert(path: PathBuf, name: &str) -> Result<Certificate> {
    Certificate::from_pem(
        &read(path.clone()).context(format!("unable to read {}", path.display()))?,
    )
    .context(format!(
        "unable to parse {} certificate from {}",
        name,
        path.display()
    ))
}
0707010000001A000081A40000000000000000000000016545C04F00000A8D000000000000000000000000000000000000001C00000000snphost-0.2.0~0/src/main.rs// SPDX-License-Identifier: Apache-2.0

#![deny(clippy::all)]

mod cert;
mod processor;
mod reset;
mod show;

mod ok;

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

use anyhow::{anyhow, Context, Result};
use sev::firmware::host::*;
use structopt::StructOpt;

const VERSION: &str = env!("CARGO_PKG_VERSION");
const AUTHORS: &str = env!("CARGO_PKG_AUTHORS");

#[derive(StructOpt)]
struct SnpHost {
    #[structopt(subcommand)]
    pub cmd: SnpHostCmd,

    #[structopt(short, long, about = "Don't print anything to the console")]
    pub quiet: bool,
}

#[allow(clippy::large_enum_variant)]
#[derive(StructOpt)]
#[structopt(author = AUTHORS, version = VERSION, about = "Utilities for managing the SEV-SNP environment")]
enum SnpHostCmd {
    #[structopt(about = "Display information about the SEV-SNP platform")]
    Show(show::Show),

    #[structopt(about = "Export a certificate chain to a given directory")]
    Export(export::Export),

    #[structopt(about = "Import a certificate chain to the AMD PSP")]
    Import(import::Import),

    #[structopt(about = "Probe system for SEV-SNP support")]
    Ok,

    #[structopt(about = "Reset the SEV-SNP platform state")]
    Reset,

    #[structopt(about = "Verify a certificate chain")]
    Verify(verify::Verify),

    #[structopt(about = "Retrieve some content from the AMD Key Distribution Server (KDS)")]
    Fetch(fetch::Fetch),
}

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

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

fn cert_entries() -> Result<Vec<CertTableEntry>> {
    let config = firmware()?
        .snp_get_ext_config()
        .map_err(|e| anyhow::anyhow!(format!("{:?}", e)))
        .context("unable to retrieve SNP certificates")?;

    match config.certs {
        Some(c) => Ok(c),
        None => Err(anyhow!("no SNP certificates found")),
    }
}

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

    let snphost = SnpHost::from_args();
    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::Reset => reset::cmd(),
        SnpHostCmd::Verify(verify) => verify::cmd(verify, snphost.quiet),
        SnpHostCmd::Fetch(fetch) => fetch::cmd(fetch),
    };

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

    result
}
0707010000001B000081A40000000000000000000000016545C04F0000521F000000000000000000000000000000000000001A00000000snphost-0.2.0~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::*;

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)
    }
}

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: "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: "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: "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: "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![],
        },
    ];

    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 sevctl-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, "/dev/sev readable".to_string()),
        Err(e) => (TestState::Fail, format!("/dev/sev not readable: {}", e)),
    };

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

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

    TestResult {
        name: "Writing /dev/sev".to_string(),
        stat,
        mesg: Some(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, "enabled".to_string())
                } else {
                    (
                        TestState::Fail,
                        format!("Error - contents read from {}: {}", path_loc, result.trim()),
                    )
                }
            }
            Err(e) => (
                TestState::Fail,
                format!("Error - (unable to read {}): {}", path_loc, e,),
            ),
        }
    } else {
        (
            TestState::Fail,
            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: Some(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),
    }
}
0707010000001C000081A40000000000000000000000016545C04F000008F1000000000000000000000000000000000000002100000000snphost-0.2.0~0/src/processor.rs// SPDX-License-Identifier: Apache-2.0

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

pub enum ProcessorGeneration {
    Milan,
    Genoa,
}

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) };
        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;

        let id = (model, family);

        let milan = (1, 25);
        let genoa = (17, 25);

        if id == milan {
            return Ok(Self::Milan);
        } else if id == genoa {
            return Ok(Self::Genoa);
        }

        Err(anyhow!("processor is not of a known SEV-SNP generation"))
    }
}

impl ToString for ProcessorGeneration {
    fn to_string(&self) -> String {
        let sstr = match self {
            Self::Milan => "Milan",
            Self::Genoa => "Genoa",
        };

        sstr.to_string()
    }
}
0707010000001D000081A40000000000000000000000016545C04F00000103000000000000000000000000000000000000001D00000000snphost-0.2.0~0/src/reset.rs// SPDX-License-Identifier: Apache-2.0

use super::*;

pub fn cmd() -> Result<()> {
    let mut fw = firmware()?;

    fw.snp_reset_config()
        .map_err(|e| anyhow::anyhow!(format!("{:?}", e)))
        .context("error resetting SEV-SNP configuration")
}
0707010000001E000081A40000000000000000000000016545C04F000004FE000000000000000000000000000000000000001C00000000snphost-0.2.0~0/src/show.rs// SPDX-License-Identifier: Apache-2.0

use super::*;

use cert::fetch::vcek::vcek_url;

#[derive(StructOpt)]
pub enum Show {
    #[structopt(about = "Show the current number of guests")]
    Guests,

    #[structopt(about = "Show the platform identifier")]
    Identifier,

    #[structopt(about = "Show the current platform and reported TCB version")]
    Tcb,

    #[structopt(about = "Show the VCEK DER download URL")]
    VcekUrl,

    #[structopt(about = "Show the platform's firmware version")]
    Version,
}

pub fn cmd(show: Show) -> Result<()> {
    let status = 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 = vcek_url()?;

            println!("{}", url);
        }
        Show::Version => println!("{}", status.version),
    }

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