From b83edbad0d2a1074ea956e2049f4814894ea85c7 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 6 Nov 2016 14:07:34 -0800 Subject: [PATCH 01/15] Start on an X509Builder --- openssl-sys/src/lib.rs | 28 +++------- openssl-sys/src/ossl10x.rs | 1 + openssl-sys/src/ossl110.rs | 1 + openssl/src/asn1.rs | 2 + openssl/src/bn.rs | 9 ++++ openssl/src/x509/mod.rs | 105 ++++++++++++++++++++++++++++++++++++- openssl/src/x509/tests.rs | 33 +++++++++++- 7 files changed, 157 insertions(+), 22 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 496cc379cf..7fa7716a0a 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1259,6 +1259,7 @@ extern { pub fn ASN1_STRING_type_new(ty: c_int) -> *mut ASN1_STRING; pub fn ASN1_TIME_free(tm: *mut ASN1_TIME); pub fn ASN1_TIME_print(b: *mut BIO, tm: *const ASN1_TIME) -> c_int; + pub fn ASN1_INTEGER_free(x: *mut ASN1_INTEGER); pub fn BIO_ctrl(b: *mut BIO, cmd: c_int, larg: c_long, parg: *mut c_void) -> c_long; pub fn BIO_free_all(b: *mut BIO); @@ -1273,20 +1274,17 @@ extern { pub fn BIO_set_flags(b: *mut BIO, flags: c_int); pub fn BIO_clear_flags(b: *mut BIO, flags: c_int); + pub fn BN_CTX_new() -> *mut BN_CTX; + pub fn BN_CTX_free(ctx: *mut BN_CTX); + pub fn BN_new() -> *mut BIGNUM; pub fn BN_dup(n: *const BIGNUM) -> *mut BIGNUM; pub fn BN_clear(bn: *mut BIGNUM); pub fn BN_free(bn: *mut BIGNUM); pub fn BN_clear_free(bn: *mut BIGNUM); - - pub fn BN_CTX_new() -> *mut BN_CTX; - pub fn BN_CTX_free(ctx: *mut BN_CTX); - pub fn BN_num_bits(bn: *const BIGNUM) -> c_int; pub fn BN_set_negative(bn: *mut BIGNUM, n: c_int); pub fn BN_set_word(bn: *mut BIGNUM, n: BN_ULONG) -> c_int; - - /* Arithmetic operations on BIGNUMs */ pub fn BN_add(r: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM) -> c_int; pub fn BN_div(dv: *mut BIGNUM, rem: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; pub fn BN_exp(r: *mut BIGNUM, a: *const BIGNUM, p: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; @@ -1306,8 +1304,6 @@ extern { pub fn BN_mod_word(r: *const BIGNUM, w: BN_ULONG) -> BN_ULONG; pub fn BN_sqr(r: *mut BIGNUM, a: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; pub fn BN_sub(r: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM) -> c_int; - - /* Bit operations on BIGNUMs */ pub fn BN_clear_bit(a: *mut BIGNUM, n: c_int) -> c_int; pub fn BN_is_bit_set(a: *const BIGNUM, n: c_int) -> c_int; pub fn BN_lshift(r: *mut BIGNUM, a: *const BIGNUM, n: c_int) -> c_int; @@ -1316,33 +1312,22 @@ extern { pub fn BN_rshift(r: *mut BIGNUM, a: *const BIGNUM, n: c_int) -> c_int; pub fn BN_set_bit(a: *mut BIGNUM, n: c_int) -> c_int; pub fn BN_rshift1(r: *mut BIGNUM, a: *const BIGNUM) -> c_int; - - /* Comparisons on BIGNUMs */ pub fn BN_cmp(a: *const BIGNUM, b: *const BIGNUM) -> c_int; pub fn BN_ucmp(a: *const BIGNUM, b: *const BIGNUM) -> c_int; - - /* Prime handling */ pub fn BN_generate_prime_ex(r: *mut BIGNUM, bits: c_int, safe: c_int, add: *const BIGNUM, rem: *const BIGNUM, cb: *mut BN_GENCB) -> c_int; pub fn BN_is_prime_ex(p: *const BIGNUM, checks: c_int, ctx: *mut BN_CTX, cb: *mut BN_GENCB) -> c_int; pub fn BN_is_prime_fasttest_ex(p: *const BIGNUM, checks: c_int, ctx: *mut BN_CTX, do_trial_division: c_int, cb: *mut BN_GENCB) -> c_int; - - /* Random number handling */ pub fn BN_rand(r: *mut BIGNUM, bits: c_int, top: c_int, bottom: c_int) -> c_int; pub fn BN_pseudo_rand(r: *mut BIGNUM, bits: c_int, top: c_int, bottom: c_int) -> c_int; pub fn BN_rand_range(r: *mut BIGNUM, range: *const BIGNUM) -> c_int; pub fn BN_pseudo_rand_range(r: *mut BIGNUM, range: *const BIGNUM) -> c_int; - - /* Conversion from/to binary representation */ pub fn BN_bin2bn(s: *const u8, size: c_int, ret: *mut BIGNUM) -> *mut BIGNUM; pub fn BN_bn2bin(a: *const BIGNUM, to: *mut u8) -> c_int; - - /* Conversion from/to decimal string representation */ pub fn BN_dec2bn(a: *mut *mut BIGNUM, s: *const c_char) -> c_int; pub fn BN_bn2dec(a: *const BIGNUM) -> *mut c_char; - - /* Conversion from/to hexidecimal string representation */ pub fn BN_hex2bn(a: *mut *mut BIGNUM, s: *const c_char) -> c_int; pub fn BN_bn2hex(a: *const BIGNUM) -> *mut c_char; + pub fn BN_to_ASN1_INTEGER(bn: *const BIGNUM, ai: *mut ASN1_INTEGER) -> *mut ASN1_INTEGER; pub fn CRYPTO_memcmp(a: *const c_void, b: *const c_void, len: size_t) -> c_int; @@ -1665,6 +1650,8 @@ extern { pub fn X509_gmtime_adj(time: *mut ASN1_TIME, adj: c_long) -> *mut ASN1_TIME; pub fn X509_new() -> *mut X509; pub fn X509_set_issuer_name(x: *mut X509, name: *mut X509_NAME) -> c_int; + pub fn X509_set_subject_name(x: *mut X509, name: *mut X509_NAME) -> c_int; + pub fn X509_set_serialNumber(x: *mut X509, sn: *mut ASN1_INTEGER) -> c_int; pub fn X509_set_version(x: *mut X509, version: c_long) -> c_int; pub fn X509_set_pubkey(x: *mut X509, pkey: *mut EVP_PKEY) -> c_int; pub fn X509_sign(x: *mut X509, pkey: *mut EVP_PKEY, md: *const EVP_MD) -> c_int; @@ -1674,6 +1661,7 @@ extern { pub fn X509_EXTENSION_free(ext: *mut X509_EXTENSION); + pub fn X509_NAME_new() -> *mut X509_NAME; pub fn X509_NAME_free(x: *mut X509_NAME); pub fn X509_NAME_add_entry_by_txt(x: *mut X509_NAME, field: *const c_char, ty: c_int, bytes: *const c_uchar, len: c_int, loc: c_int, set: c_int) -> c_int; pub fn X509_NAME_get_index_by_NID(n: *mut X509_NAME, nid: c_int, last_pos: c_int) -> c_int; diff --git a/openssl-sys/src/ossl10x.rs b/openssl-sys/src/ossl10x.rs index 0cc75fca27..acaf85ec1b 100644 --- a/openssl-sys/src/ossl10x.rs +++ b/openssl-sys/src/ossl10x.rs @@ -586,6 +586,7 @@ extern { pub fn X509_set_notAfter(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int; pub fn X509_set_notBefore(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int; pub fn X509_get_ext_d2i(x: *mut ::X509, nid: c_int, crit: *mut c_int, idx: *mut c_int) -> *mut c_void; + pub fn X509_NAME_add_entry_by_NID(x: *mut ::X509_NAME, field: c_int, ty: c_int, bytes: *mut c_uchar, len: c_int, loc: c_int, set: c_int) -> c_int; pub fn X509_NAME_get_entry(n: *mut ::X509_NAME, loc: c_int) -> *mut ::X509_NAME_ENTRY; pub fn X509_NAME_ENTRY_get_data(ne: *mut ::X509_NAME_ENTRY) -> *mut ::ASN1_STRING; pub fn X509_STORE_CTX_get_chain(ctx: *mut ::X509_STORE_CTX) -> *mut stack_st_X509; diff --git a/openssl-sys/src/ossl110.rs b/openssl-sys/src/ossl110.rs index e8d62d732a..1d68b6011a 100644 --- a/openssl-sys/src/ossl110.rs +++ b/openssl-sys/src/ossl110.rs @@ -62,6 +62,7 @@ extern { pub fn X509_set1_notAfter(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int; pub fn X509_set1_notBefore(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int; pub fn X509_get_ext_d2i(x: *const ::X509, nid: c_int, crit: *mut c_int, idx: *mut c_int) -> *mut c_void; + pub fn X509_NAME_add_entry_by_NID(x: *mut ::X509_NAME, field: c_int, ty: c_int, bytes: *const c_uchar, len: c_int, loc: c_int, set: c_int) -> c_int; pub fn X509_NAME_get_entry(n: *const ::X509_NAME, loc: c_int) -> *mut ::X509_NAME_ENTRY; pub fn X509_NAME_ENTRY_get_data(ne: *const ::X509_NAME_ENTRY) -> *mut ::ASN1_STRING; pub fn X509V3_EXT_nconf_nid(conf: *mut ::CONF, ctx: *mut ::X509V3_CTX, ext_nid: c_int, value: *const c_char) -> *mut ::X509_EXTENSION; diff --git a/openssl/src/asn1.rs b/openssl/src/asn1.rs index c0a2359101..998f9878a9 100644 --- a/openssl/src/asn1.rs +++ b/openssl/src/asn1.rs @@ -63,6 +63,8 @@ impl Asn1StringRef { } } +type_!(Asn1Integer, Asn1IntegerRef, ffi::ASN1_INTEGER, ffi::ASN1_INTEGER_free); + #[cfg(any(ossl101, ossl102))] use ffi::ASN1_STRING_data; diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs index d52be88488..ec0b1aba35 100644 --- a/openssl/src/bn.rs +++ b/openssl/src/bn.rs @@ -6,6 +6,7 @@ use std::{fmt, ptr}; use std::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub, Deref}; use {cvt, cvt_p, cvt_n}; +use asn1::Asn1Integer; use crypto::CryptoString; use error::ErrorStack; use types::{OpenSslType, OpenSslTypeRef}; @@ -492,6 +493,14 @@ impl BigNumRef { Ok(CryptoString::from_null_terminated(buf)) } } + + /// Returns an `Asn1Integer` containing the value of `self`. + pub fn to_asn1_integer(&self) -> Result { + unsafe { + cvt_p(ffi::BN_to_ASN1_INTEGER(self.as_ptr(), ptr::null_mut())) + .map(|p| Asn1Integer::from_ptr(p)) + } + } } type_!(BigNum, BigNumRef, ffi::BIGNUM, ffi::BN_free); diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index e98e600646..f52e8844b4 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -12,7 +12,7 @@ use std::slice; use std::str; use {cvt, cvt_p}; -use asn1::{Asn1StringRef, Asn1Time, Asn1TimeRef}; +use asn1::{Asn1StringRef, Asn1Time, Asn1TimeRef, Asn1IntegerRef}; use bio::{MemBio, MemBioSlice}; use hash::MessageDigest; use pkey::{PKey, PKeyRef}; @@ -353,6 +353,58 @@ impl X509Generator { } } +pub struct X509Builder(X509); + +impl X509Builder { + pub fn new() -> Result { + unsafe { + cvt_p(ffi::X509_new()).map(|p| X509Builder(X509(p))) + } + } + + pub fn set_not_after(&mut self, not_after: &Asn1TimeRef) -> Result<(), ErrorStack> { + unsafe { cvt(X509_set_notAfter(self.0.as_ptr(), not_after.as_ptr())).map(|_| ()) } + } + + pub fn set_not_before(&mut self, not_before: &Asn1TimeRef) -> Result<(), ErrorStack> { + unsafe { cvt(X509_set_notBefore(self.0.as_ptr(), not_before.as_ptr())).map(|_| ()) } + } + + pub fn set_version(&mut self, version: i32) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::X509_set_version(self.0.as_ptr(), version.into())).map(|_| ()) } + } + + pub fn set_serial_number(&mut self, + serial_number: &Asn1IntegerRef) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::X509_set_serialNumber(self.0.as_ptr(), serial_number.as_ptr())).map(|_| ()) + } + } + + pub fn set_issuer_name(&mut self, issuer_name: &X509NameRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::X509_set_issuer_name(self.0.as_ptr(), issuer_name.as_ptr())).map(|_| ()) } + } + + pub fn set_subject_name(&mut self, subject_name: &X509NameRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::X509_set_subject_name(self.0.as_ptr(), subject_name.as_ptr())).map(|_| ()) + } + } + + pub fn set_pubkey(&mut self, key: &PKeyRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::X509_set_pubkey(self.0.as_ptr(), key.as_ptr())).map(|_| ()) } + } + + pub fn sign(&mut self, key: &PKeyRef, hash: MessageDigest) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::X509_sign(self.0.as_ptr(), key.as_ptr(), hash.as_ptr())).map(|_| ()) } + } + + pub fn build(self) -> X509 { + self.0 + } +} + type_!(X509, X509Ref, ffi::X509, ffi::X509_free); impl X509Ref { @@ -446,6 +498,11 @@ impl ToOwned for X509Ref { } impl X509 { + /// Returns a new builder. + pub fn builder() -> Result { + X509Builder::new() + } + /// Reads a certificate from DER. pub fn from_der(buf: &[u8]) -> Result { unsafe { @@ -497,9 +554,55 @@ impl Stackable for X509 { type StackType = ffi::stack_st_X509; } +pub struct X509NameBuilder(X509Name); + +impl X509NameBuilder { + pub fn new() -> Result { + unsafe { cvt_p(ffi::X509_NAME_new()).map(|p| X509NameBuilder(X509Name(p))) } + } + + pub fn append_entry_by_text(&mut self, field: &str, value: &str) -> Result<(), ErrorStack> { + unsafe { + let field = CString::new(field).unwrap(); + assert!(value.len() <= c_int::max_value() as usize); + cvt(ffi::X509_NAME_add_entry_by_txt(self.0.as_ptr(), + field.as_ptr() as *mut _, + ffi::MBSTRING_UTF8, + value.as_ptr(), + value.len() as c_int, + -1, + 0)) + .map(|_| ()) + } + } + + pub fn append_entry_by_nid(&mut self, field: Nid, value: &str) -> Result<(), ErrorStack> { + unsafe { + assert!(value.len() <= c_int::max_value() as usize); + cvt(ffi::X509_NAME_add_entry_by_NID(self.0.as_ptr(), + field.as_raw(), + ffi::MBSTRING_UTF8, + value.as_ptr() as *mut _, + value.len() as c_int, + -1, + 0)) + .map(|_| ()) + } + } + + pub fn build(self) -> X509Name { + self.0 + } +} + type_!(X509Name, X509NameRef, ffi::X509_NAME, ffi::X509_NAME_free); impl X509Name { + /// Returns a new builder. + pub fn builder() -> Result { + X509NameBuilder::new() + } + /// Loads subject names from a file containing PEM-formatted certificates. /// /// This is commonly used in conjunction with `SslContextBuilder::set_client_ca_list`. diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index 2527d53805..8dad875962 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -1,9 +1,11 @@ use serialize::hex::FromHex; +use asn1::Asn1Time; +use bn::{BigNum, MSB_MAYBE_ZERO}; use hash::MessageDigest; use pkey::PKey; use rsa::Rsa; -use x509::{X509, X509Generator}; +use x509::{X509, X509Generator, X509Name}; use x509::extension::Extension::{KeyUsage, ExtKeyUsage, SubjectAltName, OtherNid, OtherStr}; use x509::extension::AltNameOption as SAN; use x509::extension::KeyUsageOption::{DigitalSignature, KeyEncipherment}; @@ -174,3 +176,32 @@ fn test_subject_alt_name_iter() { Some(&b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01"[..])); assert!(subject_alt_names_iter.next().is_none()); } + +#[test] +fn test_x509_builder() { + let pkey = pkey(); + + let mut name = X509Name::builder().unwrap(); + name.append_entry_by_nid(nid::COMMONNAME, "foobar.com").unwrap(); + let name = name.build(); + + let mut builder = X509::builder().unwrap(); + builder.set_subject_name(&name).unwrap(); + builder.set_issuer_name(&name).unwrap(); + builder.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap(); + builder.set_not_after(&Asn1Time::days_from_now(365).unwrap()).unwrap(); + builder.set_pubkey(&pkey).unwrap(); + + let mut serial = BigNum::new().unwrap();; + serial.rand(128, MSB_MAYBE_ZERO, false).unwrap(); + builder.set_serial_number(&serial.to_asn1_integer().unwrap()).unwrap(); + + builder.sign(&pkey, MessageDigest::sha256()).unwrap(); + + let x509 = builder.build(); + + assert!(pkey.public_eq(&x509.public_key().unwrap())); + + let cn = x509.subject_name().entries_by_nid(nid::COMMONNAME).next().unwrap(); + assert_eq!("foobar.com".as_bytes(), cn.data().as_slice()); +} From 1939e6fd786c5626da4da74796ed0ffecfc07308 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 6 Nov 2016 14:49:26 -0800 Subject: [PATCH 02/15] Add conf module --- openssl-sys/src/lib.rs | 5 +++++ openssl/src/conf.rs | 28 ++++++++++++++++++++++++++++ openssl/src/lib.rs | 1 + 3 files changed, 34 insertions(+) create mode 100644 openssl/src/conf.rs diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 7fa7716a0a..3f7c8573bc 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -24,6 +24,7 @@ pub enum ASN1_TYPE {} pub enum BN_CTX {} pub enum BN_GENCB {} pub enum CONF {} +pub enum CONF_METHOD {} pub enum COMP_METHOD {} pub enum EC_KEY {} pub enum ENGINE {} @@ -1329,6 +1330,10 @@ extern { pub fn BN_bn2hex(a: *const BIGNUM) -> *mut c_char; pub fn BN_to_ASN1_INTEGER(bn: *const BIGNUM, ai: *mut ASN1_INTEGER) -> *mut ASN1_INTEGER; + pub fn NCONF_default() -> *mut CONF_METHOD; + pub fn NCONF_new(meth: *mut CONF_METHOD) -> *mut CONF; + pub fn NCONF_free(conf: *mut CONF); + pub fn CRYPTO_memcmp(a: *const c_void, b: *const c_void, len: size_t) -> c_int; diff --git a/openssl/src/conf.rs b/openssl/src/conf.rs new file mode 100644 index 0000000000..140c181721 --- /dev/null +++ b/openssl/src/conf.rs @@ -0,0 +1,28 @@ +use ffi; + +use cvt_p; +use error::ErrorStack; + +pub struct ConfMethod(*mut ffi::CONF_METHOD); + +impl ConfMethod { + pub fn default() -> ConfMethod { + unsafe { ConfMethod(ffi::NCONF_default()) } + } + + pub unsafe fn from_ptr(ptr: *mut ffi::CONF_METHOD) -> ConfMethod { + ConfMethod(ptr) + } + + pub fn as_ptr(&self) -> *mut ffi::CONF_METHOD { + self.0 + } +} + +type_!(Conf, ConfRef, ffi::CONF, ffi::NCONF_free); + +impl Conf { + pub fn new(method: ConfMethod) -> Result { + unsafe { cvt_p(ffi::NCONF_new(method.as_ptr())).map(Conf) } + } +} diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index a9d937ba8e..ec8d93ebcf 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -65,6 +65,7 @@ mod bio; mod util; pub mod asn1; pub mod bn; +pub mod conf; pub mod crypto; pub mod dh; pub mod dsa; From 5f18ffa4b3cee58053209f20317b0a88eb008e43 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 6 Nov 2016 21:58:43 -0800 Subject: [PATCH 03/15] Start of extension support --- openssl-sys/src/lib.rs | 1 + openssl/src/x509/extension.rs | 160 +++++++++++++++++++++++++++++++++- openssl/src/x509/mod.rs | 78 +++++++++++++++++ openssl/src/x509/tests.rs | 27 +++--- 4 files changed, 254 insertions(+), 12 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 3f7c8573bc..ac339a4b54 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1683,6 +1683,7 @@ extern { pub fn X509_STORE_CTX_get_error_depth(ctx: *mut X509_STORE_CTX) -> c_int; pub fn X509V3_set_ctx(ctx: *mut X509V3_CTX, issuer: *mut X509, subject: *mut X509, req: *mut X509_REQ, crl: *mut X509_CRL, flags: c_int); + pub fn X509V3_set_nconf(ctx: *mut X509V3_CTX, conf: *mut CONF); pub fn X509_REQ_add_extensions(req: *mut X509_REQ, exts: *mut stack_st_X509_EXTENSION) -> c_int; pub fn X509_REQ_sign(x: *mut X509_REQ, pkey: *mut EVP_PKEY, md: *const EVP_MD) -> c_int; diff --git a/openssl/src/x509/extension.rs b/openssl/src/x509/extension.rs index 398bbb3eda..d16dbea860 100644 --- a/openssl/src/x509/extension.rs +++ b/openssl/src/x509/extension.rs @@ -1,6 +1,8 @@ -use std::fmt; +use std::fmt::{self, Write}; +use error::ErrorStack; use nid::{self, Nid}; +use x509::X509Extension; /// Type-only version of the `Extension` enum. /// @@ -219,3 +221,159 @@ impl fmt::Display for AltNameOption { }) } } + +pub struct BasicConstraints { + critical: bool, + ca: bool, + pathlen: Option, +} + +impl BasicConstraints { + pub fn new() -> BasicConstraints { + BasicConstraints { + critical: false, + ca: false, + pathlen: None, + } + } + + pub fn critical(&mut self, critical: bool) -> &mut BasicConstraints { + self.critical = critical; + self + } + + pub fn ca(&mut self, ca: bool) -> &mut BasicConstraints { + self.ca = ca; + self + } + + pub fn pathlen(&mut self, pathlen: u32) -> &mut BasicConstraints { + self.pathlen = Some(pathlen); + self + } + + pub fn build(&self) -> Result { + let mut value = String::new(); + if self.critical { + value.push_str("critical,"); + } + value.push_str("CA:"); + if self.ca { + value.push_str("TRUE"); + } else { + value.push_str("FALSE"); + } + if let Some(pathlen) = self.pathlen { + write!(value, ",pathlen:{}", pathlen).unwrap(); + } + X509Extension::new_nid(None, None, nid::BASIC_CONSTRAINTS, &value) + } +} + +pub struct KeyUsage { + critical: bool, + digital_signature: bool, + non_repudiation: bool, + key_encipherment: bool, + data_encipherment: bool, + key_agreement: bool, + key_cert_sign: bool, + crl_sign: bool, + encipher_only: bool, + decipher_only: bool, +} + +impl KeyUsage { + pub fn new() -> KeyUsage { + KeyUsage { + critical: false, + digital_signature: false, + non_repudiation: false, + key_encipherment: false, + data_encipherment: false, + key_agreement: false, + key_cert_sign: false, + crl_sign: false, + encipher_only: false, + decipher_only: false, + } + } + + pub fn critical(&mut self, critical: bool) -> &mut KeyUsage { + self.critical = critical; + self + } + + pub fn digital_signature(&mut self, digital_signature: bool) -> &mut KeyUsage { + self.digital_signature = digital_signature; + self + } + + pub fn non_repudiation(&mut self, non_repudiation: bool) -> &mut KeyUsage { + self.non_repudiation = non_repudiation; + self + } + + pub fn key_encipherment(&mut self, key_encipherment: bool) -> &mut KeyUsage { + self.key_encipherment = key_encipherment; + self + } + + pub fn data_encipherment(&mut self, data_encipherment: bool) -> &mut KeyUsage { + self.data_encipherment = data_encipherment; + self + } + + pub fn key_agreement(&mut self, key_agreement: bool) -> &mut KeyUsage { + self.key_agreement = key_agreement; + self + } + + pub fn key_cert_sign(&mut self, key_cert_sign: bool) -> &mut KeyUsage { + self.key_cert_sign = key_cert_sign; + self + } + + pub fn crl_sign(&mut self, crl_sign: bool) -> &mut KeyUsage { + self.crl_sign = crl_sign; + self + } + + pub fn encipher_only(&mut self, encipher_only: bool) -> &mut KeyUsage { + self.encipher_only = encipher_only; + self + } + + pub fn decipher_only(&mut self, decipher_only: bool) -> &mut KeyUsage { + self.decipher_only = decipher_only; + self + } + + pub fn build(&self) -> Result { + let mut value = String::new(); + let mut first = true; + append(&mut value, &mut first, self.critical, "critical"); + append(&mut value, &mut first, self.digital_signature, "digitalSignature"); + append(&mut value, &mut first, self.non_repudiation, "nonRepudiation"); + append(&mut value, &mut first, self.key_encipherment, "keyEncipherment"); + append(&mut value, &mut first, self.data_encipherment, "dataEncipherment"); + append(&mut value, &mut first, self.key_agreement, "keyAgreement"); + append(&mut value, &mut first, self.key_cert_sign, "keyCertSign"); + append(&mut value, &mut first, self.crl_sign, "cRLSign"); + append(&mut value, &mut first, self.encipher_only, "encipherOnly"); + append(&mut value, &mut first, self.decipher_only, "decipherOnly"); + X509Extension::new_nid(None, None, nid::KEY_USAGE, &value) + } +} + +fn append(value: &mut String, first: &mut bool, should: bool, element: &str) { + if !should { + return; + } + + if !*first { + value.push(','); + } + *first = false; + value.push_str(element); +} diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index f52e8844b4..57d94ae1b5 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -5,6 +5,7 @@ use std::collections::HashMap; use std::error::Error; use std::ffi::{CStr, CString}; use std::fmt; +use std::marker::PhantomData; use std::mem; use std::path::Path; use std::ptr; @@ -14,6 +15,7 @@ use std::str; use {cvt, cvt_p}; use asn1::{Asn1StringRef, Asn1Time, Asn1TimeRef, Asn1IntegerRef}; use bio::{MemBio, MemBioSlice}; +use conf::ConfRef; use hash::MessageDigest; use pkey::{PKey, PKeyRef}; use rand::rand_bytes; @@ -396,6 +398,37 @@ impl X509Builder { unsafe { cvt(ffi::X509_set_pubkey(self.0.as_ptr(), key.as_ptr())).map(|_| ()) } } + pub fn x509v3_context<'a>(&'a self, + issuer: Option<&'a X509Ref>, + conf: Option<&'a ConfRef>) + -> X509v3Context<'a> { + unsafe { + let mut ctx = mem::zeroed(); + + let issuer = match issuer { + Some(issuer) => issuer.as_ptr(), + None => self.0.as_ptr(), + }; + let subject = self.0.as_ptr(); + ffi::X509V3_set_ctx(&mut ctx, issuer, subject, ptr::null_mut(), ptr::null_mut(), 0); + + // nodb case taken care of since we zeroed ctx above + if let Some(conf) = conf { + ffi::X509V3_set_nconf(&mut ctx, conf.as_ptr()); + } + + X509v3Context(ctx, PhantomData) + } + } + + pub fn append_extension(&mut self, extension: X509Extension) -> Result<(), ErrorStack> { + unsafe { + try!(cvt(ffi::X509_add_ext(self.0.as_ptr(), extension.as_ptr(), -1))); + mem::forget(extension); + Ok(()) + } + } + pub fn sign(&mut self, key: &PKeyRef, hash: MessageDigest) -> Result<(), ErrorStack> { unsafe { cvt(ffi::X509_sign(self.0.as_ptr(), key.as_ptr(), hash.as_ptr())).map(|_| ()) } } @@ -554,6 +587,51 @@ impl Stackable for X509 { type StackType = ffi::stack_st_X509; } +pub struct X509v3Context<'a>(ffi::X509V3_CTX, PhantomData<(&'a X509Ref, &'a ConfRef)>); + +impl<'a> X509v3Context<'a> { + pub fn as_ptr(&self) -> *mut ffi::X509V3_CTX { + &self.0 as *const _ as *mut _ + } +} + +type_!(X509Extension, X509ExtensionRef, ffi::X509_EXTENSION, ffi::X509_EXTENSION_free); + +impl X509Extension { + pub fn new(conf: Option<&ConfRef>, + context: Option<&X509v3Context>, + name: &str, + value: &str) + -> Result { + let name = CString::new(name).unwrap(); + let value = CString::new(value).unwrap(); + unsafe { + let conf = conf.map_or(ptr::null_mut(), ConfRef::as_ptr); + let context = context.map_or(ptr::null_mut(), X509v3Context::as_ptr); + let name = name.as_ptr() as *mut _; + let value = value.as_ptr() as *mut _; + + cvt_p(ffi::X509V3_EXT_nconf(conf, context, name, value)).map(X509Extension) + } + } + + pub fn new_nid(conf: Option<&ConfRef>, + context: Option<&X509v3Context>, + name: Nid, + value: &str) + -> Result { + let value = CString::new(value).unwrap(); + unsafe { + let conf = conf.map_or(ptr::null_mut(), ConfRef::as_ptr); + let context = context.map_or(ptr::null_mut(), X509v3Context::as_ptr); + let name = name.as_raw(); + let value = value.as_ptr() as *mut _; + + cvt_p(ffi::X509V3_EXT_nconf_nid(conf, context, name, value)).map(X509Extension) + } + } +} + pub struct X509NameBuilder(X509Name); impl X509NameBuilder { diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index 8dad875962..2d6341390f 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -6,7 +6,7 @@ use hash::MessageDigest; use pkey::PKey; use rsa::Rsa; use x509::{X509, X509Generator, X509Name}; -use x509::extension::Extension::{KeyUsage, ExtKeyUsage, SubjectAltName, OtherNid, OtherStr}; +use x509::extension::{Extension, BasicConstraints, KeyUsage}; use x509::extension::AltNameOption as SAN; use x509::extension::KeyUsageOption::{DigitalSignature, KeyEncipherment}; use x509::extension::ExtKeyUsageOption::{self, ClientAuth, ServerAuth}; @@ -17,13 +17,13 @@ fn get_generator() -> X509Generator { .set_valid_period(365 * 2) .add_name("CN".to_string(), "test_me".to_string()) .set_sign_hash(MessageDigest::sha1()) - .add_extension(KeyUsage(vec![DigitalSignature, KeyEncipherment])) - .add_extension(ExtKeyUsage(vec![ClientAuth, + .add_extension(Extension::KeyUsage(vec![DigitalSignature, KeyEncipherment])) + .add_extension(Extension::ExtKeyUsage(vec![ClientAuth, ServerAuth, ExtKeyUsageOption::Other("2.999.1".to_owned())])) - .add_extension(SubjectAltName(vec![(SAN::DNS, "example.com".to_owned())])) - .add_extension(OtherNid(nid::BASIC_CONSTRAINTS, "critical,CA:TRUE".to_owned())) - .add_extension(OtherStr("2.999.2".to_owned(), "ASN1:UTF8:example value".to_owned())) + .add_extension(Extension::SubjectAltName(vec![(SAN::DNS, "example.com".to_owned())])) + .add_extension(Extension::OtherNid(nid::BASIC_CONSTRAINTS, "critical,CA:TRUE".to_owned())) + .add_extension(Extension::OtherStr("2.999.2".to_owned(), "ASN1:UTF8:example value".to_owned())) } fn pkey() -> PKey { @@ -50,8 +50,8 @@ fn test_cert_gen() { fn test_cert_gen_extension_ordering() { let pkey = pkey(); get_generator() - .add_extension(OtherNid(nid::SUBJECT_KEY_IDENTIFIER, "hash".to_owned())) - .add_extension(OtherNid(nid::AUTHORITY_KEY_IDENTIFIER, "keyid:always".to_owned())) + .add_extension(Extension::OtherNid(nid::SUBJECT_KEY_IDENTIFIER, "hash".to_owned())) + .add_extension(Extension::OtherNid(nid::AUTHORITY_KEY_IDENTIFIER, "keyid:always".to_owned())) .sign(&pkey) .expect("Failed to generate cert with order-dependent extensions"); } @@ -62,8 +62,8 @@ fn test_cert_gen_extension_ordering() { fn test_cert_gen_extension_bad_ordering() { let pkey = pkey(); let result = get_generator() - .add_extension(OtherNid(nid::AUTHORITY_KEY_IDENTIFIER, "keyid:always".to_owned())) - .add_extension(OtherNid(nid::SUBJECT_KEY_IDENTIFIER, "hash".to_owned())) + .add_extension(Extension::OtherNid(nid::AUTHORITY_KEY_IDENTIFIER, "keyid:always".to_owned())) + .add_extension(Extension::OtherNid(nid::SUBJECT_KEY_IDENTIFIER, "hash".to_owned())) .sign(&pkey); assert!(result.is_err()); @@ -178,7 +178,7 @@ fn test_subject_alt_name_iter() { } #[test] -fn test_x509_builder() { +fn x509_builder() { let pkey = pkey(); let mut name = X509Name::builder().unwrap(); @@ -196,6 +196,11 @@ fn test_x509_builder() { serial.rand(128, MSB_MAYBE_ZERO, false).unwrap(); builder.set_serial_number(&serial.to_asn1_integer().unwrap()).unwrap(); + let basic_constraints = BasicConstraints::new().critical(true).ca(true).build().unwrap(); + builder.append_extension(basic_constraints).unwrap(); + let key_usage = KeyUsage::new().digital_signature(true).key_encipherment(true).build().unwrap(); + builder.append_extension(key_usage).unwrap(); + builder.sign(&pkey, MessageDigest::sha256()).unwrap(); let x509 = builder.build(); From d17c3355aba2491646cc80debfdbfdb6aa55b354 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 6 Nov 2016 22:52:53 -0800 Subject: [PATCH 04/15] More extension progress --- openssl/src/x509/extension.rs | 240 ++++++++++++++++++++++++++++++---- openssl/src/x509/tests.rs | 23 +++- 2 files changed, 235 insertions(+), 28 deletions(-) diff --git a/openssl/src/x509/extension.rs b/openssl/src/x509/extension.rs index d16dbea860..0af8ec11e4 100644 --- a/openssl/src/x509/extension.rs +++ b/openssl/src/x509/extension.rs @@ -2,7 +2,7 @@ use std::fmt::{self, Write}; use error::ErrorStack; use nid::{self, Nid}; -use x509::X509Extension; +use x509::{X509v3Context, X509Extension}; /// Type-only version of the `Extension` enum. /// @@ -237,13 +237,13 @@ impl BasicConstraints { } } - pub fn critical(&mut self, critical: bool) -> &mut BasicConstraints { - self.critical = critical; + pub fn critical(&mut self) -> &mut BasicConstraints { + self.critical = true; self } - pub fn ca(&mut self, ca: bool) -> &mut BasicConstraints { - self.ca = ca; + pub fn ca(&mut self) -> &mut BasicConstraints { + self.ca = true; self } @@ -299,53 +299,53 @@ impl KeyUsage { } } - pub fn critical(&mut self, critical: bool) -> &mut KeyUsage { - self.critical = critical; + pub fn critical(&mut self) -> &mut KeyUsage { + self.critical = true; self } - pub fn digital_signature(&mut self, digital_signature: bool) -> &mut KeyUsage { - self.digital_signature = digital_signature; + pub fn digital_signature(&mut self) -> &mut KeyUsage { + self.digital_signature = true; self } - pub fn non_repudiation(&mut self, non_repudiation: bool) -> &mut KeyUsage { - self.non_repudiation = non_repudiation; + pub fn non_repudiation(&mut self) -> &mut KeyUsage { + self.non_repudiation = true; self } - pub fn key_encipherment(&mut self, key_encipherment: bool) -> &mut KeyUsage { - self.key_encipherment = key_encipherment; + pub fn key_encipherment(&mut self) -> &mut KeyUsage { + self.key_encipherment = true; self } - pub fn data_encipherment(&mut self, data_encipherment: bool) -> &mut KeyUsage { - self.data_encipherment = data_encipherment; + pub fn data_encipherment(&mut self) -> &mut KeyUsage { + self.data_encipherment = true; self } - pub fn key_agreement(&mut self, key_agreement: bool) -> &mut KeyUsage { - self.key_agreement = key_agreement; + pub fn key_agreement(&mut self) -> &mut KeyUsage { + self.key_agreement = true; self } - pub fn key_cert_sign(&mut self, key_cert_sign: bool) -> &mut KeyUsage { - self.key_cert_sign = key_cert_sign; + pub fn key_cert_sign(&mut self) -> &mut KeyUsage { + self.key_cert_sign = true; self } - pub fn crl_sign(&mut self, crl_sign: bool) -> &mut KeyUsage { - self.crl_sign = crl_sign; + pub fn crl_sign(&mut self) -> &mut KeyUsage { + self.crl_sign = true; self } - pub fn encipher_only(&mut self, encipher_only: bool) -> &mut KeyUsage { - self.encipher_only = encipher_only; + pub fn encipher_only(&mut self) -> &mut KeyUsage { + self.encipher_only = true; self } - pub fn decipher_only(&mut self, decipher_only: bool) -> &mut KeyUsage { - self.decipher_only = decipher_only; + pub fn decipher_only(&mut self) -> &mut KeyUsage { + self.decipher_only = true; self } @@ -366,6 +366,196 @@ impl KeyUsage { } } +pub struct ExtendedKeyUsage { + critical: bool, + server_auth: bool, + client_auth: bool, + code_signing: bool, + email_protection: bool, + time_stamping: bool, + ms_code_ind: bool, + ms_code_com: bool, + ms_ctl_sign: bool, + ms_sgc: bool, + ms_efs: bool, + ns_sgc: bool, + other: Vec, +} + +impl ExtendedKeyUsage { + pub fn new() -> ExtendedKeyUsage { + ExtendedKeyUsage { + critical: false, + server_auth: false, + client_auth: false, + code_signing: false, + email_protection: false, + time_stamping: false, + ms_code_ind: false, + ms_code_com: false, + ms_ctl_sign: false, + ms_sgc: false, + ms_efs: false, + ns_sgc: false, + other: vec![], + } + } + + pub fn critical(&mut self) -> &mut ExtendedKeyUsage { + self.critical = true; + self + } + + pub fn server_auth(&mut self) -> &mut ExtendedKeyUsage { + self.server_auth = true; + self + } + + pub fn client_auth(&mut self) -> &mut ExtendedKeyUsage { + self.client_auth = true; + self + } + + pub fn code_signing(&mut self) -> &mut ExtendedKeyUsage { + self.code_signing = true; + self + } + + pub fn time_stamping(&mut self) -> &mut ExtendedKeyUsage { + self.time_stamping = true; + self + } + + pub fn ms_code_ind(&mut self) -> &mut ExtendedKeyUsage { + self.ms_code_ind = true; + self + } + + pub fn ms_code_com(&mut self) -> &mut ExtendedKeyUsage { + self.ms_code_com = true; + self + } + + pub fn ms_ctl_sign(&mut self) -> &mut ExtendedKeyUsage { + self.ms_ctl_sign = true; + self + } + + pub fn ms_sgc(&mut self) -> &mut ExtendedKeyUsage { + self.ms_sgc = true; + self + } + + pub fn ms_efs(&mut self) -> &mut ExtendedKeyUsage { + self.ms_efs = true; + self + } + + pub fn ns_sgc(&mut self) -> &mut ExtendedKeyUsage { + self.ns_sgc = true; + self + } + + pub fn other(&mut self, other: &str) -> &mut ExtendedKeyUsage { + self.other.push(other.to_owned()); + self + } + + pub fn build(&self) -> Result { + let mut value = String::new(); + let mut first = true; + append(&mut value, &mut first, self.critical, "critical"); + append(&mut value, &mut first, self.server_auth, "serverAuth"); + append(&mut value, &mut first, self.client_auth, "clientAuth"); + append(&mut value, &mut first, self.code_signing, "codeSigning"); + append(&mut value, &mut first, self.email_protection, "emailProtection"); + append(&mut value, &mut first, self.time_stamping, "timeStamping"); + append(&mut value, &mut first, self.ms_code_ind, "msCodeInd"); + append(&mut value, &mut first, self.ms_code_com, "msCodeCom"); + append(&mut value, &mut first, self.ms_ctl_sign, "msCTLSign"); + append(&mut value, &mut first, self.ms_sgc, "msSGC"); + append(&mut value, &mut first, self.ms_efs, "msEFS"); + append(&mut value, &mut first, self.ns_sgc, "nsSGC"); + for other in &self.other { + append(&mut value, &mut first, true, other); + } + X509Extension::new_nid(None, None, nid::EXT_KEY_USAGE, &value) + } +} + +pub struct SubjectKeyIdentifier { + critical: bool, +} + +impl SubjectKeyIdentifier { + pub fn new() -> SubjectKeyIdentifier { + SubjectKeyIdentifier { + critical: false, + } + } + + pub fn critical(&mut self) -> &mut SubjectKeyIdentifier { + self.critical = true; + self + } + + pub fn build(&self, ctx: &X509v3Context) -> Result { + let mut value = String::new(); + let mut first = true; + append(&mut value, &mut first, self.critical, "critical"); + append(&mut value, &mut first, true, "hash"); + X509Extension::new_nid(None, Some(ctx), nid::SUBJECT_KEY_IDENTIFIER, &value) + } +} + +pub struct AuthorityKeyIdentifier { + critical: bool, + keyid: Option, + issuer: Option, +} + +impl AuthorityKeyIdentifier { + pub fn new() -> AuthorityKeyIdentifier { + AuthorityKeyIdentifier { + critical: false, + keyid: None, + issuer: None, + } + } + + pub fn critical(&mut self) -> &mut AuthorityKeyIdentifier { + self.critical = true; + self + } + + pub fn keyid(&mut self, always: bool) -> &mut AuthorityKeyIdentifier { + self.keyid = Some(always); + self + } + + pub fn issuer(&mut self, always: bool) -> &mut AuthorityKeyIdentifier { + self.issuer = Some(always); + self + } + + pub fn build(&self, ctx: &X509v3Context) -> Result { + let mut value = String::new(); + let mut first = true; + append(&mut value, &mut first, self.critical, "critical"); + match self.keyid { + Some(true) => append(&mut value, &mut first, true, "keyid:always"), + Some(false) => append(&mut value, &mut first, true, "keyid"), + None => {} + } + match self.issuer { + Some(true) => append(&mut value, &mut first, true, "issuer:always"), + Some(false) => append(&mut value, &mut first, true, "issuer"), + None => {} + } + X509Extension::new_nid(None, Some(ctx), nid::AUTHORITY_KEY_IDENTIFIER, &value) + } +} + fn append(value: &mut String, first: &mut bool, should: bool, element: &str) { if !should { return; diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index 2d6341390f..a1ab6de555 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -6,7 +6,8 @@ use hash::MessageDigest; use pkey::PKey; use rsa::Rsa; use x509::{X509, X509Generator, X509Name}; -use x509::extension::{Extension, BasicConstraints, KeyUsage}; +use x509::extension::{Extension, BasicConstraints, KeyUsage, ExtendedKeyUsage, + SubjectKeyIdentifier, AuthorityKeyIdentifier}; use x509::extension::AltNameOption as SAN; use x509::extension::KeyUsageOption::{DigitalSignature, KeyEncipherment}; use x509::extension::ExtKeyUsageOption::{self, ClientAuth, ServerAuth}; @@ -196,10 +197,26 @@ fn x509_builder() { serial.rand(128, MSB_MAYBE_ZERO, false).unwrap(); builder.set_serial_number(&serial.to_asn1_integer().unwrap()).unwrap(); - let basic_constraints = BasicConstraints::new().critical(true).ca(true).build().unwrap(); + let basic_constraints = BasicConstraints::new().critical().ca().build().unwrap(); builder.append_extension(basic_constraints).unwrap(); - let key_usage = KeyUsage::new().digital_signature(true).key_encipherment(true).build().unwrap(); + let key_usage = KeyUsage::new().digital_signature().key_encipherment().build().unwrap(); builder.append_extension(key_usage).unwrap(); + let ext_key_usage = ExtendedKeyUsage::new() + .client_auth() + .server_auth() + .other("2.999.1") + .build() + .unwrap(); + builder.append_extension(ext_key_usage).unwrap(); + let subject_key_identifier = SubjectKeyIdentifier::new() + .build(&builder.x509v3_context(None, None)) + .unwrap(); + builder.append_extension(subject_key_identifier).unwrap(); + let authority_key_identifier = AuthorityKeyIdentifier::new() + .keyid(true) + .build(&builder.x509v3_context(None, None)) + .unwrap(); + builder.append_extension(authority_key_identifier).unwrap(); builder.sign(&pkey, MessageDigest::sha256()).unwrap(); From 8f7df7b2057bc31dfc3d6a2b83ee83116a8eb93a Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 6 Nov 2016 23:19:58 -0800 Subject: [PATCH 05/15] Add SubjectAlternativeName --- openssl/src/x509/extension.rs | 64 +++++++++++++++++++++++++++++++++++ openssl/src/x509/tests.rs | 7 +++- 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/openssl/src/x509/extension.rs b/openssl/src/x509/extension.rs index 0af8ec11e4..7a09ddbc69 100644 --- a/openssl/src/x509/extension.rs +++ b/openssl/src/x509/extension.rs @@ -556,6 +556,70 @@ impl AuthorityKeyIdentifier { } } +pub struct SubjectAlternativeName { + critical: bool, + names: Vec, +} + +impl SubjectAlternativeName { + pub fn new() -> SubjectAlternativeName { + SubjectAlternativeName { + critical: false, + names: vec![], + } + } + + pub fn critical(&mut self) -> &mut SubjectAlternativeName { + self.critical = true; + self + } + + pub fn email(&mut self, email: &str) -> &mut SubjectAlternativeName { + self.names.push(format!("email:{}", email)); + self + } + + pub fn uri(&mut self, uri: &str) -> &mut SubjectAlternativeName { + self.names.push(format!("URI:{}", uri)); + self + } + + pub fn dns(&mut self, dns: &str) -> &mut SubjectAlternativeName { + self.names.push(format!("DNS:{}", dns)); + self + } + + pub fn rid(&mut self, rid: &str) -> &mut SubjectAlternativeName { + self.names.push(format!("RID:{}", rid)); + self + } + + pub fn ip(&mut self, ip: &str) -> &mut SubjectAlternativeName { + self.names.push(format!("IP:{}", ip)); + self + } + + pub fn dir_name(&mut self, dir_name: &str) -> &mut SubjectAlternativeName { + self.names.push(format!("dirName:{}", dir_name)); + self + } + + pub fn other_name(&mut self, other_name: &str) -> &mut SubjectAlternativeName { + self.names.push(format!("otherName:{}", other_name)); + self + } + + pub fn build(&self, ctx: &X509v3Context) -> Result { + let mut value = String::new(); + let mut first = true; + append(&mut value, &mut first, self.critical, "critical"); + for name in &self.names { + append(&mut value, &mut first, true, name); + } + X509Extension::new_nid(None, Some(ctx), nid::SUBJECT_ALT_NAME, &value) + } +} + fn append(value: &mut String, first: &mut bool, should: bool, element: &str) { if !should { return; diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index a1ab6de555..510bb4371f 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -7,7 +7,7 @@ use pkey::PKey; use rsa::Rsa; use x509::{X509, X509Generator, X509Name}; use x509::extension::{Extension, BasicConstraints, KeyUsage, ExtendedKeyUsage, - SubjectKeyIdentifier, AuthorityKeyIdentifier}; + SubjectKeyIdentifier, AuthorityKeyIdentifier, SubjectAlternativeName}; use x509::extension::AltNameOption as SAN; use x509::extension::KeyUsageOption::{DigitalSignature, KeyEncipherment}; use x509::extension::ExtKeyUsageOption::{self, ClientAuth, ServerAuth}; @@ -217,6 +217,11 @@ fn x509_builder() { .build(&builder.x509v3_context(None, None)) .unwrap(); builder.append_extension(authority_key_identifier).unwrap(); + let subject_alternative_name = SubjectAlternativeName::new() + .dns("example.com") + .build(&builder.x509v3_context(None, None)) + .unwrap(); + builder.append_extension(subject_alternative_name).unwrap(); builder.sign(&pkey, MessageDigest::sha256()).unwrap(); From 597d05b8f8ceb754cbfe5c3b6789be6786fb0149 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 6 Nov 2016 23:46:42 -0800 Subject: [PATCH 06/15] Add stack creation and push --- openssl-sys/src/ossl10x.rs | 2 ++ openssl-sys/src/ossl110.rs | 2 ++ openssl/src/lib.rs | 4 ++++ openssl/src/ssl/mod.rs | 4 ++++ openssl/src/stack.rs | 29 ++++++++++++++++++++++++----- openssl/src/types.rs | 3 +++ 6 files changed, 39 insertions(+), 5 deletions(-) diff --git a/openssl-sys/src/ossl10x.rs b/openssl-sys/src/ossl10x.rs index acaf85ec1b..f552be01a5 100644 --- a/openssl-sys/src/ossl10x.rs +++ b/openssl-sys/src/ossl10x.rs @@ -602,10 +602,12 @@ extern { pub fn EVP_MD_CTX_create() -> *mut EVP_MD_CTX; pub fn EVP_MD_CTX_destroy(ctx: *mut EVP_MD_CTX); + pub fn sk_new_null() -> *mut _STACK; pub fn sk_num(st: *const _STACK) -> c_int; pub fn sk_value(st: *const _STACK, n: c_int) -> *mut c_void; pub fn sk_free(st: *mut _STACK); pub fn sk_pop_free(st: *mut _STACK, free: Option); + pub fn sk_push(st: *mut _STACK, data: *mut c_void) -> c_int; pub fn sk_pop(st: *mut _STACK) -> *mut c_void; pub fn SSLeay() -> c_ulong; diff --git a/openssl-sys/src/ossl110.rs b/openssl-sys/src/ossl110.rs index 1d68b6011a..eca4c84e54 100644 --- a/openssl-sys/src/ossl110.rs +++ b/openssl-sys/src/ossl110.rs @@ -151,7 +151,9 @@ extern { pub fn OpenSSL_version_num() -> c_ulong; pub fn OpenSSL_version(key: c_int) -> *const c_char; + pub fn OPENSSL_sk_new_null() -> *mut ::OPENSSL_STACK; pub fn OPENSSL_sk_free(st: *mut ::OPENSSL_STACK); pub fn OPENSSL_sk_pop_free(st: *mut ::OPENSSL_STACK, free: Option); + pub fn OPENSSL_sk_push(st: *mut ::OPENSSL_STACK, data: *const c_void) -> c_int; pub fn OPENSSL_sk_pop(st: *mut ::OPENSSL_STACK) -> *mut c_void; } diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index ec8d93ebcf..5750b41042 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -31,6 +31,10 @@ macro_rules! type_ { unsafe fn from_ptr(ptr: *mut $c) -> $n { $n(ptr) } + + fn as_ptr(&self) -> *mut $c { + self.0 + } } impl Drop for $n { diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 1e7efc63e1..7060433f54 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -822,6 +822,10 @@ impl OpenSslType for SslCipher { unsafe fn from_ptr(ptr: *mut ffi::SSL_CIPHER) -> SslCipher { SslCipher(ptr) } + + fn as_ptr(&self) -> *mut ffi::SSL_CIPHER { + self.0 + } } impl Deref for SslCipher { diff --git a/openssl/src/stack.rs b/openssl/src/stack.rs index dae42ca862..87aa86c50d 100644 --- a/openssl/src/stack.rs +++ b/openssl/src/stack.rs @@ -6,14 +6,18 @@ use std::marker::PhantomData; use libc::c_int; use std::mem; +use {cvt, cvt_p}; +use error::ErrorStack; use types::{OpenSslType, OpenSslTypeRef}; use util::Opaque; #[cfg(ossl10x)] use ffi::{sk_pop as OPENSSL_sk_pop, sk_free as OPENSSL_sk_free, sk_num as OPENSSL_sk_num, - sk_value as OPENSSL_sk_value, _STACK as OPENSSL_STACK}; + sk_value as OPENSSL_sk_value, _STACK as OPENSSL_STACK, + sk_new_null as OPENSSL_sk_new_null, sk_push as OPENSSL_sk_push}; #[cfg(ossl110)] -use ffi::{OPENSSL_sk_pop, OPENSSL_sk_free, OPENSSL_sk_num, OPENSSL_sk_value, OPENSSL_STACK}; +use ffi::{OPENSSL_sk_pop, OPENSSL_sk_free, OPENSSL_sk_num, OPENSSL_sk_value, OPENSSL_STACK, + OPENSSL_sk_new_null, OPENSSL_sk_push}; /// Trait implemented by types which can be placed in a stack. /// @@ -31,9 +35,11 @@ pub trait Stackable: OpenSslType { pub struct Stack(*mut T::StackType); impl Stack { - /// Return a new Stack, taking ownership of the handle - pub unsafe fn from_ptr(stack: *mut T::StackType) -> Stack { - Stack(stack) + pub fn new() -> Result, ErrorStack> { + unsafe { + let ptr = try!(cvt_p(OPENSSL_sk_new_null())); + Ok(Stack(ptr as *mut _)) + } } } @@ -79,6 +85,10 @@ impl OpenSslType for Stack { unsafe fn from_ptr(ptr: *mut T::StackType) -> Stack { Stack(ptr) } + + fn as_ptr(&self) -> *mut T::StackType { + self.0 + } } impl Deref for Stack { @@ -198,6 +208,15 @@ impl StackRef { } } + /// Pushes a value onto the top of the stack. + pub fn push(&mut self, data: T) -> Result<(), ErrorStack> { + unsafe { + try!(cvt(OPENSSL_sk_push(self.as_stack(), data.as_ptr() as *mut _))); + mem::forget(data); + Ok(()) + } + } + /// Removes the last element from the stack and returns it. pub fn pop(&mut self) -> Option { unsafe { diff --git a/openssl/src/types.rs b/openssl/src/types.rs index 2fadfd42c8..a444529d38 100644 --- a/openssl/src/types.rs +++ b/openssl/src/types.rs @@ -13,6 +13,9 @@ pub trait OpenSslType: Sized { /// Constructs an instance of this type from its raw type. unsafe fn from_ptr(ptr: *mut Self::CType) -> Self; + + /// Returns a raw pointer to the wrapped value. + fn as_ptr(&self) -> *mut Self::CType; } /// A trait implemented by types which reference borrowed OpenSSL types. From d78acc729bbe0960ddbeabb40530427175512a29 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 7 Nov 2016 20:42:43 +0000 Subject: [PATCH 07/15] Add an X509ReqBuilder --- openssl-sys/src/lib.rs | 4 ++ openssl/src/x509/mod.rs | 94 +++++++++++++++++++++++++++++++++------ openssl/src/x509/tests.rs | 30 ++++++++++++- 3 files changed, 114 insertions(+), 14 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index ac339a4b54..5852e7d075 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1685,6 +1685,10 @@ extern { pub fn X509V3_set_ctx(ctx: *mut X509V3_CTX, issuer: *mut X509, subject: *mut X509, req: *mut X509_REQ, crl: *mut X509_CRL, flags: c_int); pub fn X509V3_set_nconf(ctx: *mut X509V3_CTX, conf: *mut CONF); + pub fn X509_REQ_new() -> *mut X509_REQ; + pub fn X509_REQ_set_version(req: *mut X509_REQ, version: c_long) -> c_int; + pub fn X509_REQ_set_subject_name(req: *mut X509_REQ, name: *mut X509_NAME) -> c_int; + pub fn X509_REQ_set_pubkey(req: *mut X509_REQ, pkey: *mut EVP_PKEY) -> c_int; pub fn X509_REQ_add_extensions(req: *mut X509_REQ, exts: *mut stack_st_X509_EXTENSION) -> c_int; pub fn X509_REQ_sign(x: *mut X509_REQ, pkey: *mut EVP_PKEY, md: *const EVP_MD) -> c_int; diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 57d94ae1b5..97d9fa3fa4 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -597,6 +597,10 @@ impl<'a> X509v3Context<'a> { type_!(X509Extension, X509ExtensionRef, ffi::X509_EXTENSION, ffi::X509_EXTENSION_free); +impl Stackable for X509Extension { + type StackType = ffi::stack_st_X509_EXTENSION; +} + impl X509Extension { pub fn new(conf: Option<&ConfRef>, context: Option<&X509v3Context>, @@ -743,29 +747,73 @@ impl X509NameEntryRef { } } -type_!(X509Req, X509ReqRef, ffi::X509_REQ, ffi::X509_REQ_free); +pub struct X509ReqBuilder(X509Req); -impl X509ReqRef { - /// Writes CSR as PEM - pub fn to_pem(&self) -> Result, ErrorStack> { - let mem_bio = try!(MemBio::new()); - if unsafe { ffi::PEM_write_bio_X509_REQ(mem_bio.as_ptr(), self.as_ptr()) } != 1 { - return Err(ErrorStack::get()); +impl X509ReqBuilder { + pub fn new() -> Result { + unsafe { cvt_p(ffi::X509_REQ_new()).map(|p| X509ReqBuilder(X509Req(p))) } + } + + pub fn set_version(&mut self, version: i32) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::X509_REQ_set_version(self.0.as_ptr(), version.into())).map(|_| ()) } + } + + pub fn set_subject_name(&mut self, subject_name: &X509NameRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::X509_REQ_set_subject_name(self.0.as_ptr(), subject_name.as_ptr())).map(|_| ()) } - Ok(mem_bio.get_buf().to_owned()) } - /// Returns a DER serialized form of the CSR - pub fn to_der(&self) -> Result, ErrorStack> { - let mem_bio = try!(MemBio::new()); + pub fn set_pubkey(&mut self, key: &PKeyRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::X509_REQ_set_pubkey(self.0.as_ptr(), key.as_ptr())).map(|_| ()) } + } + + pub fn x509v3_context<'a>(&'a self, + conf: Option<&'a ConfRef>) + -> X509v3Context<'a> { unsafe { - ffi::i2d_X509_REQ_bio(mem_bio.as_ptr(), self.as_ptr()); + let mut ctx = mem::zeroed(); + + ffi::X509V3_set_ctx(&mut ctx, + ptr::null_mut(), + ptr::null_mut(), + self.0.as_ptr(), + ptr::null_mut(), + 0); + + // nodb case taken care of since we zeroed ctx above + if let Some(conf) = conf { + ffi::X509V3_set_nconf(&mut ctx, conf.as_ptr()); + } + + X509v3Context(ctx, PhantomData) } - Ok(mem_bio.get_buf().to_owned()) + } + + pub fn add_extensions(&mut self, + extensions: &StackRef) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::X509_REQ_add_extensions(self.0.as_ptr(), extensions.as_ptr())).map(|_| ()) + } + } + + pub fn sign(&mut self, key: &PKeyRef, hash: MessageDigest) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::X509_REQ_sign(self.0.as_ptr(), key.as_ptr(), hash.as_ptr())).map(|_| ()) } + } + + pub fn build(self) -> X509Req { + self.0 } } +type_!(X509Req, X509ReqRef, ffi::X509_REQ, ffi::X509_REQ_free); + impl X509Req { + pub fn builder() -> Result { + X509ReqBuilder::new() + } + /// Reads CSR from PEM pub fn from_pem(buf: &[u8]) -> Result { let mem_bio = try!(MemBioSlice::new(buf)); @@ -779,6 +827,26 @@ impl X509Req { } } +impl X509ReqRef { + /// Writes CSR as PEM + pub fn to_pem(&self) -> Result, ErrorStack> { + let mem_bio = try!(MemBio::new()); + if unsafe { ffi::PEM_write_bio_X509_REQ(mem_bio.as_ptr(), self.as_ptr()) } != 1 { + return Err(ErrorStack::get()); + } + Ok(mem_bio.get_buf().to_owned()) + } + + /// Returns a DER serialized form of the CSR + pub fn to_der(&self) -> Result, ErrorStack> { + let mem_bio = try!(MemBio::new()); + unsafe { + ffi::i2d_X509_REQ_bio(mem_bio.as_ptr(), self.as_ptr()); + } + Ok(mem_bio.get_buf().to_owned()) + } +} + /// A collection of X.509 extensions. /// /// Upholds the invariant that a certificate MUST NOT include more than one diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index 510bb4371f..514b8edcca 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -5,7 +5,8 @@ use bn::{BigNum, MSB_MAYBE_ZERO}; use hash::MessageDigest; use pkey::PKey; use rsa::Rsa; -use x509::{X509, X509Generator, X509Name}; +use stack::Stack; +use x509::{X509, X509Generator, X509Name, X509Req}; use x509::extension::{Extension, BasicConstraints, KeyUsage, ExtendedKeyUsage, SubjectKeyIdentifier, AuthorityKeyIdentifier, SubjectAlternativeName}; use x509::extension::AltNameOption as SAN; @@ -187,6 +188,7 @@ fn x509_builder() { let name = name.build(); let mut builder = X509::builder().unwrap(); + builder.set_version(2).unwrap(); builder.set_subject_name(&name).unwrap(); builder.set_issuer_name(&name).unwrap(); builder.set_not_before(&Asn1Time::days_from_now(0).unwrap()).unwrap(); @@ -232,3 +234,29 @@ fn x509_builder() { let cn = x509.subject_name().entries_by_nid(nid::COMMONNAME).next().unwrap(); assert_eq!("foobar.com".as_bytes(), cn.data().as_slice()); } + +#[test] +fn x509_req_builder() { + let pkey = pkey(); + + let mut name = X509Name::builder().unwrap(); + name.append_entry_by_nid(nid::COMMONNAME, "foobar.com").unwrap(); + let name = name.build(); + + let mut builder = X509Req::builder().unwrap(); + builder.set_version(2).unwrap(); + builder.set_subject_name(&name).unwrap(); + builder.set_pubkey(&pkey).unwrap(); + + let mut extensions = Stack::new().unwrap(); + let key_usage = KeyUsage::new().digital_signature().key_encipherment().build().unwrap(); + extensions.push(key_usage).unwrap(); + let subject_alternative_name = SubjectAlternativeName::new() + .dns("example.com") + .build(&builder.x509v3_context(None)) + .unwrap(); + extensions.push(subject_alternative_name).unwrap(); + builder.add_extensions(&extensions).unwrap(); + + builder.sign(&pkey, MessageDigest::sha256()).unwrap(); +} From 18c5d1f771172aa1c532553d49de48242d4434ec Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 7 Nov 2016 20:50:57 +0000 Subject: [PATCH 08/15] Add init calls to new constructors --- openssl/src/conf.rs | 5 ++++- openssl/src/stack.rs | 2 ++ openssl/src/x509/mod.rs | 14 ++++++++++++-- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/openssl/src/conf.rs b/openssl/src/conf.rs index 140c181721..5483955de8 100644 --- a/openssl/src/conf.rs +++ b/openssl/src/conf.rs @@ -7,7 +7,10 @@ pub struct ConfMethod(*mut ffi::CONF_METHOD); impl ConfMethod { pub fn default() -> ConfMethod { - unsafe { ConfMethod(ffi::NCONF_default()) } + unsafe { + ffi::init(); + ConfMethod(ffi::NCONF_default()) + } } pub unsafe fn from_ptr(ptr: *mut ffi::CONF_METHOD) -> ConfMethod { diff --git a/openssl/src/stack.rs b/openssl/src/stack.rs index 87aa86c50d..584ead8c53 100644 --- a/openssl/src/stack.rs +++ b/openssl/src/stack.rs @@ -5,6 +5,7 @@ use std::convert::AsRef; use std::marker::PhantomData; use libc::c_int; use std::mem; +use ffi; use {cvt, cvt_p}; use error::ErrorStack; @@ -37,6 +38,7 @@ pub struct Stack(*mut T::StackType); impl Stack { pub fn new() -> Result, ErrorStack> { unsafe { + ffi::init(); let ptr = try!(cvt_p(OPENSSL_sk_new_null())); Ok(Stack(ptr as *mut _)) } diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 97d9fa3fa4..af79ffbb2d 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -360,6 +360,7 @@ pub struct X509Builder(X509); impl X509Builder { pub fn new() -> Result { unsafe { + ffi::init(); cvt_p(ffi::X509_new()).map(|p| X509Builder(X509(p))) } } @@ -610,6 +611,7 @@ impl X509Extension { let name = CString::new(name).unwrap(); let value = CString::new(value).unwrap(); unsafe { + ffi::init(); let conf = conf.map_or(ptr::null_mut(), ConfRef::as_ptr); let context = context.map_or(ptr::null_mut(), X509v3Context::as_ptr); let name = name.as_ptr() as *mut _; @@ -626,6 +628,7 @@ impl X509Extension { -> Result { let value = CString::new(value).unwrap(); unsafe { + ffi::init(); let conf = conf.map_or(ptr::null_mut(), ConfRef::as_ptr); let context = context.map_or(ptr::null_mut(), X509v3Context::as_ptr); let name = name.as_raw(); @@ -640,7 +643,10 @@ pub struct X509NameBuilder(X509Name); impl X509NameBuilder { pub fn new() -> Result { - unsafe { cvt_p(ffi::X509_NAME_new()).map(|p| X509NameBuilder(X509Name(p))) } + unsafe { + ffi::init(); + cvt_p(ffi::X509_NAME_new()).map(|p| X509NameBuilder(X509Name(p))) + } } pub fn append_entry_by_text(&mut self, field: &str, value: &str) -> Result<(), ErrorStack> { @@ -751,7 +757,11 @@ pub struct X509ReqBuilder(X509Req); impl X509ReqBuilder { pub fn new() -> Result { - unsafe { cvt_p(ffi::X509_REQ_new()).map(|p| X509ReqBuilder(X509Req(p))) } + unsafe { + ffi::init(); + cvt_p(ffi::X509_REQ_new()).map(|p| X509ReqBuilder(X509Req(p))) + } + } pub fn set_version(&mut self, version: i32) -> Result<(), ErrorStack> { From c0e02e7e5147b4218fff5ea1edc48dcd35aaabad Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 7 Nov 2016 21:15:36 +0000 Subject: [PATCH 09/15] Use X509Builder in X509Generator --- openssl/src/x509/mod.rs | 161 +++++++++++----------------------------- 1 file changed, 42 insertions(+), 119 deletions(-) diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index af79ffbb2d..402e17d4a1 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -1,4 +1,4 @@ -use libc::{c_char, c_int, c_long, c_ulong}; +use libc::{c_int, c_long}; use std::borrow::Borrow; use std::cmp; use std::collections::HashMap; @@ -14,14 +14,14 @@ use std::str; use {cvt, cvt_p}; use asn1::{Asn1StringRef, Asn1Time, Asn1TimeRef, Asn1IntegerRef}; +use bn::{BigNum, MSB_MAYBE_ZERO}; use bio::{MemBio, MemBioSlice}; use conf::ConfRef; use hash::MessageDigest; use pkey::{PKey, PKeyRef}; -use rand::rand_bytes; use error::ErrorStack; use ffi; -use nid::Nid; +use nid::{self, Nid}; use types::{OpenSslType, OpenSslTypeRef}; use stack::{Stack, StackRef, Stackable}; @@ -210,123 +210,55 @@ impl X509Generator { self } - fn add_extension_internal(x509: *mut ffi::X509, - exttype: &extension::ExtensionType, - value: &str) - -> Result<(), ErrorStack> { - unsafe { - let mut ctx: ffi::X509V3_CTX = mem::zeroed(); - ffi::X509V3_set_ctx(&mut ctx, x509, x509, ptr::null_mut(), ptr::null_mut(), 0); - let value = CString::new(value.as_bytes()).unwrap(); - let ext = match exttype.get_nid() { - Some(nid) => { - try!(cvt_p(ffi::X509V3_EXT_nconf_nid(ptr::null_mut(), - &mut ctx, - nid.as_raw(), - value.as_ptr() as *mut c_char))) - } - None => { - let name = CString::new(exttype.get_name().unwrap().as_bytes()).unwrap(); - try!(cvt_p(ffi::X509V3_EXT_nconf(ptr::null_mut(), - &mut ctx, - name.as_ptr() as *mut c_char, - value.as_ptr() as *mut c_char))) - } - }; - if ffi::X509_add_ext(x509, ext, -1) != 1 { - ffi::X509_EXTENSION_free(ext); - Err(ErrorStack::get()) - } else { - Ok(()) - } - } - } - - fn add_name_internal(name: *mut ffi::X509_NAME, - key: &str, - value: &str) - -> Result<(), ErrorStack> { - let value_len = value.len() as c_int; - unsafe { - let key = CString::new(key.as_bytes()).unwrap(); - let value = CString::new(value.as_bytes()).unwrap(); - cvt(ffi::X509_NAME_add_entry_by_txt(name, - key.as_ptr() as *const _, - ffi::MBSTRING_UTF8, - value.as_ptr() as *const _, - value_len, - -1, - 0)) - .map(|_| ()) - } - } - - fn random_serial() -> Result { - let len = mem::size_of::(); - let mut bytes = vec![0; len]; - try!(rand_bytes(&mut bytes)); - let mut res = 0; - for b in bytes.iter() { - res = res << 8; - res |= (*b as c_long) & 0xff; - } - - // While OpenSSL is actually OK to have negative serials - // other libraries (for example, Go crypto) can drop - // such certificates as invalid, so we clear the high bit - Ok(((res as c_ulong) >> 1) as c_long) - } - /// Sets the certificate public-key, then self-sign and return it pub fn sign(&self, p_key: &PKeyRef) -> Result { - ffi::init(); - - unsafe { - let x509 = X509::from_ptr(try!(cvt_p(ffi::X509_new()))); - - try!(cvt(ffi::X509_set_version(x509.as_ptr(), 2))); - try!(cvt(ffi::ASN1_INTEGER_set(ffi::X509_get_serialNumber(x509.as_ptr()), - try!(X509Generator::random_serial())))); - - let not_before = try!(Asn1Time::days_from_now(0)); - let not_after = try!(Asn1Time::days_from_now(self.days)); - - try!(cvt(X509_set_notBefore(x509.as_ptr(), not_before.as_ptr() as *const _))); - // If prev line succeded - ownership should go to cert - mem::forget(not_before); + let mut builder = try!(X509::builder()); + try!(builder.set_version(2)); - try!(cvt(X509_set_notAfter(x509.as_ptr(), not_after.as_ptr() as *const _))); - // If prev line succeded - ownership should go to cert - mem::forget(not_after); + let mut serial = try!(BigNum::new()); + try!(serial.rand(128, MSB_MAYBE_ZERO, false)); + let serial = try!(serial.to_asn1_integer()); + try!(builder.set_serial_number(&serial)); - try!(cvt(ffi::X509_set_pubkey(x509.as_ptr(), p_key.as_ptr()))); + let not_before = try!(Asn1Time::days_from_now(0)); + try!(builder.set_not_before(¬_before)); + let not_after = try!(Asn1Time::days_from_now(self.days)); + try!(builder.set_not_after(¬_after)); - let name = try!(cvt_p(ffi::X509_get_subject_name(x509.as_ptr()))); + try!(builder.set_pubkey(p_key)); - let default = [("CN", "rust-openssl")]; - let default_iter = &mut default.iter().map(|&(k, v)| (k, v)); - let arg_iter = &mut self.names.iter().map(|&(ref k, ref v)| (&k[..], &v[..])); - let iter: &mut Iterator = if self.names.len() == 0 { - default_iter - } else { - arg_iter - }; - - for (key, val) in iter { - try!(X509Generator::add_name_internal(name, &key, &val)); + let mut name = try!(X509Name::builder()); + if self.names.is_empty() { + try!(name.append_entry_by_nid(nid::COMMONNAME, "rust-openssl")); + } else { + for &(ref key, ref value) in &self.names { + try!(name.append_entry_by_text(key, value)); } - try!(cvt(ffi::X509_set_issuer_name(x509.as_ptr(), name))); + } + let name = name.build(); - for (exttype, ext) in self.extensions.iter() { - try!(X509Generator::add_extension_internal(x509.as_ptr(), - &exttype, - &ext.to_string())); - } + try!(builder.set_subject_name(&name)); + try!(builder.set_issuer_name(&name)); - let hash_fn = self.hash_type.as_ptr(); - try!(cvt(ffi::X509_sign(x509.as_ptr(), p_key.as_ptr(), hash_fn))); - Ok(x509) + for (exttype, ext) in self.extensions.iter() { + let extension = match exttype.get_nid() { + Some(nid) => { + let ctx = builder.x509v3_context(None, None); + try!(X509Extension::new_nid(None, Some(&ctx), nid, &ext.to_string())) + } + None => { + let ctx = builder.x509v3_context(None, None); + try!(X509Extension::new(None, + Some(&ctx), + &exttype.get_name().unwrap(), + &ext.to_string())) + } + }; + try!(builder.append_extension(extension)); } + + try!(builder.sign(p_key, self.hash_type)); + Ok(builder.build()) } /// Obtain a certificate signing request (CSR) @@ -1020,15 +952,6 @@ impl Stackable for GeneralName { type StackType = ffi::stack_st_GENERAL_NAME; } -#[test] -fn test_negative_serial() { - // I guess that's enough to get a random negative number - for _ in 0..1000 { - assert!(X509Generator::random_serial().unwrap() > 0, - "All serials should be positive"); - } -} - #[cfg(ossl110)] mod compat { pub use ffi::X509_getm_notAfter as X509_get_notAfter; From 97872500a3c4c5e7ce060931a8a26f6834822e9c Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 7 Nov 2016 21:36:09 +0000 Subject: [PATCH 10/15] Deprecate X509Generator --- openssl/src/x509/extension.rs | 8 ++++++++ openssl/src/x509/mod.rs | 37 ++++++++++++----------------------- 2 files changed, 20 insertions(+), 25 deletions(-) diff --git a/openssl/src/x509/extension.rs b/openssl/src/x509/extension.rs index 7a09ddbc69..48a1bc54ef 100644 --- a/openssl/src/x509/extension.rs +++ b/openssl/src/x509/extension.rs @@ -9,6 +9,7 @@ use x509::{X509v3Context, X509Extension}; /// See the `Extension` documentation for more information on the different /// variants. #[derive(Clone,Hash,PartialEq,Eq)] +#[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] pub enum ExtensionType { KeyUsage, ExtKeyUsage, @@ -23,6 +24,7 @@ pub enum ExtensionType { /// Only one extension of each type is allow in a certificate. /// See RFC 3280 for more information about extensions. #[derive(Clone)] +#[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] pub enum Extension { /// The purposes of the key contained in the certificate KeyUsage(Vec), @@ -58,6 +60,7 @@ pub enum Extension { } impl Extension { + #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] pub fn get_type(&self) -> ExtensionType { match self { &Extension::KeyUsage(_) => ExtensionType::KeyUsage, @@ -71,6 +74,7 @@ impl Extension { } impl ExtensionType { + #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] pub fn get_nid(&self) -> Option { match self { &ExtensionType::KeyUsage => Some(nid::KEY_USAGE), @@ -82,6 +86,7 @@ impl ExtensionType { } } + #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] pub fn get_name(&self) -> Option<&str> { match self { &ExtensionType::OtherStr(ref s) => Some(s), @@ -122,6 +127,7 @@ impl ToString for Extension { } #[derive(Clone,Copy)] +#[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] pub enum KeyUsageOption { DigitalSignature, NonRepudiation, @@ -151,6 +157,7 @@ impl fmt::Display for KeyUsageOption { } #[derive(Clone)] +#[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] pub enum ExtKeyUsageOption { ServerAuth, ClientAuth, @@ -187,6 +194,7 @@ impl fmt::Display for ExtKeyUsageOption { } #[derive(Clone, Copy)] +#[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] pub enum AltNameOption { /// The value is specified as OID;content. See `man ASN1_generate_nconf` for more information on the content syntax. /// diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 402e17d4a1..8ee82b9873 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -1,3 +1,4 @@ +#![allow(deprecated)] use libc::{c_int, c_long}; use std::borrow::Borrow; use std::cmp; @@ -89,31 +90,7 @@ impl X509StoreContextRef { } } -#[allow(non_snake_case)] -/// Generator of private key/certificate pairs -/// -/// # Example -/// -/// ``` -/// use openssl::hash::MessageDigest; -/// use openssl::pkey::PKey; -/// use openssl::rsa::Rsa; -/// use openssl::x509::X509Generator; -/// use openssl::x509::extension::{Extension, KeyUsageOption}; -/// -/// let rsa = Rsa::generate(2048).unwrap(); -/// let pkey = PKey::from_rsa(rsa).unwrap(); -/// -/// let gen = X509Generator::new() -/// .set_valid_period(365*2) -/// .add_name("CN".to_owned(), "SuperMegaCorp Inc.".to_owned()) -/// .set_sign_hash(MessageDigest::sha256()) -/// .add_extension(Extension::KeyUsage(vec![KeyUsageOption::DigitalSignature])); -/// -/// let cert = gen.sign(&pkey).unwrap(); -/// let cert_pem = cert.to_pem().unwrap(); -/// let pkey_pem = pkey.private_key_to_pem().unwrap(); -/// ``` +#[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] pub struct X509Generator { days: u32, names: Vec<(String, String)>, @@ -121,6 +98,7 @@ pub struct X509Generator { hash_type: MessageDigest, } +#[allow(deprecated)] impl X509Generator { /// Creates a new generator with the following defaults: /// @@ -129,6 +107,7 @@ impl X509Generator { /// CN: "rust-openssl" /// /// hash: SHA1 + #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] pub fn new() -> X509Generator { X509Generator { days: 365, @@ -139,6 +118,7 @@ impl X509Generator { } /// Sets certificate validity period in days since today + #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] pub fn set_valid_period(mut self, days: u32) -> X509Generator { self.days = days; self @@ -150,6 +130,7 @@ impl X509Generator { /// # let generator = openssl::x509::X509Generator::new(); /// generator.add_name("CN".to_string(),"example.com".to_string()); /// ``` + #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] pub fn add_name(mut self, attr_type: String, attr_value: String) -> X509Generator { self.names.push((attr_type, attr_value)); self @@ -161,6 +142,7 @@ impl X509Generator { /// # let generator = openssl::x509::X509Generator::new(); /// generator.add_names(vec![("CN".to_string(),"example.com".to_string())]); /// ``` + #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] pub fn add_names(mut self, attrs: I) -> X509Generator where I: IntoIterator { @@ -179,6 +161,7 @@ impl X509Generator { /// # let generator = openssl::x509::X509Generator::new(); /// generator.add_extension(KeyUsage(vec![DigitalSignature, KeyEncipherment])); /// ``` + #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] pub fn add_extension(mut self, ext: extension::Extension) -> X509Generator { self.extensions.add(ext); self @@ -195,6 +178,7 @@ impl X509Generator { /// # let generator = openssl::x509::X509Generator::new(); /// generator.add_extensions(vec![KeyUsage(vec![DigitalSignature, KeyEncipherment])]); /// ``` + #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] pub fn add_extensions(mut self, exts: I) -> X509Generator where I: IntoIterator { @@ -205,12 +189,14 @@ impl X509Generator { self } + #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] pub fn set_sign_hash(mut self, hash_type: MessageDigest) -> X509Generator { self.hash_type = hash_type; self } /// Sets the certificate public-key, then self-sign and return it + #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] pub fn sign(&self, p_key: &PKeyRef) -> Result { let mut builder = try!(X509::builder()); try!(builder.set_version(2)); @@ -262,6 +248,7 @@ impl X509Generator { } /// Obtain a certificate signing request (CSR) + #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] pub fn request(&self, p_key: &PKeyRef) -> Result { let cert = match self.sign(p_key) { Ok(c) => c, From b3b7194e823e3d9425528f32f7f89d4c05883e0f Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 8 Nov 2016 19:10:56 +0000 Subject: [PATCH 11/15] Docs --- openssl/src/x509/mod.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 8ee82b9873..e3a54d7d7d 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -274,9 +274,11 @@ impl X509Generator { } } +/// A builder type which can create `X509` objects. pub struct X509Builder(X509); impl X509Builder { + /// Creates a new builder. pub fn new() -> Result { unsafe { ffi::init(); @@ -284,18 +286,25 @@ impl X509Builder { } } + /// Sets the notAfter constraint on the certificate. pub fn set_not_after(&mut self, not_after: &Asn1TimeRef) -> Result<(), ErrorStack> { unsafe { cvt(X509_set_notAfter(self.0.as_ptr(), not_after.as_ptr())).map(|_| ()) } } + /// Sets the notBefore constraint on the certificate. pub fn set_not_before(&mut self, not_before: &Asn1TimeRef) -> Result<(), ErrorStack> { unsafe { cvt(X509_set_notBefore(self.0.as_ptr(), not_before.as_ptr())).map(|_| ()) } } + /// Sets the version of the certificate. + /// + /// Note that the version is zero-indexed; that is, a certificate corresponding to version 3 of + /// the X.509 standard should pass `2` to this method. pub fn set_version(&mut self, version: i32) -> Result<(), ErrorStack> { unsafe { cvt(ffi::X509_set_version(self.0.as_ptr(), version.into())).map(|_| ()) } } + /// Sets the serial number of the certificate. pub fn set_serial_number(&mut self, serial_number: &Asn1IntegerRef) -> Result<(), ErrorStack> { @@ -304,20 +313,26 @@ impl X509Builder { } } + /// Sets the issuer name of the certificate. pub fn set_issuer_name(&mut self, issuer_name: &X509NameRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::X509_set_issuer_name(self.0.as_ptr(), issuer_name.as_ptr())).map(|_| ()) } } + /// Sets the subject name of the certificate. pub fn set_subject_name(&mut self, subject_name: &X509NameRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::X509_set_subject_name(self.0.as_ptr(), subject_name.as_ptr())).map(|_| ()) } } + /// Sets the public key associated with the certificate. pub fn set_pubkey(&mut self, key: &PKeyRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::X509_set_pubkey(self.0.as_ptr(), key.as_ptr())).map(|_| ()) } } + /// Returns a context object which is needed to create certain X509 extension values. + /// + /// Set `issuer` to `None` if the certificate will be self-signed. pub fn x509v3_context<'a>(&'a self, issuer: Option<&'a X509Ref>, conf: Option<&'a ConfRef>) @@ -341,6 +356,7 @@ impl X509Builder { } } + /// Adds an X509 extension value to the certificate. pub fn append_extension(&mut self, extension: X509Extension) -> Result<(), ErrorStack> { unsafe { try!(cvt(ffi::X509_add_ext(self.0.as_ptr(), extension.as_ptr(), -1))); @@ -349,10 +365,12 @@ impl X509Builder { } } + /// Signs the certificate with a private key. pub fn sign(&mut self, key: &PKeyRef, hash: MessageDigest) -> Result<(), ErrorStack> { unsafe { cvt(ffi::X509_sign(self.0.as_ptr(), key.as_ptr(), hash.as_ptr())).map(|_| ()) } } + /// Consumes the builder, returning the certificate. pub fn build(self) -> X509 { self.0 } @@ -507,6 +525,7 @@ impl Stackable for X509 { type StackType = ffi::stack_st_X509; } +/// A context object required to construct certain X509 extension values. pub struct X509v3Context<'a>(ffi::X509V3_CTX, PhantomData<(&'a X509Ref, &'a ConfRef)>); impl<'a> X509v3Context<'a> { @@ -522,6 +541,13 @@ impl Stackable for X509Extension { } impl X509Extension { + /// Constructs an X509 extension value. See `man x509v3_config` for information on supported + /// names and their value formats. + /// + /// Some extension types, such as `subjectAlternativeName`, require an `X509v3Context` to be + /// provided. + /// + /// See the extension module for builder types which will construct certain common extensions. pub fn new(conf: Option<&ConfRef>, context: Option<&X509v3Context>, name: &str, @@ -540,6 +566,13 @@ impl X509Extension { } } + /// Constructs an X509 extension value. See `man x509v3_config` for information on supported + /// extensions and their value formats. + /// + /// Some extension types, such as `nid::SUBJECT_ALTERNATIVE_NAME`, require an `X509v3Context` to + /// be provided. + /// + /// See the extension module for builder types which will construct certain common extensions. pub fn new_nid(conf: Option<&ConfRef>, context: Option<&X509v3Context>, name: Nid, From 16d5632983ea40a35b722e8aeb08d6a3e6b0b721 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 11 Feb 2017 10:14:16 -0800 Subject: [PATCH 12/15] Remove X509Req setters --- openssl/src/x509/mod.rs | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 6b65fbd2ac..d225e565a6 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -874,13 +874,6 @@ impl X509ReqRef { } } - pub fn set_version(&mut self, value: i32) -> Result<(), ErrorStack> - { - unsafe { - cvt(ffi::X509_REQ_set_version(self.as_ptr(), value as c_long)).map(|_| ()) - } - } - pub fn subject_name(&self) -> &X509NameRef { unsafe { let name = compat::X509_REQ_get_subject_name(self.as_ptr()); @@ -888,12 +881,6 @@ impl X509ReqRef { X509NameRef::from_ptr(name) } } - - pub fn set_subject_name(&mut self, value: &X509NameRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::X509_REQ_set_subject_name(self.as_ptr(), value.as_ptr())).map(|_| ()) - } - } } /// A collection of X.509 extensions. From 89cd1d3ea7e19cca2ba193a667663429237a7c92 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 11 Feb 2017 10:16:14 -0800 Subject: [PATCH 13/15] Use published foreign_types --- openssl/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openssl/Cargo.toml b/openssl/Cargo.toml index 7855897f68..34d8e3dba2 100644 --- a/openssl/Cargo.toml +++ b/openssl/Cargo.toml @@ -19,7 +19,7 @@ v110 = [] [dependencies] bitflags = "0.7" -foreign-types = { git = "https://github.com/sfackler/foreign-types" } +foreign-types = "0.2" lazy_static = "0.2" libc = "0.2" openssl-sys = { version = "0.9.6", path = "../openssl-sys" } From 129a3cff08c76f0869814e6e06ff2936cf6ddffd Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 11 Feb 2017 10:23:13 -0800 Subject: [PATCH 14/15] Update deprecation version --- openssl/src/x509/extension.rs | 16 ++++++++-------- openssl/src/x509/mod.rs | 20 ++++++++++---------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/openssl/src/x509/extension.rs b/openssl/src/x509/extension.rs index 48a1bc54ef..c9f60a9221 100644 --- a/openssl/src/x509/extension.rs +++ b/openssl/src/x509/extension.rs @@ -9,7 +9,7 @@ use x509::{X509v3Context, X509Extension}; /// See the `Extension` documentation for more information on the different /// variants. #[derive(Clone,Hash,PartialEq,Eq)] -#[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] +#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] pub enum ExtensionType { KeyUsage, ExtKeyUsage, @@ -24,7 +24,7 @@ pub enum ExtensionType { /// Only one extension of each type is allow in a certificate. /// See RFC 3280 for more information about extensions. #[derive(Clone)] -#[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] +#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] pub enum Extension { /// The purposes of the key contained in the certificate KeyUsage(Vec), @@ -60,7 +60,7 @@ pub enum Extension { } impl Extension { - #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] + #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] pub fn get_type(&self) -> ExtensionType { match self { &Extension::KeyUsage(_) => ExtensionType::KeyUsage, @@ -74,7 +74,7 @@ impl Extension { } impl ExtensionType { - #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] + #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] pub fn get_nid(&self) -> Option { match self { &ExtensionType::KeyUsage => Some(nid::KEY_USAGE), @@ -86,7 +86,7 @@ impl ExtensionType { } } - #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] + #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] pub fn get_name(&self) -> Option<&str> { match self { &ExtensionType::OtherStr(ref s) => Some(s), @@ -127,7 +127,7 @@ impl ToString for Extension { } #[derive(Clone,Copy)] -#[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] +#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] pub enum KeyUsageOption { DigitalSignature, NonRepudiation, @@ -157,7 +157,7 @@ impl fmt::Display for KeyUsageOption { } #[derive(Clone)] -#[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] +#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] pub enum ExtKeyUsageOption { ServerAuth, ClientAuth, @@ -194,7 +194,7 @@ impl fmt::Display for ExtKeyUsageOption { } #[derive(Clone, Copy)] -#[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] +#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] pub enum AltNameOption { /// The value is specified as OID;content. See `man ASN1_generate_nconf` for more information on the content syntax. /// diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index d225e565a6..4df05ad06a 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -97,7 +97,7 @@ impl X509StoreContextRef { } } -#[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] +#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] pub struct X509Generator { days: u32, names: Vec<(String, String)>, @@ -114,7 +114,7 @@ impl X509Generator { /// CN: "rust-openssl" /// /// hash: SHA1 - #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] + #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] pub fn new() -> X509Generator { X509Generator { days: 365, @@ -125,7 +125,7 @@ impl X509Generator { } /// Sets certificate validity period in days since today - #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] + #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] pub fn set_valid_period(mut self, days: u32) -> X509Generator { self.days = days; self @@ -137,7 +137,7 @@ impl X509Generator { /// # let generator = openssl::x509::X509Generator::new(); /// generator.add_name("CN".to_string(),"example.com".to_string()); /// ``` - #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] + #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] pub fn add_name(mut self, attr_type: String, attr_value: String) -> X509Generator { self.names.push((attr_type, attr_value)); self @@ -149,7 +149,7 @@ impl X509Generator { /// # let generator = openssl::x509::X509Generator::new(); /// generator.add_names(vec![("CN".to_string(),"example.com".to_string())]); /// ``` - #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] + #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] pub fn add_names(mut self, attrs: I) -> X509Generator where I: IntoIterator { @@ -168,7 +168,7 @@ impl X509Generator { /// # let generator = openssl::x509::X509Generator::new(); /// generator.add_extension(KeyUsage(vec![DigitalSignature, KeyEncipherment])); /// ``` - #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] + #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] pub fn add_extension(mut self, ext: extension::Extension) -> X509Generator { self.extensions.add(ext); self @@ -185,7 +185,7 @@ impl X509Generator { /// # let generator = openssl::x509::X509Generator::new(); /// generator.add_extensions(vec![KeyUsage(vec![DigitalSignature, KeyEncipherment])]); /// ``` - #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] + #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] pub fn add_extensions(mut self, exts: I) -> X509Generator where I: IntoIterator { @@ -196,14 +196,14 @@ impl X509Generator { self } - #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] + #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] pub fn set_sign_hash(mut self, hash_type: MessageDigest) -> X509Generator { self.hash_type = hash_type; self } /// Sets the certificate public-key, then self-sign and return it - #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] + #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] pub fn sign(&self, p_key: &PKeyRef) -> Result { let mut builder = try!(X509::builder()); try!(builder.set_version(2)); @@ -255,7 +255,7 @@ impl X509Generator { } /// Obtain a certificate signing request (CSR) - #[deprecated(since = "0.9.1", note = "use X509Builder and X509ReqBuilder instead")] + #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] pub fn request(&self, p_key: &PKeyRef) -> Result { let cert = match self.sign(p_key) { Ok(c) => c, From 980a71a008450285144a0bdedcfc89249c5a49a4 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 11 Feb 2017 10:42:25 -0800 Subject: [PATCH 15/15] Fix for libressl --- openssl-sys/src/libressl.rs | 3 +++ openssl-sys/src/ossl10x.rs | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/openssl-sys/src/libressl.rs b/openssl-sys/src/libressl.rs index 197d2c226c..40490cd0f0 100644 --- a/openssl-sys/src/libressl.rs +++ b/openssl-sys/src/libressl.rs @@ -707,6 +707,7 @@ extern { pub fn X509_set_notAfter(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int; pub fn X509_set_notBefore(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int; pub fn X509_get_ext_d2i(x: *mut ::X509, nid: c_int, crit: *mut c_int, idx: *mut c_int) -> *mut c_void; + pub fn X509_NAME_add_entry_by_NID(x: *mut ::X509_NAME, field: c_int, ty: c_int, bytes: *mut c_uchar, len: c_int, loc: c_int, set: c_int) -> c_int; pub fn X509_NAME_get_entry(n: *mut ::X509_NAME, loc: c_int) -> *mut ::X509_NAME_ENTRY; pub fn X509_NAME_ENTRY_get_data(ne: *mut ::X509_NAME_ENTRY) -> *mut ::ASN1_STRING; pub fn X509_STORE_CTX_get_chain(ctx: *mut ::X509_STORE_CTX) -> *mut stack_st_X509; @@ -723,9 +724,11 @@ extern { pub fn EVP_MD_CTX_destroy(ctx: *mut EVP_MD_CTX); pub fn EVP_PKEY_bits(key: *mut EVP_PKEY) -> c_int; + pub fn sk_new_null() -> *mut _STACK; pub fn sk_num(st: *const _STACK) -> c_int; pub fn sk_value(st: *const _STACK, n: c_int) -> *mut c_void; pub fn sk_free(st: *mut _STACK); + pub fn sk_push(st: *mut _STACK, data: *mut c_void) -> c_int; pub fn sk_pop_free(st: *mut _STACK, free: Option); pub fn sk_pop(st: *mut _STACK) -> *mut c_void; diff --git a/openssl-sys/src/ossl10x.rs b/openssl-sys/src/ossl10x.rs index 128689e58d..0ffe385084 100644 --- a/openssl-sys/src/ossl10x.rs +++ b/openssl-sys/src/ossl10x.rs @@ -883,8 +883,8 @@ extern { pub fn sk_num(st: *const _STACK) -> c_int; pub fn sk_value(st: *const _STACK, n: c_int) -> *mut c_void; pub fn sk_free(st: *mut _STACK); - pub fn sk_pop_free(st: *mut _STACK, free: Option); pub fn sk_push(st: *mut _STACK, data: *mut c_void) -> c_int; + pub fn sk_pop_free(st: *mut _STACK, free: Option); pub fn sk_pop(st: *mut _STACK) -> *mut c_void; pub fn SSLeay() -> c_ulong;