Skip to content

Commit

Permalink
Certs: Adding generic support.
Browse files Browse the repository at this point in the history
Adding generic support to automatically identify which type of certificate
the user provided and construct a Certificate from the identity discovered.

Signed-off-by: Larry Dewey <larry.dewey@amd.com>
  • Loading branch information
larrydewey committed Feb 13, 2024
1 parent 8ec07d4 commit 89af1f5
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ hw_tests = []
dangerous_hw_tests = ["hw_tests"]
sev = []
snp = []
openssl = ["dep:openssl"]
crypto_nossl = ["dep:p384", "dep:rsa", "dep:sha2", "dep:x509-cert"]

[target.'cfg(target_os = "linux")'.dependencies]
Expand Down
61 changes: 61 additions & 0 deletions src/certs/snp/cert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,49 @@ use openssl::x509::X509;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Certificate(X509);

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum CertFormatError {
UnknownFormat,
}

impl std::error::Error for CertFormatError {}

impl std::fmt::Display for CertFormatError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::UnknownFormat => write!(f, "Unknown Certificate Format Encountered."),
}
}
}

#[derive(Clone, Copy, Debug)]
enum CertFormat {
Pem,
Der,
}

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

impl std::str::FromStr for CertFormat {
type Err = CertFormatError;

fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
match s {
"pem" => Ok(Self::Pem),
"der" => Ok(Self::Der),
_ => Err(CertFormatError::UnknownFormat),
}
}
}

/// Wrap an X509 struct into a Certificate.
impl From<X509> for Certificate {
fn from(x509: X509) -> Self {
Expand Down Expand Up @@ -77,4 +120,22 @@ impl Certificate {
pub fn public_key(&self) -> Result<PKey<Public>> {
Ok(self.0.public_key()?)
}

/// Identifies the format of a certificate based upon the first twenty-eight
/// bytes of a byte stream. A non-PEM format assumes DER format.
fn identify_format(bytes: &[u8]) -> CertFormat {
const PEM_START: &[u8] = b"-----BEGIN CERTIFICATE-----";
match bytes {
PEM_START => CertFormat::Pem,
_ => CertFormat::Der,
}
}

/// An façade method for constructing a Certificate from raw bytes.
pub fn from_bytes(raw_bytes: &[u8]) -> Result<Self> {
match Self::identify_format(raw_bytes) {
CertFormat::Pem => Self::from_pem(raw_bytes),
CertFormat::Der => Self::from_der(raw_bytes),
}
}
}

0 comments on commit 89af1f5

Please sign in to comment.