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

Add IssuerAuth, MdocAuth, ReaderAuth checks #75

Merged
merged 13 commits into from
Dec 20, 2024
13 changes: 10 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,13 @@ documentation = "https://docs.rs/isomdl"
license = "Apache-2.0 OR MIT"
exclude = ["test/"]

[[bin]]
name = "isomdl-utils"
path = "src/bin/utils.rs"

[dependencies]
anyhow = "1.0"
ecdsa = { version = "0.16.0", features = ["serde"] }
ecdsa = { version = "0.16.0", features = ["serde", "verifying"] }
p256 = { version = "0.13.0", features = ["serde", "ecdh"] }
p384 = { version = "0.13.0", features = ["serde", "ecdh"] }
rand = { version = "0.8.5", features = ["getrandom"] }
Expand All @@ -36,12 +40,15 @@ async-signature = "0.3.0"
#tracing = "0.1"
base64 = "0.13"
pem-rfc7468 = "0.7.0"
x509-cert = { version = "0.1.1", features = ["pem"] }

x509-cert = { version = "0.2.4", features = ["pem", "builder"] }
ssi-jwk = "0.2.1"
isomdl-macros = { version = "0.1.0", path = "macros" }
clap = { version = "4", features = ["derive"] }
clap-stdin = "0.2.1"
const-oid = "0.9.2"
der = { version = "0.7", features = ["std", "derive", "alloc"] }
hex = "0.4.3"
asn1-rs = { version = "0.5.2", features = ["bits"] }

strum = "0.24"
strum_macros = "0.24"
Expand Down
84 changes: 84 additions & 0 deletions src/bin/utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
use std::{collections::BTreeMap, fs::File, io::Read, path::PathBuf};

use anyhow::{Context, Error, Ok};
use clap::Parser;
use clap_stdin::MaybeStdin;
use isomdl::presentation::{device::Document, Stringify};

mod x509;

#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
#[command(subcommand)]
action: Action,
}

