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

feat: support non utf8 strings #71

Merged
merged 2 commits into from
Jan 20, 2022
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
93 changes: 78 additions & 15 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ use ring::signature::KeyPair as RingKeyPair;
use ring::signature::{self, EcdsaSigningAlgorithm, EdDSAParameters};
use yasna::DERWriter;
use yasna::models::{GeneralizedTime, UTCTime};
use yasna::tags::{TAG_BMPSTRING, TAG_TELETEXSTRING, TAG_UNIVERSALSTRING};
use chrono::{DateTime, Timelike, Datelike};
use chrono::{NaiveDate, Utc};
use std::collections::HashMap;
Expand Down Expand Up @@ -370,6 +371,31 @@ impl DnType {
}
}

/// A distinguished name entry
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
est31 marked this conversation as resolved.
Show resolved Hide resolved
#[non_exhaustive]
pub enum DnValue {
/// A string of characters from the T.61 character set
TeletexString(Vec<u8>),
/// An ASCII string containing only A-Z, a-z, 0-9, '()+,-./:=? and <SPACE>
PrintableString(String),
/// A string encoded using UTF-32
UniversalString(Vec<u8>),
/// A string encoded using UTF-8
Utf8String(String),
/// A string encoded using UCS-2
BmpString(Vec<u8>),
}

impl<T> From<T> for DnValue
where
T :Into<String>
{
fn from(t :T) -> Self {
DnValue::Utf8String(t.into())
}
}

#[derive(Debug, PartialEq, Eq, Clone)]
/**
Distinguished name used e.g. for the issuer and subject fields of a certificate
Expand All @@ -382,7 +408,7 @@ See also the RFC 5280 sections on the [issuer](https://tools.ietf.org/html/rfc52
and [subject](https://tools.ietf.org/html/rfc5280#section-4.1.2.6) fields.
*/
pub struct DistinguishedName {
entries :HashMap<DnType, String>,
entries :HashMap<DnType, DnValue>,
order :Vec<DnType>,
}

