Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

One verify to rule them all #158

Merged
merged 3 commits into from
Dec 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ derive_more = "0.99"
ecdsa = { version = "0.16", default-features = false }
ed25519-dalek = { version = "2.1", default-features = false }
env_logger = { version = "0.10", default-features = false }
getrandom = "0.2.11"
hex.version = "0.4"
hubpack = "0.1"
log = { version = "0.4", features = ["std"] }
Expand Down
3 changes: 2 additions & 1 deletion attest-data/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ version = "0.1.0"
edition = "2021"

[dependencies]
getrandom = { workspace = true, optional = true }
hubpack.workspace = true
thiserror = { workspace = true, optional = true }
salty.workspace = true
Expand All @@ -12,4 +13,4 @@ serde_with = { workspace = true, features = ["macros"] }
sha3.workspace = true

[features]
std = ["thiserror"]
std = ["getrandom", "thiserror"]
17 changes: 17 additions & 0 deletions attest-data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ use std::fmt::{self, Display, Formatter};
pub enum AttestDataError {
#[cfg_attr(feature = "std", error("Deserialization failed"))]
Deserialize,
#[cfg_attr(
feature = "std",
error("Failed to get random Nonce from the platform")
)]
GetRandom,
#[cfg_attr(feature = "std", error("Slice is the wrong length"))]
TryFromSliceError,
}
Expand Down Expand Up @@ -109,6 +114,18 @@ impl Display for Nonce {
}
}

impl Nonce {
#[cfg(feature = "std")]
pub fn from_platform_rng() -> Result<Self, AttestDataError> {
let mut nonce = [0u8; NONCE_SIZE];
getrandom::getrandom(&mut nonce[..])
.map_err(|_| AttestDataError::GetRandom)?;
let nonce = nonce;

Ok(Self(nonce))
}
}

/// Measurement is an enum that can hold any of the hash algorithms that we support
#[derive(
Clone, Copy, Debug, Deserialize, PartialEq, Serialize, SerializedSize,
Expand Down
202 changes: 154 additions & 48 deletions verifier-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use pem_rfc7468::{LineEnding, PemLabel};
use sha3::{Digest, Sha3_256};
use std::{
fmt::{self, Debug, Formatter},
fs,
fs::{self, File},
io::{self, Read, Write},
path::{Path, PathBuf},
process::{Command, Output},
Expand Down Expand Up @@ -85,6 +85,20 @@ enum AttestCommand {
#[clap(env)]
digest: PathBuf,
},
Verify {
/// Path to file holding trust anchor for the associated PKI.
#[clap(long, env, conflicts_with = "self_signed")]
ca_cert: Option<PathBuf>,

/// Preserve temporary / intermediate files. The path to the
/// temp directory will be written to stderr.
#[clap(long, env)]
persist: bool,

/// Verify the final cert in the provided PkiPath against itself.
#[clap(long, env, conflicts_with = "ca_cert")]
self_signed: bool,
},
/// Verify signature over Attestation
VerifyAttestation {
/// Path to file holding the alias cert
Expand Down Expand Up @@ -470,69 +484,161 @@ fn main() -> Result<()> {
let digest = fs::read(digest)?;
attest.record(&digest)?;
}
AttestCommand::Verify {
ca_cert,
persist,
self_signed,
} => {
// generate nonce from RNG
info!("getting Nonce from platform RNG");
let nonce = Nonce::from_platform_rng()?;

// make tempdir, write nonce to temp dir
let tmp_dir = tempfile::tempdir()?;
let nonce_path = tmp_dir.path().join("nonce.bin");
info!("writing nonce to: {}", nonce_path.display());
fs::write(&nonce_path, nonce)?;

// get attestation
info!("getting attestation");
let mut attestation = vec![0u8; attest.attest_len()? as usize];
attest.attest(nonce, &mut attestation)?;
let attestation_path = tmp_dir.path().join("attest.bin");
info!("writing attestation to: {}", attestation_path.display());
fs::write(&attestation_path, &attestation)?;

// get log
info!("getting measurement log");
let mut log = vec![0u8; attest.log_len()? as usize];
attest.log(&mut log)?;
let log_path = tmp_dir.path().join("log.bin");
info!("writing measurement log to: {}", log_path.display());
fs::write(&log_path, &log)?;

// get cert chain
info!("getting cert chain");
let cert_chain_path = tmp_dir.path().join("cert-chain.pem");
let mut cert_chain = File::create(&cert_chain_path)?;
let alias_cert_path = tmp_dir.path().join("alias.pem");
for index in 0..attest.cert_chain_len()? {
let encoding = Encoding::Pem;
info!("getting cert[{}] encoded as {}", index, encoding);
let cert = get_cert(&attest, encoding, index)?;

// the first cert in the chain / the leaf cert is the one
// used to sign attestations
if index == 0 {
info!(
"writing alias cert to: {}",
alias_cert_path.display()
);
fs::write(&alias_cert_path, &cert)?;
}

info!(
"writing cert[{}] to: {}",
index,
cert_chain_path.display()
);
cert_chain.write_all(&cert)?;
}

verify_attestation(
&alias_cert_path,
&attestation_path,
&log_path,
&nonce_path,
)?;
info!("attestation verified");
verify_cert_chain(&ca_cert, &cert_chain_path, self_signed)?;
info!("cert chain verified");

// persist the temp dir and write path to stderr if requested
if persist {
let tmp_path = tmp_dir.into_path();
eprintln!("{}", tmp_path.display());
}
}
AttestCommand::VerifyAttestation {
alias_cert,
attestation,
log,
nonce,
} => {
let attestation = fs::read(attestation)?;
let (attestation, _): (Attestation, _) =
hubpack::deserialize(&attestation).map_err(|e| {
anyhow!("Failed to deserialize Attestation: {}", e)
})?;

let log = fs::read(log)?;

let nonce: Nonce = fs::read(nonce)?.try_into()?;

let alias = fs::read(alias_cert)?;
let alias = match pem_rfc7468::decode_vec(&alias) {
Ok((l, v)) => {
debug!("decoded pem w/ label: \"{}\"", l);
if l != Certificate::PEM_LABEL {
error!("got cert w/ unsupported pem label");
}

v
}
Err(e) => {
debug!("error decoding PEM: {}", e);
alias
}
};

let alias = Certificate::from_der(&alias)?;

verifier::verify_attestation(&alias, &attestation, &log, &nonce)?;
verify_attestation(&alias_cert, &attestation, &log, &nonce)?;
}
AttestCommand::VerifyCertChain {
cert_chain,
ca_cert,
self_signed,
} => {
if !self_signed && ca_cert.is_none() {
return Err(anyhow!("`ca-cert` or `self-signed` is required"));
}
verify_cert_chain(&ca_cert, &cert_chain, self_signed)?;
}
}

let cert_chain = fs::read(cert_chain)?;
let cert_chain: PkiPath = Certificate::load_pem_chain(&cert_chain)?;
Ok(())
}

