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

project: apply cargo fmt universally, verify in CI. #146

Merged
merged 5 commits into from
Sep 7, 2023
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
15 changes: 15 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,21 @@ env:
RUSTDOCFLAGS: -D warnings

jobs:
rustfmt:
name: Format
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
with:
persist-credentials: false
- name: Install rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt
- name: Check formatting
run: cargo fmt -- --check

clippy:
name: Clippy
runs-on: ubuntu-latest
Expand Down
2 changes: 2 additions & 0 deletions .rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
hard_tabs = true
match_block_trailing_comma = true
18 changes: 9 additions & 9 deletions examples/rsa-irc-openssl.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
#![allow(clippy::complexity, clippy::style, clippy::pedantic)]

use rcgen::{Certificate, CertificateParams,
DistinguishedName, date_time_ymd};
use std::fs;
use rcgen::{date_time_ymd, Certificate, CertificateParams, DistinguishedName};
use std::convert::TryInto;
use std::fs;

fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut params :CertificateParams = Default::default();
let mut params: CertificateParams = Default::default();
params.not_before = date_time_ymd(2021, 05, 19);
params.not_after = date_time_ymd(4096, 01, 01);
params.distinguished_name = DistinguishedName::new();

params.alg = &rcgen::PKCS_RSA_SHA256;

let pkey :openssl::pkey::PKey<_> = openssl::rsa::Rsa::generate(2048)?.try_into()?;
let pkey: openssl::pkey::PKey<_> = openssl::rsa::Rsa::generate(2048)?.try_into()?;
let key_pair_pem = String::from_utf8(pkey.private_key_to_pem_pkcs8()?)?;
let key_pair = rcgen::KeyPair::from_pem(&key_pair_pem)?;
params.key_pair = Some(key_pair);
Expand All @@ -23,16 +22,17 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let pem = pem::parse(&pem_serialized)?;
let der_serialized = pem.contents();
let hash = ring::digest::digest(&ring::digest::SHA512, &der_serialized);
let hash_hex :String = hash.as_ref().iter()
.map(|b| format!("{b:02x}"))
.collect();
let hash_hex: String = hash.as_ref().iter().map(|b| format!("{b:02x}")).collect();
println!("sha-512 fingerprint: {hash_hex}");
println!("{pem_serialized}");
println!("{}", cert.serialize_private_key_pem());
std::fs::create_dir_all("certs/")?;
fs::write("certs/cert.pem", &pem_serialized.as_bytes())?;
fs::write("certs/cert.der", &der_serialized)?;
fs::write("certs/key.pem", &cert.serialize_private_key_pem().as_bytes())?;
fs::write(
"certs/key.pem",
&cert.serialize_private_key_pem().as_bytes(),
)?;
fs::write("certs/key.der", &cert.serialize_private_key_der())?;
Ok(())
}
22 changes: 11 additions & 11 deletions examples/rsa-irc.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
#![allow(clippy::complexity, clippy::style, clippy::pedantic)]

use rsa::RsaPrivateKey;
use rsa::pkcs8::EncodePrivateKey;
use rand::rngs::OsRng;
use rsa::pkcs8::EncodePrivateKey;
use rsa::RsaPrivateKey;

use rcgen::{Certificate, CertificateParams,
DistinguishedName, date_time_ymd};
use std::fs;
use rcgen::{date_time_ymd, Certificate, CertificateParams, DistinguishedName};
use std::convert::TryFrom;
use std::fs;

fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut params :CertificateParams = Default::default();
let mut params: CertificateParams = Default::default();
params.not_before = date_time_ymd(2021, 05, 19);
params.not_after = date_time_ymd(4096, 01, 01);
params.distinguished_name = DistinguishedName::new();

params.alg = &rcgen::PKCS_RSA_SHA256;