Expand All @@ -395,11 +421,8 @@ impl DistinguishedName {
}
}
/// Obtains the attribute value for the given attribute type
pub fn get(&self, ty :&DnType) -> Option<&str> {
self.entries.get(ty).map(|s| {
let s :&str = s;
s
})
pub fn get(&self, ty :&DnType) -> Option<&DnValue> {
self.entries.get(ty)
}
/// Removes the attribute with the specified DnType
///
Expand All @@ -414,7 +437,16 @@ impl DistinguishedName {
removed
}
/// Inserts or updates an attribute that consists of type and name
pub fn push(&mut self, ty :DnType, s :impl Into<String>) {
///
/// ```
/// # use rcgen::{DistinguishedName, DnType, DnValue};
/// let mut dn = DistinguishedName::new();
/// dn.push(DnType::OrganizationName, "Crab widgits SE");
/// dn.push(DnType::CommonName, DnValue::PrintableString("Master Cert".to_string()));
/// assert_eq!(dn.get(&DnType::OrganizationName), Some(&DnValue::Utf8String("Crab widgits SE".to_string())));
/// assert_eq!(dn.get(&DnType::CommonName), Some(&DnValue::PrintableString("Master Cert".to_string())));
/// ```
pub fn push(&mut self, ty :DnType, s :impl Into<DnValue>) {
if !self.entries.contains_key(&ty) {
self.order.push(ty.clone());
}
Expand All @@ -430,6 +462,8 @@ impl DistinguishedName {

#[cfg(feature = "x509-parser")]
fn from_name(name :&x509_parser::x509::X509Name) -> Result<Self, RcgenError> {
use x509_parser::der_parser::der::DerObjectContent;

let mut dn = DistinguishedName::new();
for rdn in name.iter() {
let mut rdn_iter = rdn.iter();
Expand All @@ -444,14 +478,19 @@ impl DistinguishedName {
} else {
panic!("x509-parser distinguished name set is empty");
};
let value = attr.attr_value().as_slice()
.or(Err(RcgenError::CouldNotParseCertificate))?;

let attr_type_oid = attr.attr_type().iter()
.ok_or(RcgenError::CouldNotParseCertificate)?;
let dn_type = DnType::from_oid(&attr_type_oid.collect::<Vec<_>>());
let dn_value = String::from_utf8(value.into())
.or(Err(RcgenError::CouldNotParseCertificate))?;
let dn_value = match attr.attr_value().content {
DerObjectContent::T61String(s) => DnValue::TeletexString(s.into()),
DerObjectContent::PrintableString(s) => DnValue::PrintableString(s.into()),
DerObjectContent::UniversalString(s) => DnValue::UniversalString(s.into()),
DerObjectContent::UTF8String(s) => DnValue::Utf8String(s.into()),
DerObjectContent::BmpString(s) => DnValue::BmpString(s.into()),
_ => return Err(RcgenError::CouldNotParseCertificate),
};

dn.push(dn_type, dn_value);
}
Ok(dn)
Expand All @@ -467,12 +506,12 @@ pub struct DistinguishedNameIterator<'a> {
}

impl <'a> Iterator for DistinguishedNameIterator<'a> {
type Item = (&'a DnType, &'a str);
type Item = (&'a DnType, &'a DnValue);

fn next(&mut self) -> Option<Self::Item> {
self.iter.next()
.and_then(|ty| {
self.distinguished_name.entries.get(ty).map(|v| (ty, v.as_str()))
self.distinguished_name.entries.get(ty).map(|v| (ty, v))
})
}
}
Expand Down Expand Up @@ -699,7 +738,19 @@ impl CertificateParams {
writer.next().write_set(|writer| {
writer.next().write_sequence(|writer| {
writer.next().write_oid(&ty.to_oid());
writer.next().write_utf8_string(content);
match content {
DnValue::TeletexString(s) => writer.next().write_tagged_implicit(TAG_TELETEXSTRING, |writer| {
writer.write_bytes(s)
}),
DnValue::PrintableString(s) => writer.next().write_printable_string(s),
DnValue::UniversalString(s) => writer.next().write_tagged_implicit(TAG_UNIVERSALSTRING, |writer| {
writer.write_bytes(s)
}),
DnValue::Utf8String(s) => writer.next().write_utf8_string(s),
DnValue::BmpString(s) => writer.next().write_tagged_implicit(TAG_BMPSTRING, |writer| {
writer.write_bytes(s)
}),
}
});
});
}
Expand Down Expand Up @@ -1195,7 +1246,19 @@ fn write_distinguished_name(writer :DERWriter, dn :&DistinguishedName) {
writer.next().write_set(|writer| {
writer.next().write_sequence(|writer| {
writer.next().write_oid(&ty.to_oid());
writer.next().write_utf8_string(content);
match content {
DnValue::TeletexString(s) => writer.next().write_tagged_implicit(TAG_TELETEXSTRING, |writer| {
writer.write_bytes(s)
}),
DnValue::PrintableString(s) => writer.next().write_printable_string(s),
DnValue::UniversalString(s) => writer.next().write_tagged_implicit(TAG_UNIVERSALSTRING, |writer| {
writer.write_bytes(s)
}),
DnValue::Utf8String(s) => writer.next().write_utf8_string(s),
DnValue::BmpString(s) => writer.next().write_tagged_implicit(TAG_BMPSTRING, |writer| {
writer.write_bytes(s)
}),
}
});
});
}
Expand Down
29 changes: 29 additions & 0 deletions tests/botan.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
extern crate botan;
extern crate rcgen;

#[cfg(feature = "x509-parser")]
use rcgen::DnValue;
use rcgen::{BasicConstraints, Certificate, CertificateParams, DnType, IsCa};

mod util;
Expand Down Expand Up @@ -174,3 +176,30 @@ fn test_botan_imported_ca() {

check_cert_ca(&cert_der, &cert, &ca_cert_der);
}

#[cfg(feature = "x509-parser")]
#[test]
fn test_botan_imported_ca_with_printable_string() {
use std::convert::TryInto;
let mut params = default_params();
params.distinguished_name.push(DnType::CountryName, DnValue::PrintableString("US".to_string()));
params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
let ca_cert = Certificate::from_params(params).unwrap();

let (ca_cert_der, ca_key_der) = (ca_cert.serialize_der().unwrap(), ca_cert.serialize_private_key_der());

let ca_key_pair = ca_key_der.as_slice().try_into().unwrap();
let imported_ca_cert_params = CertificateParams::from_ca_cert_der(ca_cert_der.as_slice(), ca_key_pair)
.unwrap();
let imported_ca_cert = Certificate::from_params(imported_ca_cert_params).unwrap();

let mut params = CertificateParams::new(vec!["crabs.crabs".to_string()]);
params.distinguished_name.push(DnType::OrganizationName, "Crab widgits SE");
params.distinguished_name.push(DnType::CommonName, "Dev domain");
// Botan has a sanity check that enforces a maximum expiration date
params.not_after = rcgen::date_time_ymd(3016, 01, 01);
let cert = Certificate::from_params(params).unwrap();
let cert_der = cert.serialize_der_with_signer(&imported_ca_cert).unwrap();

check_cert_ca(&cert_der, &cert, &ca_cert_der);
}
20 changes: 19 additions & 1 deletion tests/openssl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ extern crate openssl;
extern crate rcgen;

use rcgen::{Certificate, NameConstraints, GeneralSubtree, IsCa,
BasicConstraints, CertificateParams, DnType};
BasicConstraints, CertificateParams, DnType, DnValue};
use openssl::pkey::PKey;
use openssl::x509::{X509, X509Req, X509StoreContext};
use openssl::x509::store::{X509StoreBuilder, X509Store};
Expand Down Expand Up @@ -325,6 +325,24 @@ fn test_openssl_separate_ca() {
verify_cert_ca(&cert_pem, &key, &ca_cert_pem);
}

#[test]
fn test_openssl_separate_ca_with_printable_string() {
let mut params = util::default_params();
params.distinguished_name.push(DnType::CountryName, DnValue::PrintableString("US".to_string()));
params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
let ca_cert = Certificate::from_params(params).unwrap();
let ca_cert_pem = ca_cert.serialize_pem().unwrap();

let mut params = CertificateParams::new(vec!["crabs.crabs".to_string()]);
params.distinguished_name.push(DnType::OrganizationName, "Crab widgits SE");
params.distinguished_name.push(DnType::CommonName, "Dev domain");
let cert = Certificate::from_params(params).unwrap();
let cert_pem = cert.serialize_pem_with_signer(&ca_cert).unwrap();
let key = cert.serialize_private_key_der();

verify_cert_ca(&cert_pem, &key, &ca_cert_pem);
}

#[test]
fn test_openssl_separate_ca_with_other_signing_alg() {
let mut params = util::default_params();
Expand Down
30 changes: 29 additions & 1 deletion tests/webpki.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ extern crate ring;
extern crate pem;

#[cfg(feature = "x509-parser")]
use rcgen::CertificateSigningRequest;
use rcgen::{CertificateSigningRequest, DnValue};
use rcgen::{BasicConstraints, Certificate, CertificateParams, DnType, IsCa, KeyPair, RemoteKeyPair};
use webpki::{EndEntityCert, TlsServerTrustAnchors, TrustAnchor};
use webpki::SignatureAlgorithm;
Expand Down Expand Up @@ -362,6 +362,34 @@ fn test_webpki_imported_ca() {
&webpki::ECDSA_P256_SHA256, &webpki::ECDSA_P256_SHA256, sign_fn);
}

#[cfg(feature = "x509-parser")]
#[test]
fn test_webpki_imported_ca_with_printable_string() {
use std::convert::TryInto;
let mut params = util::default_params();
params.distinguished_name.push(DnType::CountryName, DnValue::PrintableString("US".to_string()));
params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
let ca_cert = Certificate::from_params(params).unwrap();

let (ca_cert_der, ca_key_der) = (ca_cert.serialize_der().unwrap(), ca_cert.serialize_private_key_der());

let ca_key_pair = ca_key_der.as_slice().try_into().unwrap();
let imported_ca_cert_params = CertificateParams::from_ca_cert_der(ca_cert_der.as_slice(), ca_key_pair)
.unwrap();
let imported_ca_cert = Certificate::from_params(imported_ca_cert_params).unwrap();

let mut params = CertificateParams::new(vec!["crabs.crabs".to_string()]);
params.distinguished_name.push(DnType::OrganizationName, "Crab widgits SE");
params.distinguished_name.push(DnType::CommonName, "Dev domain");
let cert = Certificate::from_params(params).unwrap();
let cert_der = cert.serialize_der_with_signer(&imported_ca_cert).unwrap();

let sign_fn = |cert, msg| sign_msg_ecdsa(cert, msg,
&signature::ECDSA_P256_SHA256_ASN1_SIGNING);
check_cert_ca(&cert_der, &cert, &ca_cert_der,
&webpki::ECDSA_P256_SHA256, &webpki::ECDSA_P256_SHA256, sign_fn);
}

#[cfg(feature = "x509-parser")]
#[test]
fn test_certificate_from_csr() {
Expand Down