let root = match ca_cert {
Some(r) => {
let root = fs::read(r)?;
Some(Certificate::from_pem(root)?)
}
None => {
warn!("allowing self-signed cert chain");
None
}
};
fn verify_attestation(
alias_cert: &PathBuf,
attestation: &PathBuf,
log: &PathBuf,
nonce: &PathBuf,
) -> Result<()> {
info!("verifying attestation");
let attestation = fs::read(attestation)?;
let (attestation, _): (Attestation, _) = hubpack::deserialize(&attestation)
.map_err(|e| anyhow!("Failed to deserialize Attestation: {}", e))?;

let log = fs::read(log)?;

let nonce: Nonce = fs::read(nonce)?.try_into()?;

let alias = fs::read(alias_cert)?;
let alias = match pem_rfc7468::decode_vec(&alias) {
Ok((l, v)) => {
debug!("decoded pem w/ label: \"{}\"", l);
if l != Certificate::PEM_LABEL {
error!("got cert w/ unsupported pem label");
}

let verifier = PkiPathSignatureVerifier::new(root)?;
verifier.verify(&cert_chain)?;
v
}
Err(e) => {
debug!("error decoding PEM: {}", e);
alias
}
};

let alias = Certificate::from_der(&alias)?;

verifier::verify_attestation(&alias, &attestation, &log, &nonce)
}

fn verify_cert_chain(
ca_cert: &Option<PathBuf>,
cert_chain: &PathBuf,
self_signed: bool,
) -> Result<()> {
info!("veryfying cert chain");
if !self_signed && ca_cert.is_none() {
return Err(anyhow!("`ca-cert` or `self-signed` is required"));
}

Ok(())
let cert_chain = fs::read(cert_chain)?;
let cert_chain: PkiPath = Certificate::load_pem_chain(&cert_chain)?;

let root = match ca_cert {
Some(r) => {
let root = fs::read(r)?;
Some(Certificate::from_pem(root)?)
}
None => {
warn!("allowing self-signed cert chain");
None
}
};

let verifier = PkiPathSignatureVerifier::new(root)?;
verifier.verify(&cert_chain)
}
Loading