let mut rng = OsRng;
let bits = 2048;
let bits = 2048;
let private_key = RsaPrivateKey::new(&mut rng, bits)?;
let private_key_der = private_key.to_pkcs8_der()?;
let key_pair = rcgen::KeyPair::try_from(private_key_der.as_bytes()).unwrap();
Expand All @@ -29,16 +28,17 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let pem = pem::parse(&pem_serialized)?;
let der_serialized = pem.contents();
let hash = ring::digest::digest(&ring::digest::SHA512, &der_serialized);
let hash_hex :String = hash.as_ref().iter()
.map(|b| format!("{:02x}", b))
.collect();
let hash_hex: String = hash.as_ref().iter().map(|b| format!("{:02x}", b)).collect();
println!("sha-512 fingerprint: {hash_hex}");
println!("{pem_serialized}");
println!("{}", cert.serialize_private_key_pem());
std::fs::create_dir_all("certs/")?;
fs::write("certs/cert.pem", &pem_serialized.as_bytes())?;
fs::write("certs/cert.der", &der_serialized)?;
fs::write("certs/key.pem", &cert.serialize_private_key_pem().as_bytes())?;
fs::write(
"certs/key.pem",
&cert.serialize_private_key_pem().as_bytes(),
)?;
fs::write("certs/key.der", &cert.serialize_private_key_der())?;
Ok(())
}
123 changes: 75 additions & 48 deletions src/crl.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
use yasna::Tag;
#[cfg(feature = "pem")]
use pem::Pem;
use yasna::DERWriter;
use time::OffsetDateTime;
use yasna::DERWriter;
use yasna::Tag;

use crate::{write_dt_utc_or_generalized, write_x509_extension, write_x509_authority_key_identifier, write_distinguished_name};
use crate::oid::*;
use crate::{Certificate, RcgenError, SerialNumber, SignatureAlgorithm, KeyIdMethod, KeyUsagePurpose};
use crate::ENCODE_CONFIG;
use crate::{
write_distinguished_name, write_dt_utc_or_generalized, write_x509_authority_key_identifier,
write_x509_extension,
};
use crate::{
Certificate, KeyIdMethod, KeyUsagePurpose, RcgenError, SerialNumber, SignatureAlgorithm,
};

/// A certificate revocation list (CRL)
///
Expand Down Expand Up @@ -44,12 +49,12 @@
/// println!("{}", crl.serialize_pem_with_signer(&issuer).unwrap());
///# }
pub struct CertificateRevocationList {
params :CertificateRevocationListParams,
params: CertificateRevocationListParams,
}

