Skip to content

Commit

Permalink
Merge pull request virtee#151 from larrydewey/Extend-Certs
Browse files Browse the repository at this point in the history
Certs: Adding generic support.
  • Loading branch information
larrydewey authored Feb 16, 2024
2 parents 74bd9eb + 47a76fd commit 5d8d03c
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/certs/snp/cert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use super::*;

use crate::error::CertFormatError;
use openssl::pkey::{PKey, Public};
use openssl::x509::X509;

Expand All @@ -10,6 +11,34 @@ use openssl::x509::X509;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Certificate(X509);

#[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 +106,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),
}
}
}
18 changes: 18 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,24 @@ use std::{

use std::os::raw::c_int;

#[cfg(feature = "openssl")]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum CertFormatError {
UnknownFormat,
}

#[cfg(feature = "openssl")]
impl std::error::Error for CertFormatError {}

#[cfg(feature = "openssl")]
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."),
}
}
}

/// An error representingthe upper 32 bits of a SW_EXITINFO2 field set by the VMM.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum VmmError {
Expand Down

0 comments on commit 5d8d03c

Please sign in to comment.