Skip to content

Commit

Permalink
Add IssuerAuth, MdocAuth, ReaderAuth checks (#75)
Browse files Browse the repository at this point in the history
This PR adds support for the mdoc holder to validate the ReaderAuth, and the mdoc reader to validate the mdoc auth and issuer auth.

Remaining outstanding work items:

* Check CRL of DS and IACA certificates.
* Check CRL/OCSP for reader and reader CA certificates.
* Add support for producing ReaderAuth secured document requests.
* Add support for key curves other than P-256.
* Perform validation of particular mDL attributes (e.g. country name matches certificate).

---------

Co-authored-by: Jacob <[email protected]>
  • Loading branch information
justAnIdentity and cobward authored Dec 20, 2024
1 parent 72d8f61 commit b3a0317
Show file tree
Hide file tree
Showing 48 changed files with 2,939 additions and 572 deletions.
20 changes: 16 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,20 @@ 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.9", 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"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_bytes = "0.11.0"
sha2 = "0.10.6"
sha2 = { version = "0.10.8", features = ["oid"] }
thiserror = "1.0"
elliptic-curve = "0.13.1"
hkdf = "0.12.3"
Expand All @@ -36,21 +40,29 @@ 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"

coset = "0.3.8"
ciborium = "0.2.2"
digest = "0.10.7"
tracing = "0.1.41"
sha1 = "0.10.6"

[dev-dependencies]
hex = "0.4.3"
p256 = "0.13.0"
rstest = "0.23.0"
serde_json = "*"
test-log = { version = "0.2.16", features = ["trace"] }
x509-cert = { version = "0.2.4", features = ["pem", "builder", "hazmat"] }
83 changes: 83 additions & 0 deletions src/bin/utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
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,
}

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()
}
}
32 changes: 32 additions & 0 deletions src/bin/x509/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use der::DecodePem;
use isomdl::definitions::x509::{
trust_anchor::{TrustAnchor, TrustAnchorRegistry, TrustPurpose},
validation::ValidationRuleset,
X5Chain,
};
use x509_cert::Certificate;

use crate::RuleSet;

pub fn validate(rules: RuleSet, signer: &[u8], root: &[u8]) -> Result<Vec<String>, anyhow::Error> {
let root = Certificate::from_pem(root)?;

let trust_anchor = TrustAnchor {
certificate: root,
purpose: TrustPurpose::Iaca,
};

let trust_anchor_registry = TrustAnchorRegistry {
anchors: vec![trust_anchor],
};

let x5chain = X5Chain::builder().with_pem_certificate(signer)?.build()?;

let outcome = match rules {
RuleSet::Iaca => ValidationRuleset::Mdl,
RuleSet::Aamva => ValidationRuleset::AamvaMdl,
}
.validate(&x5chain, &trust_anchor_registry);

Ok(outcome.errors)
}
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
Loading

0 comments on commit b3a0317

Please sign in to comment.