impl CertificateRevocationList {
/// Generates a new certificate revocation list (CRL) from the given parameters.
pub fn from_params(params :CertificateRevocationListParams) -> Result<Self, RcgenError> {
pub fn from_params(params: CertificateRevocationListParams) -> Result<Self, RcgenError> {
if params.next_update.le(&params.this_update) {
return Err(RcgenError::InvalidCrlNextUpdate);
}
Expand All @@ -61,8 +66,10 @@
}
/// Serializes the certificate revocation list (CRL) in binary DER format, signed with
/// the issuing certificate authority's key.
pub fn serialize_der_with_signer(&self, ca :&Certificate) -> Result<Vec<u8>, RcgenError> {
if !ca.params.key_usages.is_empty() && !ca.params.key_usages.contains(&KeyUsagePurpose::CrlSign) {
pub fn serialize_der_with_signer(&self, ca: &Certificate) -> Result<Vec<u8>, RcgenError> {
if !ca.params.key_usages.is_empty()
&& !ca.params.key_usages.contains(&KeyUsagePurpose::CrlSign)
{
return Err(RcgenError::IssuerNotCrlSigner);
}
self.params.serialize_der_with_signer(ca)
Expand All @@ -72,7 +79,7 @@
///
/// *This function is only available if rcgen is built with the "pem" feature*
#[cfg(feature = "pem")]
pub fn serialize_pem_with_signer(&self, ca :&Certificate) -> Result<String, RcgenError> {
pub fn serialize_pem_with_signer(&self, ca: &Certificate) -> Result<String, RcgenError> {
let contents = self.serialize_der_with_signer(ca)?;
let p = Pem::new("X509 CRL", contents);
Ok(pem::encode_config(&p, ENCODE_CONFIG))
Expand All @@ -86,34 +93,41 @@
pub struct CrlDistributionPoint {
/// One or more URI distribution point names, indicating a place the current CRL can
/// be retrieved. When present, SHOULD include at least one LDAP or HTTP URI.
pub uris :Vec<String>,
pub uris: Vec<String>,
}

impl CrlDistributionPoint {
pub(crate) fn write_der(&self, writer :DERWriter) {
pub(crate) fn write_der(&self, writer: DERWriter) {
// DistributionPoint SEQUENCE
writer.write_sequence(|writer| {
write_distribution_point_name_uris(writer.next(), &self.uris);
});
}
}

fn write_distribution_point_name_uris<'a>(writer :DERWriter, uris: impl IntoIterator<Item = &'a String>) {
fn write_distribution_point_name_uris<'a>(
writer: DERWriter,
uris: impl IntoIterator<Item = &'a String>,
) {
// distributionPoint DistributionPointName
writer.write_tagged_implicit(Tag::context(0), |writer| {
writer.write_sequence(|writer| {
// fullName GeneralNames
writer.next().write_tagged_implicit(Tag::context(0), | writer| {
// GeneralNames
writer.write_sequence(|writer| {
for uri in uris.into_iter() {
// uniformResourceIdentifier [6] IA5String,
writer.next().write_tagged_implicit(Tag::context(6), |writer| {
writer.write_ia5_string(uri)
});
}
})
});
writer
.next()
.write_tagged_implicit(Tag::context(0), |writer| {
// GeneralNames
writer.write_sequence(|writer| {
for uri in uris.into_iter() {
// uniformResourceIdentifier [6] IA5String,
writer
.next()
.write_tagged_implicit(Tag::context(6), |writer| {
writer.write_ia5_string(uri)
});
}
})
});
});
});
}
Expand Down Expand Up @@ -141,28 +155,28 @@
/// Parameters used for certificate revocation list (CRL) generation
pub struct CertificateRevocationListParams {
/// Issue date of the CRL.
pub this_update :OffsetDateTime,
pub this_update: OffsetDateTime,
/// The date by which the next CRL will be issued.
pub next_update :OffsetDateTime,
pub next_update: OffsetDateTime,
/// A monotonically increasing sequence number for a given CRL scope and issuer.
pub crl_number :SerialNumber,
pub crl_number: SerialNumber,
/// An optional CRL extension identifying the CRL distribution point and scope for a
/// particular CRL as described in RFC 5280 Section 5.2.5[^1].
///
/// [^1]: <https://datatracker.ietf.org/doc/html/rfc5280#section-5.2.5>
pub issuing_distribution_point :Option<CrlIssuingDistributionPoint>,
pub issuing_distribution_point: Option<CrlIssuingDistributionPoint>,
/// A list of zero or more parameters describing revoked certificates included in the CRL.
pub revoked_certs :Vec<RevokedCertParams>,
pub revoked_certs: Vec<RevokedCertParams>,
/// Signature algorithm to use when signing the serialized CRL.
pub alg :&'static SignatureAlgorithm,
pub alg: &'static SignatureAlgorithm,
/// Method to generate key identifiers from public keys
///
/// Defaults to SHA-256.
pub key_identifier_method :KeyIdMethod,
pub key_identifier_method: KeyIdMethod,
}

impl CertificateRevocationListParams {
fn serialize_der_with_signer(&self, ca :&Certificate) -> Result<Vec<u8>, RcgenError> {
fn serialize_der_with_signer(&self, ca: &Certificate) -> Result<Vec<u8>, RcgenError> {
yasna::try_construct_der(|writer| {
// https://www.rfc-editor.org/rfc/rfc5280#section-5.1
writer.write_sequence(|writer| {
Expand All @@ -184,7 +198,7 @@
})
})
}
fn write_crl(&self, writer :DERWriter, ca :&Certificate) -> Result<(), RcgenError> {
fn write_crl(&self, writer: DERWriter, ca: &Certificate) -> Result<(), RcgenError> {
writer.write_sequence(|writer| {
// Write CRL version.
// RFC 5280 §5.1.2.1:
Expand Down Expand Up @@ -251,9 +265,14 @@

// Write issuing distribution point (if present).
if let Some(issuing_distribution_point) = &self.issuing_distribution_point {
write_x509_extension(writer.next(), OID_CRL_ISSUING_DISTRIBUTION_POINT, true, |writer| {
issuing_distribution_point.write_der(writer);
});
write_x509_extension(
writer.next(),
OID_CRL_ISSUING_DISTRIBUTION_POINT,
true,
|writer| {
issuing_distribution_point.write_der(writer);
},
);
}
});
});
Expand All @@ -267,14 +286,14 @@
/// [issuing distribution point extension](https://datatracker.ietf.org/doc/html/rfc5280#section-5.2.5).
pub struct CrlIssuingDistributionPoint {
/// The CRL's distribution point, containing a sequence of URIs the CRL can be retrieved from.
pub distribution_point :CrlDistributionPoint,
pub distribution_point: CrlDistributionPoint,
/// An optional description of the CRL's scope. If omitted, the CRL may contain
/// both user certs and CA certs.
pub scope :Option<CrlScope>,
pub scope: Option<CrlScope>,
}

impl CrlIssuingDistributionPoint {
fn write_der(&self, writer :DERWriter) {
fn write_der(&self, writer: DERWriter) {
// IssuingDistributionPoint SEQUENCE
writer.write_sequence(|writer| {
// distributionPoint [0] DistributionPointName OPTIONAL
Expand Down Expand Up @@ -309,19 +328,19 @@
/// Parameters used for describing a revoked certificate included in a [`CertificateRevocationList`].
pub struct RevokedCertParams {
/// Serial number identifying the revoked certificate.
pub serial_number :SerialNumber,
pub serial_number: SerialNumber,
/// The date at which the CA processed the revocation.
pub revocation_time :OffsetDateTime,
pub revocation_time: OffsetDateTime,
/// An optional reason code identifying why the certificate was revoked.
pub reason_code :Option<RevocationReason>,
pub reason_code: Option<RevocationReason>,
/// An optional field describing the date on which it was known or suspected that the
/// private key was compromised or the certificate otherwise became invalid. This date
/// may be earlier than the [`RevokedCertParams::revocation_time`].
pub invalidity_date :Option<OffsetDateTime>,
pub invalidity_date: Option<OffsetDateTime>,
}

impl RevokedCertParams {
fn write_der(&self, writer :DERWriter) {
fn write_der(&self, writer: DERWriter) {
writer.write_sequence(|writer| {
// Write serial number.
// RFC 5280 §4.1.2.2:
Expand All @@ -331,7 +350,9 @@
// Note: Non-conforming CAs may issue certificates with serial numbers
// that are negative or zero. Certificate users SHOULD be prepared to
// gracefully handle such certificates.
writer.next().write_bigint_bytes(self.serial_number.as_ref(), true);
writer
.next()
.write_bigint_bytes(self.serial_number.as_ref(), true);

// Write revocation date.
write_dt_utc_or_generalized(writer.next(), self.revocation_time);
Expand All @@ -342,7 +363,8 @@
// optional for conforming CRL issuers and applications. However, CRL
// issuers SHOULD include reason codes (Section 5.3.1) and invalidity
// dates (Section 5.3.2) whenever this information is available.
let has_reason_code = matches!(self.reason_code, Some(reason) if reason != RevocationReason::Unspecified);
let has_reason_code =
matches!(self.reason_code, Some(reason) if reason != RevocationReason::Unspecified);
let has_invalidity_date = self.invalidity_date.is_some();
if has_reason_code || has_invalidity_date {
writer.next().write_sequence(|writer| {
Expand All @@ -355,9 +377,14 @@

// Write invalidity date if present.
self.invalidity_date.map(|invalidity_date| {
write_x509_extension(writer.next(), OID_CRL_INVALIDITY_DATE, false, |writer| {
write_dt_utc_or_generalized(writer, invalidity_date);
})
write_x509_extension(
writer.next(),
OID_CRL_INVALIDITY_DATE,
false,
|writer| {
write_dt_utc_or_generalized(writer, invalidity_date);
},
)

Check warning on line 387 in src/crl.rs

View check run for this annotation

Codecov / codecov/patch

src/crl.rs#L380-L387

Added lines #L380 - L387 were not covered by tests
});
});
}
Expand Down
Loading