#[derive(Debug, clap::Subcommand)]
enum Action {
/// Print the namespaces and element identifiers used in an mDL.
GetNamespaces {
/// Base64 encoded mDL in the format used in the issuance module of this crate.
mdl: MaybeStdin<String>,
},
/// Validate a document signer cert against a possible root certificate.
ValidateCerts {
/// Validation rule set.
rules: RuleSet,
/// Path to PEM-encoded document signer cert.
ds: PathBuf,
/// Path to PEM-encoded IACA root cert.
root: PathBuf,
},
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum RuleSet {
Iaca,
Aamva,
NamesOnly,
}

fn main() -> Result<(), Error> {
match Args::parse().action {
Action::GetNamespaces { mdl } => print_namespaces(mdl.to_string()),
Action::ValidateCerts { rules, ds, root } => validate_certs(rules, ds, root),
}
}

fn print_namespaces(mdl: String) -> Result<(), Error> {
let claims = Document::parse(mdl)
.context("could not parse mdl")?
.namespaces
.into_inner()
.into_iter()
.map(|(ns, inner)| (ns, inner.into_inner().into_keys().collect()))
.collect::<BTreeMap<String, Vec<String>>>();
println!("{}", serde_json::to_string_pretty(&claims)?);
Ok(())
}

fn validate_certs(rules: RuleSet, ds: PathBuf, root: PathBuf) -> Result<(), Error> {
let mut ds_bytes = vec![];
File::open(ds)?.read_to_end(&mut ds_bytes)?;
let mut root_bytes = vec![];
File::open(root)?.read_to_end(&mut root_bytes)?;
let validation_errors = x509::validate(rules, &ds_bytes, &root_bytes)?;
if validation_errors.is_empty() {
println!("Validated!");
} else {
println!(
"Validation errors:\n{}",
serde_json::to_string_pretty(&validation_errors)?
)
}
Ok(())
}

#[cfg(test)]
mod test {
#[test]
fn print_namespaces() {
super::print_namespaces(include_str!("../../test/stringified-mdl.txt").to_string()).unwrap()
}
}
41 changes: 41 additions & 0 deletions src/bin/x509/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use anyhow::anyhow;
use isomdl::definitions::x509::{
error::Error as X509Error,
trust_anchor::{RuleSetType, TrustAnchor, TrustAnchorRegistry, ValidationRuleSet},
x5chain::X509,
X5Chain,
};

use crate::RuleSet;

pub fn validate(
rules: RuleSet,
signer: &[u8],
root: &[u8],
) -> Result<Vec<X509Error>, anyhow::Error> {
let root_bytes = pem_rfc7468::decode_vec(root)
.map_err(|e| anyhow!("unable to parse pem: {}", e))?
.1;

let ruleset = ValidationRuleSet {
distinguished_names: vec!["2.5.4.6".to_string(), "2.5.4.8".to_string()],
typ: match rules {
RuleSet::Iaca => RuleSetType::IACA,
RuleSet::Aamva => RuleSetType::AAMVA,
RuleSet::NamesOnly => RuleSetType::NamesOnly,
},
};

let trust_anchor = TrustAnchor::Custom(X509 { bytes: root_bytes }, ruleset);
let trust_anchor_registry = TrustAnchorRegistry {
certificates: vec![trust_anchor],
};
let bytes = pem_rfc7468::decode_vec(signer)
.map_err(|e| anyhow!("unable to parse pem: {}", e))?
.1;
let x5chain_cbor: ciborium::Value = ciborium::Value::Bytes(bytes);

let x5chain = X5Chain::from_cbor(x5chain_cbor)?;

Ok(x5chain.validate(Some(trust_anchor_registry)))
}
2 changes: 0 additions & 2 deletions src/cose/mac0.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,8 +218,6 @@ mod hmac {

use super::super::SignatureAlgorithm;

/// Implement [`SignatureAlgorithm`].

impl SignatureAlgorithm for Hmac<Sha256> {
fn algorithm(&self) -> iana::Algorithm {
iana::Algorithm::HMAC_256_256
Expand Down
2 changes: 1 addition & 1 deletion src/cose/serialized_as_cbor_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
/// implement `Serialize`/`Deserialize` but only `AsCborValue`.
pub struct SerializedAsCborValue<T>(pub T);

impl<'a, T: Clone + AsCborValue> Serialize for SerializedAsCborValue<&'a T> {
impl<T: Clone + AsCborValue> Serialize for SerializedAsCborValue<&T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
Expand Down
4 changes: 0 additions & 4 deletions src/cose/sign1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,6 @@ mod p256 {

use crate::cose::SignatureAlgorithm;

/// Implement [`SignatureAlgorithm`].

impl SignatureAlgorithm for SigningKey {
fn algorithm(&self) -> iana::Algorithm {
iana::Algorithm::ES256
Expand All @@ -252,8 +250,6 @@ mod p384 {

use crate::cose::SignatureAlgorithm;

/// Implement [`SignatureAlgorithm`].

impl SignatureAlgorithm for SigningKey {
fn algorithm(&self) -> iana::Algorithm {
iana::Algorithm::ES384
Expand Down
4 changes: 2 additions & 2 deletions src/definitions/device_engagement.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! This module contains the definitions for the [DeviceEngagement] struct and related types.
//!
//! The [DeviceEngagement] struct represents a device engagement object, which contains information about a device's engagement with a server.
//! The [DeviceEngagement] struct represents a device engagement object, which contains information about a device's engagement with a server.
//! It includes fields such as the `version`, `security details, `device retrieval methods, `server retrieval methods, and `protocol information.
//!
//! The module also provides implementations for conversions between [DeviceEngagement] and [ciborium::Value], as well as other utility functions.
Expand Down Expand Up @@ -76,7 +76,7 @@ pub enum DeviceRetrievalMethod {

/// Represents the BLE options for device engagement.
///
/// This struct is used to configure the BLE options for device engagement.
/// This struct is used to configure the BLE options for device engagement.
/// It contains the necessary parameters and settings for BLE communication.
BLE(BleOptions),

Expand Down
2 changes: 1 addition & 1 deletion src/definitions/device_engagement/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::definitions::helpers::tag24::Error as Tag24Error;
/// Errors that can occur when deserialising a DeviceEngagement.
#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
pub enum Error {
#[error("Expected isomdl version 1.0")]
#[error("Expected isomdl major version 1")]
UnsupportedVersion,
#[error("Unsupported device retrieval method")]
UnsupportedDRM,
Expand Down
1 change: 0 additions & 1 deletion src/definitions/device_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ pub type ReaderAuth = MaybeTagged<CoseSign1>;
/// Represents a device request.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]

pub struct DeviceRequest {
/// The version of the device request.
pub version: String,
Expand Down
2 changes: 1 addition & 1 deletion src/definitions/helpers/non_empty_vec.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use serde::{Deserialize, Serialize};
use std::ops::Deref;

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, Hash)]
#[serde(try_from = "Vec<T>", into = "Vec<T>")]
pub struct NonEmptyVec<T: Clone>(Vec<T>);

Expand Down
1 change: 1 addition & 0 deletions src/definitions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub mod namespaces;
pub mod session;
pub mod traits;
pub mod validity_info;
pub mod x509;

pub use device_engagement::{
BleOptions, DeviceEngagement, DeviceRetrievalMethod, NfcOptions, Security, WifiOptions,
Expand Down
12 changes: 6 additions & 6 deletions src/definitions/namespaces/latin1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,12 @@ mod test {
fn upper_latin() {
#[allow(clippy::invisible_characters)]
let upper_latin_chars = vec![
' ', '¡', '¢', '£', '¤', '¥', '¦', '§', '¨', '©', 'ª', '«', '¬', '­', '®', '¯', '°',
'±', '²', '³', '´', 'µ', '¶', '·', '¸', '¹', 'º', '»', '¼', '½', '¾', '¿', 'À', 'Á',
'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò',
'Ó', 'Ô', 'Õ', 'Ö', '×', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'Þ', 'ß', 'à', 'á', 'â', 'ã',
'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ñ', 'ò', 'ó', 'ô',
'õ', 'ö', '÷', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'þ', 'ÿ',
' ', '¡', '¢', '£', '¤', '¥', '¦', '§', '¨', '©', 'ª', '«', '¬', '\u{AD}', '®', '¯',
'°', '±', '²', '³', '´', 'µ', '¶', '·', '¸', '¹', 'º', '»', '¼', '½', '¾', '¿', 'À',
'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ',
'Ò', 'Ó', 'Ô', 'Õ', 'Ö', '×', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'Þ', 'ß', 'à', 'á', 'â',
'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ñ', 'ò', 'ó',
'ô', 'õ', 'ö', '÷', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'þ', 'ÿ',
];
assert!(upper_latin_chars.iter().all(is_upper_latin));
}
Expand Down
57 changes: 57 additions & 0 deletions src/definitions/x509/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use crate::definitions::device_key::cose_key::Error as CoseError;
use crate::definitions::helpers::non_empty_vec;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, thiserror::Error)]
pub enum Error {
#[error("Error occurred while validating x509 certificate: {0}")]
ValidationError(String),
#[error("Error occurred while decoding a x509 certificate: {0}")]
DecodingError(String),
#[error("Error decoding cbor")]
CborDecodingError,
#[error("Error decoding json")]
JsonError,
}

impl From<serde_json::Error> for Error {
fn from(_: serde_json::Error) -> Self {
Error::JsonError
}
}

impl From<x509_cert::der::Error> for Error {
fn from(value: x509_cert::der::Error) -> Self {
Error::ValidationError(value.to_string())
}
}

impl From<p256::ecdsa::Error> for Error {
fn from(value: p256::ecdsa::Error) -> Self {
Error::ValidationError(value.to_string())
}
}

impl From<x509_cert::spki::Error> for Error {
fn from(value: x509_cert::spki::Error) -> Self {
Error::ValidationError(value.to_string())
}
}

impl From<CoseError> for Error {
fn from(value: CoseError) -> Self {
Error::ValidationError(value.to_string())
}
}

impl From<non_empty_vec::Error> for Error {
fn from(value: non_empty_vec::Error) -> Self {
Error::ValidationError(value.to_string())
}
}

impl From<asn1_rs::Error> for Error {
fn from(value: asn1_rs::Error) -> Self {
Error::ValidationError(value.to_string())
}
}
Loading
Loading