From c5da7131f53f6fb659f64be4b9bf089f7e389143 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 29 Sep 2016 00:09:31 +0200 Subject: [PATCH 001/186] Make sure private component exists when signing Closes #457 --- openssl/src/crypto/rsa.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index feb66a6f..3ba063cd 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -163,6 +163,7 @@ impl RSA { } pub fn sign(&self, hash: hash::Type, message: &[u8]) -> Result, ErrorStack> { + assert!(self.d().is_some(), "private components missing"); let k_len = self.size().expect("RSA missing an n"); let mut sig = vec![0; k_len as usize]; let mut sig_len = k_len; From 4cc55b65e038f02c817a03b0848393ecdafccde1 Mon Sep 17 00:00:00 2001 From: manuels Date: Sat, 1 Oct 2016 13:39:33 +0200 Subject: [PATCH 002/186] Add RSA_*_PADDING constants --- openssl-sys/src/lib.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 380f0058..b0ae686d 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -340,6 +340,12 @@ pub const PKCS5_SALT_LEN: c_int = 8; pub const RSA_F4: c_long = 0x10001; +pub const RSA_PKCS1_PADDING: c_int = 1; +pub const RSA_SSLV23_PADDING: c_int = 2; +pub const RSA_NO_PADDING: c_int = 3; +pub const RSA_PKCS1_OAEP_PADDING: c_int = 4; +pub const RSA_X931_PADDING: c_int = 5; + pub const SSL_CTRL_SET_TMP_DH: c_int = 3; pub const SSL_CTRL_EXTRA_CHAIN_CERT: c_int = 14; pub const SSL_CTRL_OPTIONS: c_int = 32; From 44ed665f02fea1cdd4c8fda81e20480383b1d3aa Mon Sep 17 00:00:00 2001 From: manuels Date: Sat, 1 Oct 2016 13:42:13 +0200 Subject: [PATCH 003/186] Add RAND_status() RAND_status() returns 1 if the PRNG has been seeded with enough data, 0 otherwise. --- openssl-sys/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index b0ae686d..b7a61c52 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -873,6 +873,7 @@ extern "C" { out: *mut u8) -> c_int; pub fn RAND_bytes(buf: *mut u8, num: c_int) -> c_int; + pub fn RAND_status() -> c_int; pub fn RSA_new() -> *mut RSA; pub fn RSA_free(rsa: *mut RSA); From f16cd5586f554530aa1511a7586ed7d3b4642235 Mon Sep 17 00:00:00 2001 From: Andrei Oprisan Date: Tue, 4 Oct 2016 12:00:40 +0300 Subject: [PATCH 004/186] added try_ssl_size, which handles -1 as error and returns the value otherwise; added RSA private_decrypt and public encrypt lift_ssl_size Added public/private encrypt/decrypt to RSA from the original commit + tests; added try_ssl_returns_size macro to check for -1 in case of SSL functions which return size --- openssl/src/crypto/rsa.rs | 194 ++++++++++++++++++++++++++++++++++++++ openssl/src/macros.rs | 23 +++++ 2 files changed, 217 insertions(+) diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index 3ba063cd..e0d8e7ea 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -11,6 +11,24 @@ use HashTypeInternals; use crypto::hash; use crypto::util::{CallbackState, invoke_passwd_cb}; +/// Type of encryption padding to use. +#[derive(Copy, Clone)] +pub enum EncryptionPadding { + NoPadding, + OAEP, + PKCS1v15 +} + +impl EncryptionPadding { + pub fn openssl_padding_code(&self) -> c_int { + match self { + &EncryptionPadding::NoPadding => ffi::RSA_NO_PADDING, + &EncryptionPadding::OAEP => ffi::RSA_PKCS1_OAEP_PADDING, + &EncryptionPadding::PKCS1v15 => ffi::RSA_PKCS1_PADDING + } + } +} + pub struct RSA(*mut ffi::RSA); impl Drop for RSA { @@ -162,6 +180,125 @@ impl RSA { } } + pub fn max_data(&self) -> Option { + // 41 comes from RSA_public_encrypt(3) for OAEP + self.size().map(|len| len - 41) + } + + pub fn private_decrypt_with_padding(&self, from: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { + assert!(self.d().is_some(), "private components missing"); + let k_len = self.size().expect("RSA missing an n"); + let mut to: Vec = vec![0; k_len as usize]; + + unsafe { + let enc_len = try_ssl_returns_size!(ffi::RSA_private_decrypt(from.len() as i32, + from.as_ptr(), + to.as_mut_ptr(), + self.0, + padding.openssl_padding_code())); + to.truncate(enc_len as usize); + Ok(to) + } + } + + pub fn private_encrypt_with_padding(&self, from: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { + assert!(self.d().is_some(), "private components missing"); + let k_len = self.size().expect("RSA missing an n"); + let mut to:Vec = vec![0; k_len as usize]; + + assert!(from.len() < self.max_data().unwrap_or_else(|| 0) as usize); + + unsafe { + let enc_len = try_ssl_returns_size!(ffi::RSA_private_encrypt(from.len() as c_int, + from.as_ptr(), + to.as_mut_ptr(), + self.0, + padding.openssl_padding_code())); + assert!(enc_len as u32 == k_len); + + Ok(to) + } + } + + pub fn public_decrypt_with_padding(&self, from: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { + let k_len = self.size().expect("RSA missing an n"); + let mut to: Vec = vec![0; k_len as usize]; + + unsafe { + let enc_len = try_ssl_returns_size!(ffi::RSA_public_decrypt(from.len() as i32, + from.as_ptr(), + to.as_mut_ptr(), + self.0, + padding.openssl_padding_code())); + to.truncate(enc_len as usize); + Ok(to) + } + } + + pub fn public_encrypt_with_padding(&self, from: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { + let k_len = self.size().expect("RSA missing an n"); + let mut to:Vec = vec![0; k_len as usize]; + + assert!(from.len() < self.max_data().unwrap_or_else(|| 0) as usize); + + unsafe { + let enc_len = try_ssl_returns_size!(ffi::RSA_public_encrypt(from.len() as c_int, + from.as_ptr(), + to.as_mut_ptr(), + self.0, + padding.openssl_padding_code())); + assert!(enc_len as u32 == k_len); + + Ok(to) + } + } + + /** + * Encrypts data with the public key, using OAEP padding, returning the encrypted data. The + * supplied data must not be larger than max_data(). + */ + pub fn encrypt(&self, s: &[u8]) -> Result, ErrorStack> { self.public_encrypt_with_padding(s, EncryptionPadding::OAEP) } + + /** + * Encrypts data with the public key, using provided padding, returning the encrypted data. The + * supplied data must not be larger than max_data(). + */ + pub fn encrypt_with_padding(&self, s: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { self.public_encrypt_with_padding(s, padding) } + + /** + * Encrypts data with the public key, using OAEP padding, returning the encrypted data. The + * supplied data must not be larger than max_data(). + */ + pub fn public_encrypt(&self, s: &[u8]) -> Result, ErrorStack> { self.public_encrypt_with_padding(s, EncryptionPadding::OAEP) } + + /** + * Decrypts data with the public key, using PKCS1v15 padding, returning the decrypted data. + */ + pub fn public_decrypt(&self, s: &[u8]) -> Result, ErrorStack> { self.public_decrypt_with_padding(s, EncryptionPadding::PKCS1v15) } + + /** + * Decrypts data with the private key, expecting OAEP padding, returning the decrypted data. + */ + pub fn decrypt(&self, s: &[u8]) -> Result, ErrorStack> { self.private_decrypt_with_padding(s, EncryptionPadding::OAEP) } + + /** + * Decrypts data with the private key, using provided padding, returning the encrypted data. The + * supplied data must not be larger than max_data(). + */ + pub fn decrypt_with_padding(&self, s: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { self.private_decrypt_with_padding(s, padding) } + + /** + * Decrypts data with the private key, expecting OAEP padding, returning the decrypted data. + */ + pub fn private_decrypt(&self, s: &[u8]) -> Result, ErrorStack> { self.private_decrypt_with_padding(s, EncryptionPadding::OAEP) } + + /** + * Encrypts data with the private key, using PKCS1v15 padding, returning the encrypted data. The + * supplied data must not be larger than max_data(). + */ + pub fn private_encrypt(&self, s: &[u8]) -> Result, ErrorStack> { self.private_encrypt_with_padding(s, EncryptionPadding::PKCS1v15) } + + pub fn sign(&self, hash: hash::Type, message: &[u8]) -> Result, ErrorStack> { assert!(self.d().is_some(), "private components missing"); let k_len = self.size().expect("RSA missing an n"); @@ -335,4 +472,61 @@ mod test { assert!(password_queried); } + + #[test] + pub fn test_public_encrypt_private_decrypt_with_padding() { + let key = include_bytes!("../../test/rsa.pem.pub"); + let public_key = RSA::public_key_from_pem(key).unwrap(); + + let original_data: Vec = "This is test".to_string().into_bytes(); + let result = public_key.public_encrypt_with_padding(&original_data, EncryptionPadding::PKCS1v15).unwrap(); + + assert_eq!(result.len(), 256); + + let pkey = include_bytes!("../../test/rsa.pem"); + let private_key = RSA::private_key_from_pem(pkey).unwrap(); + let dec_result = private_key.private_decrypt_with_padding(&result, EncryptionPadding::PKCS1v15).unwrap(); + + assert_eq!(dec_result, original_data); + } + + #[test] + fn test_private_encrypt() { + let mut k0 = super::RSA::generate(512).unwrap(); + let k0pkey = k0.public_key_to_pem().unwrap(); + let mut k1 = super::RSA::public_key_from_pem(&k0pkey).unwrap(); + + let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); + + let emsg = k0.private_encrypt(&msg).unwrap(); + let dmsg = k1.public_decrypt(&emsg).unwrap(); + assert!(msg == dmsg); + } + + #[test] + fn test_public_encrypt() { + let mut k0 = super::RSA::generate(512).unwrap(); + let k0pkey = k0.public_key_to_pem().unwrap(); + let mut k1 = super::RSA::public_key_from_pem(&k0pkey).unwrap(); + + let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); + + let emsg = k1.public_encrypt(&msg).unwrap(); + let dmsg = k0.private_decrypt(&emsg).unwrap(); + assert!(msg == dmsg); + } + + #[test] + fn test_public_encrypt_pkcs() { + let mut k0 = super::RSA::generate(512).unwrap(); + let k0pkey = k0.public_key_to_pem().unwrap(); + let mut k1 = super::RSA::public_key_from_pem(&k0pkey).unwrap(); + + let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); + + let emsg = k1.public_encrypt_with_padding(&msg, super::EncryptionPadding::PKCS1v15).unwrap(); + let dmsg = k0.private_decrypt_with_padding(&emsg, super::EncryptionPadding::PKCS1v15).unwrap(); + assert!(msg == dmsg); + } + } diff --git a/openssl/src/macros.rs b/openssl/src/macros.rs index 35221f1c..e2d9cae5 100644 --- a/openssl/src/macros.rs +++ b/openssl/src/macros.rs @@ -33,6 +33,17 @@ macro_rules! try_ssl_null{ }) } +/// Shortcut return with SSL error if last error result is -1 +/// (default for size) +macro_rules! try_ssl_returns_size{ + ($e:expr) => ( + if $e == -1 { + return Err(::error::ErrorStack::get().into()) + } else { + $e + } + ) +} /// Lifts current SSL error code into Result<(), Error> /// if expression is true @@ -57,3 +68,15 @@ macro_rules! lift_ssl_if{ macro_rules! lift_ssl { ($e:expr) => (lift_ssl_if!($e == 0)) } + +/// Lifts current SSL error code into Result<(), Error> +/// if SSL returned -1 (default size error indication) +macro_rules! lift_ssl_returns_size { + ($e:expr) => ( { + if $e == -1 { + Err(::error::ErrorStack::get().into()) + } else { + Ok($e) + } + }) +} From 50648b7dac92200f5fb3d32422061e78404649c2 Mon Sep 17 00:00:00 2001 From: Andrei Oprisan Date: Fri, 7 Oct 2016 10:01:16 +0300 Subject: [PATCH 005/186] Removed max_size; removed all encrypt/decrypt methods except private/public encrypt/decrypt which take the padding --- openssl/src/crypto/rsa.rs | 95 +++++++++++---------------------------- 1 file changed, 26 insertions(+), 69 deletions(-) diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index e0d8e7ea..da2e1c79 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -20,7 +20,7 @@ pub enum EncryptionPadding { } impl EncryptionPadding { - pub fn openssl_padding_code(&self) -> c_int { + fn openssl_padding_code(&self) -> c_int { match self { &EncryptionPadding::NoPadding => ffi::RSA_NO_PADDING, &EncryptionPadding::OAEP => ffi::RSA_PKCS1_OAEP_PADDING, @@ -180,12 +180,10 @@ impl RSA { } } - pub fn max_data(&self) -> Option { - // 41 comes from RSA_public_encrypt(3) for OAEP - self.size().map(|len| len - 41) - } - - pub fn private_decrypt_with_padding(&self, from: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { + /** + * Decrypts data with the private key, using provided padding, returning the decrypted data. + */ + pub fn private_decrypt(&self, from: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { assert!(self.d().is_some(), "private components missing"); let k_len = self.size().expect("RSA missing an n"); let mut to: Vec = vec![0; k_len as usize]; @@ -201,13 +199,14 @@ impl RSA { } } - pub fn private_encrypt_with_padding(&self, from: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { + /** + * Encrypts data with the private key, using provided padding, returning the encrypted data. + */ + pub fn private_encrypt(&self, from: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { assert!(self.d().is_some(), "private components missing"); let k_len = self.size().expect("RSA missing an n"); let mut to:Vec = vec![0; k_len as usize]; - assert!(from.len() < self.max_data().unwrap_or_else(|| 0) as usize); - unsafe { let enc_len = try_ssl_returns_size!(ffi::RSA_private_encrypt(from.len() as c_int, from.as_ptr(), @@ -220,7 +219,10 @@ impl RSA { } } - pub fn public_decrypt_with_padding(&self, from: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { + /** + * Decrypts data with the public key, using provided padding, returning the decrypted data. + */ + pub fn public_decrypt(&self, from: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { let k_len = self.size().expect("RSA missing an n"); let mut to: Vec = vec![0; k_len as usize]; @@ -235,12 +237,13 @@ impl RSA { } } - pub fn public_encrypt_with_padding(&self, from: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { + /** + * Encrypts data with the public key, using provided padding, returning the encrypted data. + */ + pub fn public_encrypt(&self, from: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { let k_len = self.size().expect("RSA missing an n"); let mut to:Vec = vec![0; k_len as usize]; - assert!(from.len() < self.max_data().unwrap_or_else(|| 0) as usize); - unsafe { let enc_len = try_ssl_returns_size!(ffi::RSA_public_encrypt(from.len() as c_int, from.as_ptr(), @@ -253,53 +256,7 @@ impl RSA { } } - /** - * Encrypts data with the public key, using OAEP padding, returning the encrypted data. The - * supplied data must not be larger than max_data(). - */ - pub fn encrypt(&self, s: &[u8]) -> Result, ErrorStack> { self.public_encrypt_with_padding(s, EncryptionPadding::OAEP) } - - /** - * Encrypts data with the public key, using provided padding, returning the encrypted data. The - * supplied data must not be larger than max_data(). - */ - pub fn encrypt_with_padding(&self, s: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { self.public_encrypt_with_padding(s, padding) } - - /** - * Encrypts data with the public key, using OAEP padding, returning the encrypted data. The - * supplied data must not be larger than max_data(). - */ - pub fn public_encrypt(&self, s: &[u8]) -> Result, ErrorStack> { self.public_encrypt_with_padding(s, EncryptionPadding::OAEP) } - - /** - * Decrypts data with the public key, using PKCS1v15 padding, returning the decrypted data. - */ - pub fn public_decrypt(&self, s: &[u8]) -> Result, ErrorStack> { self.public_decrypt_with_padding(s, EncryptionPadding::PKCS1v15) } - - /** - * Decrypts data with the private key, expecting OAEP padding, returning the decrypted data. - */ - pub fn decrypt(&self, s: &[u8]) -> Result, ErrorStack> { self.private_decrypt_with_padding(s, EncryptionPadding::OAEP) } - - /** - * Decrypts data with the private key, using provided padding, returning the encrypted data. The - * supplied data must not be larger than max_data(). - */ - pub fn decrypt_with_padding(&self, s: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { self.private_decrypt_with_padding(s, padding) } - - /** - * Decrypts data with the private key, expecting OAEP padding, returning the decrypted data. - */ - pub fn private_decrypt(&self, s: &[u8]) -> Result, ErrorStack> { self.private_decrypt_with_padding(s, EncryptionPadding::OAEP) } - - /** - * Encrypts data with the private key, using PKCS1v15 padding, returning the encrypted data. The - * supplied data must not be larger than max_data(). - */ - pub fn private_encrypt(&self, s: &[u8]) -> Result, ErrorStack> { self.private_encrypt_with_padding(s, EncryptionPadding::PKCS1v15) } - - - pub fn sign(&self, hash: hash::Type, message: &[u8]) -> Result, ErrorStack> { + pub fn sign(&self, hash: hash::Type, message: &[u8]) -> Result, ErrorStack> { assert!(self.d().is_some(), "private components missing"); let k_len = self.size().expect("RSA missing an n"); let mut sig = vec![0; k_len as usize]; @@ -479,13 +436,13 @@ mod test { let public_key = RSA::public_key_from_pem(key).unwrap(); let original_data: Vec = "This is test".to_string().into_bytes(); - let result = public_key.public_encrypt_with_padding(&original_data, EncryptionPadding::PKCS1v15).unwrap(); + let result = public_key.public_encrypt(&original_data, EncryptionPadding::PKCS1v15).unwrap(); assert_eq!(result.len(), 256); let pkey = include_bytes!("../../test/rsa.pem"); let private_key = RSA::private_key_from_pem(pkey).unwrap(); - let dec_result = private_key.private_decrypt_with_padding(&result, EncryptionPadding::PKCS1v15).unwrap(); + let dec_result = private_key.private_decrypt(&result, EncryptionPadding::PKCS1v15).unwrap(); assert_eq!(dec_result, original_data); } @@ -498,8 +455,8 @@ mod test { let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); - let emsg = k0.private_encrypt(&msg).unwrap(); - let dmsg = k1.public_decrypt(&emsg).unwrap(); + let emsg = k0.private_encrypt(&msg, EncryptionPadding::PKCS1v15).unwrap(); + let dmsg = k1.public_decrypt(&emsg, EncryptionPadding::PKCS1v15).unwrap(); assert!(msg == dmsg); } @@ -511,8 +468,8 @@ mod test { let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); - let emsg = k1.public_encrypt(&msg).unwrap(); - let dmsg = k0.private_decrypt(&emsg).unwrap(); + let emsg = k1.public_encrypt(&msg, EncryptionPadding::OAEP).unwrap(); + let dmsg = k0.private_decrypt(&emsg, EncryptionPadding::OAEP).unwrap(); assert!(msg == dmsg); } @@ -524,8 +481,8 @@ mod test { let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); - let emsg = k1.public_encrypt_with_padding(&msg, super::EncryptionPadding::PKCS1v15).unwrap(); - let dmsg = k0.private_decrypt_with_padding(&emsg, super::EncryptionPadding::PKCS1v15).unwrap(); + let emsg = k1.public_encrypt(&msg, super::EncryptionPadding::PKCS1v15).unwrap(); + let dmsg = k0.private_decrypt(&emsg, super::EncryptionPadding::PKCS1v15).unwrap(); assert!(msg == dmsg); } From b6719de92e7ab26b38d1f69dcf637e39d3299d0c Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 7 Oct 2016 08:09:02 -0700 Subject: [PATCH 006/186] Rename EncryptionPadding to Padding --- openssl/src/crypto/rsa.rs | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index da2e1c79..b0a3e6b4 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -13,18 +13,18 @@ use crypto::util::{CallbackState, invoke_passwd_cb}; /// Type of encryption padding to use. #[derive(Copy, Clone)] -pub enum EncryptionPadding { +pub enum Padding { NoPadding, OAEP, PKCS1v15 } -impl EncryptionPadding { +impl Padding { fn openssl_padding_code(&self) -> c_int { match self { - &EncryptionPadding::NoPadding => ffi::RSA_NO_PADDING, - &EncryptionPadding::OAEP => ffi::RSA_PKCS1_OAEP_PADDING, - &EncryptionPadding::PKCS1v15 => ffi::RSA_PKCS1_PADDING + &Padding::NoPadding => ffi::RSA_NO_PADDING, + &Padding::OAEP => ffi::RSA_PKCS1_OAEP_PADDING, + &Padding::PKCS1v15 => ffi::RSA_PKCS1_PADDING } } } @@ -183,7 +183,7 @@ impl RSA { /** * Decrypts data with the private key, using provided padding, returning the decrypted data. */ - pub fn private_decrypt(&self, from: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { + pub fn private_decrypt(&self, from: &[u8], padding: Padding) -> Result, ErrorStack> { assert!(self.d().is_some(), "private components missing"); let k_len = self.size().expect("RSA missing an n"); let mut to: Vec = vec![0; k_len as usize]; @@ -202,7 +202,7 @@ impl RSA { /** * Encrypts data with the private key, using provided padding, returning the encrypted data. */ - pub fn private_encrypt(&self, from: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { + pub fn private_encrypt(&self, from: &[u8], padding: Padding) -> Result, ErrorStack> { assert!(self.d().is_some(), "private components missing"); let k_len = self.size().expect("RSA missing an n"); let mut to:Vec = vec![0; k_len as usize]; @@ -222,7 +222,7 @@ impl RSA { /** * Decrypts data with the public key, using provided padding, returning the decrypted data. */ - pub fn public_decrypt(&self, from: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { + pub fn public_decrypt(&self, from: &[u8], padding: Padding) -> Result, ErrorStack> { let k_len = self.size().expect("RSA missing an n"); let mut to: Vec = vec![0; k_len as usize]; @@ -240,7 +240,7 @@ impl RSA { /** * Encrypts data with the public key, using provided padding, returning the encrypted data. */ - pub fn public_encrypt(&self, from: &[u8], padding: EncryptionPadding) -> Result, ErrorStack> { + pub fn public_encrypt(&self, from: &[u8], padding: Padding) -> Result, ErrorStack> { let k_len = self.size().expect("RSA missing an n"); let mut to:Vec = vec![0; k_len as usize]; @@ -436,13 +436,13 @@ mod test { let public_key = RSA::public_key_from_pem(key).unwrap(); let original_data: Vec = "This is test".to_string().into_bytes(); - let result = public_key.public_encrypt(&original_data, EncryptionPadding::PKCS1v15).unwrap(); + let result = public_key.public_encrypt(&original_data, Padding::PKCS1v15).unwrap(); assert_eq!(result.len(), 256); let pkey = include_bytes!("../../test/rsa.pem"); let private_key = RSA::private_key_from_pem(pkey).unwrap(); - let dec_result = private_key.private_decrypt(&result, EncryptionPadding::PKCS1v15).unwrap(); + let dec_result = private_key.private_decrypt(&result, Padding::PKCS1v15).unwrap(); assert_eq!(dec_result, original_data); } @@ -455,8 +455,8 @@ mod test { let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); - let emsg = k0.private_encrypt(&msg, EncryptionPadding::PKCS1v15).unwrap(); - let dmsg = k1.public_decrypt(&emsg, EncryptionPadding::PKCS1v15).unwrap(); + let emsg = k0.private_encrypt(&msg, Padding::PKCS1v15).unwrap(); + let dmsg = k1.public_decrypt(&emsg, Padding::PKCS1v15).unwrap(); assert!(msg == dmsg); } @@ -468,8 +468,8 @@ mod test { let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); - let emsg = k1.public_encrypt(&msg, EncryptionPadding::OAEP).unwrap(); - let dmsg = k0.private_decrypt(&emsg, EncryptionPadding::OAEP).unwrap(); + let emsg = k1.public_encrypt(&msg, Padding::OAEP).unwrap(); + let dmsg = k0.private_decrypt(&emsg, Padding::OAEP).unwrap(); assert!(msg == dmsg); } @@ -481,8 +481,8 @@ mod test { let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); - let emsg = k1.public_encrypt(&msg, super::EncryptionPadding::PKCS1v15).unwrap(); - let dmsg = k0.private_decrypt(&emsg, super::EncryptionPadding::PKCS1v15).unwrap(); + let emsg = k1.public_encrypt(&msg, super::Padding::PKCS1v15).unwrap(); + let dmsg = k0.private_decrypt(&emsg, super::Padding::PKCS1v15).unwrap(); assert!(msg == dmsg); } From c1e41349fbdf6d4ff942e236500c0d639203968d Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 7 Oct 2016 08:10:01 -0700 Subject: [PATCH 007/186] Rename NoPadding to None --- openssl/src/crypto/rsa.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index b0a3e6b4..8a3f9188 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -14,17 +14,17 @@ use crypto::util::{CallbackState, invoke_passwd_cb}; /// Type of encryption padding to use. #[derive(Copy, Clone)] pub enum Padding { - NoPadding, + None, OAEP, PKCS1v15 } impl Padding { fn openssl_padding_code(&self) -> c_int { - match self { - &Padding::NoPadding => ffi::RSA_NO_PADDING, - &Padding::OAEP => ffi::RSA_PKCS1_OAEP_PADDING, - &Padding::PKCS1v15 => ffi::RSA_PKCS1_PADDING + match *self { + Padding::None => ffi::RSA_NO_PADDING, + Padding::OAEP => ffi::RSA_PKCS1_OAEP_PADDING, + Padding::PKCS1v15 => ffi::RSA_PKCS1_PADDING } } } From 43c951f743e68fac5f45119eda7c994882a1d489 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Fri, 30 Sep 2016 00:43:05 -0700 Subject: [PATCH 008/186] Add support for OpenSSL 1.1.0 This commit is relatively major refactoring of the `openssl-sys` crate as well as the `openssl` crate itself. The end goal here was to support OpenSSL 1.1.0, and lots of other various tweaks happened along the way. The major new features are: * OpenSSL 1.1.0 is supported * OpenSSL 0.9.8 is no longer supported (aka all OSX users by default) * All FFI bindings are verified with the `ctest` crate (same way as the `libc` crate) * CI matrixes are vastly expanded to include 32/64 of all platforms, more OpenSSL version coverage, as well as ARM coverage on Linux * The `c_helpers` module is completely removed along with the `gcc` dependency. * The `openssl-sys` build script was completely rewritten * Now uses `OPENSSL_DIR` to find the installation, not include/lib env vars. * Better error messages for mismatched versions. * Better error messages for failing to find OpenSSL on a platform (more can be done here) * Probing of OpenSSL build-time configuration to inform the API of the `*-sys` crate. * Many Cargo features have been removed as they're now enabled by default. As this is a breaking change to both the `openssl` and `openssl-sys` crates this will necessitate a major version bump of both. There's still a few more API questions remaining but let's hash that out on a PR! Closes #452 --- .travis.yml | 104 +++-- Cargo.toml | 2 +- README.md | 112 +++--- appveyor.yml | 48 ++- openssl-sys/Cargo.toml | 26 -- openssl-sys/build.rs | 386 +++++++++++++++---- openssl-sys/src/lib.rs | 720 +++++++++-------------------------- openssl-sys/src/ossl10x.rs | 569 +++++++++++++++++++++++++++ openssl-sys/src/ossl110.rs | 146 +++++++ openssl-sys/src/probe.rs | 77 ---- openssl/Cargo.toml | 43 +-- openssl/build.rs | 37 +- openssl/src/bn/mod.rs | 68 ++-- openssl/src/c_helpers.c | 67 ---- openssl/src/c_helpers.rs | 15 - openssl/src/crypto/dsa.rs | 56 ++- openssl/src/crypto/hash.rs | 22 +- openssl/src/crypto/hmac.rs | 130 +++++-- openssl/src/crypto/mod.rs | 1 - openssl/src/crypto/pkcs12.rs | 34 +- openssl/src/crypto/pkcs5.rs | 7 +- openssl/src/crypto/rsa.rs | 159 ++++++-- openssl/src/crypto/symm.rs | 30 +- openssl/src/dh/mod.rs | 59 ++- openssl/src/error.rs | 5 +- openssl/src/lib.rs | 5 +- openssl/src/macros.rs | 14 + openssl/src/ssl/bio.rs | 176 ++++++--- openssl/src/ssl/mod.rs | 350 +++++++++-------- openssl/src/ssl/tests/mod.rs | 124 +++--- openssl/src/version.rs | 31 +- openssl/src/x509/mod.rs | 132 +++++-- openssl/src/x509/tests.rs | 2 - openssl/test/build.sh | 35 +- openssl/test/run.sh | 33 +- systest/Cargo.toml | 12 + systest/build.rs | 110 ++++++ systest/src/main.rs | 9 + 38 files changed, 2513 insertions(+), 1443 deletions(-) create mode 100644 openssl-sys/src/ossl10x.rs create mode 100644 openssl-sys/src/ossl110.rs delete mode 100644 openssl-sys/src/probe.rs delete mode 100644 openssl/src/c_helpers.c delete mode 100644 openssl/src/c_helpers.rs create mode 100644 systest/Cargo.toml create mode 100644 systest/build.rs create mode 100644 systest/src/main.rs diff --git a/.travis.yml b/.travis.yml index 0d76be3d..347a23c5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,28 +1,86 @@ language: rust -sudo: false -addons: - apt: - packages: - - gcc-arm-linux-gnueabihf -rust: -- nightly -- 1.9.0 -os: -- osx -- linux +sudo: required +rust: stable +dist: trusty + env: - matrix: - - TEST_FEATURES=false - - TEST_FEATURES=true + global: + - TARGET=x86_64-unknown-linux-gnu matrix: - # include: - # - os: linux - # env: TARGET=arm-unknown-linux-gnueabihf TEST_FEATURES=true - # rust: 1.7.0 - exclude: - - os: osx - env: TEST_FEATURES=true + include: + # ARM-bit version compat + - env: > + TARGET=arm-unknown-linux-gnueabihf + BUILD_OPENSSL_VERSION=1.0.2h + CARGO_TARGET_ARM_UNKNOWN_LINUX_GNUEABIHF_LINKER=arm-linux-gnueabihf-gcc + QEMU_LD_PREFIX=/usr/arm-linux-gnueabihf + RUST_TEST_THREADS=1 + addons: + apt: + packages: + - gcc-arm-linux-gnueabihf + - qemu-user-static + - libc6-dev-armhf-cross + - binfmt-support + - env: > + TARGET=arm-unknown-linux-gnueabihf + BUILD_OPENSSL_VERSION=1.1.0b + CARGO_TARGET_ARM_UNKNOWN_LINUX_GNUEABIHF_LINKER=arm-linux-gnueabihf-gcc + QEMU_LD_PREFIX=/usr/arm-linux-gnueabihf + RUST_TEST_THREADS=1 + addons: + apt: + packages: + - gcc-arm-linux-gnueabihf + - qemu-user-static + - libc6-dev-armhf-cross + - binfmt-support + + # Minimum version supported + - rust: 1.9.0 + + # beta/nightly channels + - rust: beta + - rust: nightly + + # 64-bit version compat + - env: BUILD_OPENSSL_VERSION=1.0.1u + - env: BUILD_OPENSSL_VERSION=1.0.2h + - env: BUILD_OPENSSL_VERSION=1.1.0b + + # 32-bit version compat + - env: TARGET=i686-unknown-linux-gnu BUILD_OPENSSL_VERSION=1.0.1u + addons: + apt: + packages: + - gcc-multilib + - env: TARGET=i686-unknown-linux-gnu BUILD_OPENSSL_VERSION=1.0.2h + addons: + apt: + packages: + - gcc-multilib + - env: TARGET=i686-unknown-linux-gnu BUILD_OPENSSL_VERSION=1.1.0b + addons: + apt: + packages: + - gcc-multilib + + # osx 32/64 + - os: osx + env: TARGET=x86_64-apple-darwin + - os: osx + env: TARGET=i686-apple-darwin + install: brew uninstall openssl && brew install openssl --universal + + before_install: -- ./openssl/test/build.sh + - ./openssl/test/build.sh + - curl https://static.rust-lang.org/rustup.sh | + sh -s -- --add-target=$TARGET --disable-sudo -y --prefix=`rustc --print sysroot` script: -- ./openssl/test/run.sh + - ./openssl/test/run.sh + +cache: + cargo: true + directories: + - $HOME/openssl diff --git a/Cargo.toml b/Cargo.toml index 0bd2c005..2ef99c17 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,2 +1,2 @@ [workspace] -members = ["openssl", "openssl-sys"] +members = ["openssl", "openssl-sys", "systest"] diff --git a/README.md b/README.md index d919cff1..54f208b4 100644 --- a/README.md +++ b/README.md @@ -6,13 +6,16 @@ ## Building -rust-openssl depends on both the OpenSSL runtime libraries and headers. +rust-openssl depends on the OpenSSL runtime libraries version 1.0.1 or above. +Currently the libraries need to be present in the build environment before this +crate is compiled, and some instructions of how to do this are in the sections +below. ### Linux -On Linux, you can install OpenSSL via your package manager. The headers are -sometimes provided in a separate package than the runtime libraries - look for -something like `openssl-devel` or `libssl-dev`. +On Linux, you can typically install OpenSSL via your package manager. The +headers are sometimes provided in a separate package than the runtime libraries +- look for something like `openssl-devel` or `libssl-dev`. ```bash # On Ubuntu @@ -23,79 +26,78 @@ sudo pacman -S openssl sudo dnf install openssl-devel ``` +If installation via a package manager is not possible, or if you're cross +compiling to a separate target, you'll typically need to compile OpenSSL from +source. That can normally be done with: + +``` +curl -O https://www.openssl.org/source/openssl-1.1.0b.tar.gz +tar xf openssl-1.1.0b.tar.gz +cd openssl-1.1.0b +export CC=... +./Configure --prefix=... linux-x86_64 -fPIC +make -j$(nproc) +make install +``` + ### OSX -OpenSSL 0.9.8 is preinstalled on OSX. Some features are only available when -linking against OpenSSL 1.0.0 or greater; see below on how to point -rust-openssl to a separate installation. OSX releases starting at 10.11, "El -Capitan", no longer include OpenSSL headers which will prevent the `openssl` -crate from compiling. +Although OpenSSL 0.9.8 is preinstalled on OSX this library is being phased out +of OSX and this crate also does not support this version of OpenSSL. To use this +crate on OSX you'll need to install OpenSSL via some alternate means, typically +homebrew: -For OSX 10.11 you can use brew to install OpenSSL and then set the environment variables -as described below. ```bash brew install openssl -export OPENSSL_INCLUDE_DIR=`brew --prefix openssl`/include -export OPENSSL_LIB_DIR=`brew --prefix openssl`/lib ``` -May be necessary clean the repository with `cargo clean` before build again. +### Windows MSVC -### Windows +On MSVC it's unfortunately not always a trivial process acquiring OpenSSL. +Perhaps the easiest way to do this right now is to download [precompiled +binaries] and install them on your system. Currently it's recommended to +install the 1.1.0b light installation if you're choosing this route. -On Windows, consider building with [mingw-w64](http://mingw-w64.org/). -Build script will try to find mingw in `PATH` environment variable to provide -Cargo with location where openssl libs from mingw-w64 package may be found. +[precompiled binaries]: http://slproweb.com/products/Win32OpenSSL.html -mingw-w64 can be easily installed by using [MSYS2](http://msys2.github.io/). Install MSYS2 according to the instructions, and then, from an MSYS2 Shell, install mingw-w64: +Once a precompiled binary is installed you can configure this crate to find the +installation via an environment variable: -32-bit: -```bash -pacman -S mingw-w64-i686-gcc -``` - -64-bit -```bash -pacman -S mingw-w64-x86_64-gcc +``` +set OPENSSL_DIR=C:\OpenSSL-Win64 ``` -and then install the mingw-w64 toolchain. +After that, you're just a `cargo build` away! -32-bit: -```bash -pacman -S mingw-w64-i686-toolchain +### Windows GNU (MinGW) + +The easiest way to acquire OpenSSL when working with MinGW is to ensure you're +using [MSYS2](http://msys2.github.io) and to then execute: + +``` +# 32-bit +pacman -S mingw-w64-i686-openssl + +# 64-bit +pacman -S mingw-w64-x86_64-openssl ``` -64-bit: -```bash -pacman -S mingw-w64-x86_64-toolchain -``` - -Alternatively, install OpenSSL from [here][1]. Cargo will not be able to find OpenSSL if it's -installed to the default location. You can either copy the `include/openssl` -directory, `libssl32.dll`, and `libeay32.dll` to locations that Cargo can find -or pass the location to Cargo via environment variables: - -```bash -env OPENSSL_LIB_DIR=C:/OpenSSL-Win64 OPENSSL_INCLUDE_DIR=C:/OpenSSL-Win64/include cargo build -``` +And after that, a `cargo build` should be all you need! ### Manual configuration rust-openssl's build script will by default attempt to locate OpenSSL via -pkg-config. This will not work in some situations, for example, on systems that -don't have pkg-config, when cross compiling, or when using a copy of OpenSSL +pkg-config or other system-specific mechanisms. This will not work in some +situations however, for example cross compiling or when using a copy of OpenSSL other than the normal system install. The build script can be configured via environment variables: -* `OPENSSL_LIB_DIR` - If specified, a directory that will be used to find - OpenSSL runtime libraries. -* `OPENSSL_INCLUDE_DIR` - If specified, a directory that will be used to find - OpenSSL headers. + +* `OPENSSL_DIR` - If specified, a directory that will be used to find + OpenSSL installation. It's expected that under this directory the `include` + folder has header files and a `lib` folder has the runtime libraries. * `OPENSSL_STATIC` - If specified, OpenSSL libraries will be statically rather - than dynamically linked. + than dynamically linked. -If either `OPENSSL_LIB_DIR` or `OPENSSL_INCLUDE_DIR` are specified, then the -build script will skip the pkg-config step. - -[1]: http://slproweb.com/products/Win32OpenSSL.html +If `OPENSSL_DIR` is specified, then the build script will skip the pkg-config +step. diff --git a/appveyor.yml b/appveyor.yml index 4cd6c231..9a7a3dc7 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,25 +1,43 @@ environment: - OPENSSL_INCLUDE_DIR: C:\OpenSSL\include - OPENSSL_LIB_DIR: C:\OpenSSL\lib - OPENSSL_LIBS: ssleay32:libeay32 matrix: - - TARGET: i686-pc-windows-gnu - BITS: 32 - - TARGET: x86_64-pc-windows-msvc - BITS: 64 + # 1.1.0, 64/32 bit + - TARGET: i686-pc-windows-gnu + BITS: 32 + MSYS2: 1 + OPENSSL_VERSION: 1_1_0b + - TARGET: x86_64-pc-windows-msvc + BITS: 64 + OPENSSL_VERSION: 1_1_0b + OPENSSL_DIR: C:\OpenSSL + + # 1.0.2, 64/32 bit + - TARGET: x86_64-pc-windows-gnu + BITS: 64 + MSYS2: 1 + OPENSSL_VERSION: 1_0_2j + - TARGET: i686-pc-windows-msvc + BITS: 32 + OPENSSL_VERSION: 1_0_2j + OPENSSL_DIR: C:\OpenSSL install: - - ps: Start-FileDownload "http://slproweb.com/download/Win${env:BITS}OpenSSL-1_0_2h.exe" - - Win%BITS%OpenSSL-1_0_2h.exe /SILENT /VERYSILENT /SP- /DIR="C:\OpenSSL" - - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-1.9.0-${env:TARGET}.exe" - - rust-1.9.0-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" - - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin - - SET PATH=%PATH%;C:\MinGW\bin + # install OpenSSL + - ps: Start-FileDownload "http://slproweb.com/download/Win${env:BITS}OpenSSL-${env:OPENSSL_VERSION}.exe" + - Win%BITS%OpenSSL-%OPENSSL_VERSION%.exe /SILENT /VERYSILENT /SP- /DIR="C:\OpenSSL" + + # Install Rust + - curl -sSf -o rustup-init.exe https://win.rustup.rs/ + - rustup-init.exe -y --default-host %TARGET% + - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin + - if defined MSYS2 set PATH=C:\msys64\mingw%BITS%\bin;%PATH% - rustc -V - cargo -V build: false -# Don't run doctests due to rust-lang/cargo#1592 test_script: - - cargo test --lib --manifest-path openssl/Cargo.toml + - cargo run --manifest-path systest/Cargo.toml --target %TARGET% + - cargo test --manifest-path openssl/Cargo.toml --target %TARGET% +cache: + - target + - C:\Users\appveyor\.cargo\registry diff --git a/openssl-sys/Cargo.toml b/openssl-sys/Cargo.toml index dcdf9d1a..d44dcfc1 100644 --- a/openssl-sys/Cargo.toml +++ b/openssl-sys/Cargo.toml @@ -10,38 +10,12 @@ documentation = "https://sfackler.github.io/rust-openssl/doc/v0.7.17/openssl_sys links = "openssl" build = "build.rs" -[features] -tlsv1_2 = [] -tlsv1_1 = [] -dtlsv1 = [] -dtlsv1_2 = [] -sslv2 = [] -sslv3 = [] -aes_xts = [] -aes_ctr = [] -npn = [] -alpn = [] -rfc5114 = [] -pkcs5_pbkdf2_hmac = [] -ecdh_auto = [] -hmac_clone = [] - [dependencies] libc = "0.2" [build-dependencies] pkg-config = "0.3" -[target.le32-unknown-nacl.dependencies] -libressl-pnacl-sys = "2.1.0" -[target.x86_64-unknown-nacl.dependencies] -libressl-pnacl-sys = "2.1.0" -[target.i686-unknown-nacl.dependencies] -libressl-pnacl-sys = "2.1.0" -[target.arm-unknown-nacl.dependencies] -libressl-pnacl-sys = "2.1.0" - -# Only here to make sure we link to these in a static build on Windows [target.'cfg(windows)'.dependencies] user32-sys = "0.2" gdi32-sys = "0.2" diff --git a/openssl-sys/build.rs b/openssl-sys/build.rs index 0e3a76d2..9f5b3877 100644 --- a/openssl-sys/build.rs +++ b/openssl-sys/build.rs @@ -1,86 +1,344 @@ extern crate pkg_config; +use std::collections::HashSet; use std::env; +use std::ffi::OsString; +use std::fs::File; +use std::io::Read; +use std::path::{Path, PathBuf}; fn main() { let target = env::var("TARGET").unwrap(); - // libressl_pnacl_sys links the libs needed. - if target.ends_with("nacl") { return; } + let openssl_dir = env::var_os("OPENSSL_DIR").unwrap_or_else(|| { + find_openssl_dir(&target) + }); - let lib_dir = env::var("OPENSSL_LIB_DIR").ok(); - let include_dir = env::var("OPENSSL_INCLUDE_DIR").ok(); - - if lib_dir.is_none() && include_dir.is_none() { - // rustc doesn't seem to work with pkg-config's output in mingw64 - if !target.contains("windows") { - if let Ok(info) = pkg_config::find_library("openssl") { - // avoid empty include paths as they are not supported by GCC - if info.include_paths.len() > 0 { - let paths = env::join_paths(info.include_paths).unwrap(); - println!("cargo:include={}", paths.to_str().unwrap()); - } - return; - } - } - if let Some(mingw_paths) = get_mingw_in_path() { - for path in mingw_paths { - println!("cargo:rustc-link-search=native={}", path); - } - } + let lib_dir = Path::new(&openssl_dir).join("lib"); + let include_dir = Path::new(&openssl_dir).join("include"); + if !Path::new(&lib_dir).exists() { + panic!("OpenSSL library directory does not exist: {}", + lib_dir.to_string_lossy()); } - let libs_env = env::var("OPENSSL_LIBS").ok(); - let libs = match libs_env { - Some(ref v) => v.split(":").collect(), - None => if target.contains("windows") { - if get_mingw_in_path().is_some() && lib_dir.is_none() && include_dir.is_none() { - vec!["ssleay32", "eay32"] - } else { - vec!["ssl32", "eay32"] - } - } else { - vec!["ssl", "crypto"] - } - }; + if !Path::new(&include_dir).exists() { + panic!("OpenSSL include directory does not exist: {}", + include_dir.to_string_lossy()); + } - let mode = if env::var_os("OPENSSL_STATIC").is_some() { - "static" + println!("cargo:rustc-link-search=native={}", lib_dir.to_string_lossy()); + println!("cargo:include={}", include_dir.to_string_lossy()); + + let version = validate_headers(&[include_dir.clone().into()], + &[lib_dir.clone().into()]); + + let libs = if (version.contains("0x10001") || + version.contains("0x10002")) && + target.contains("windows") { + ["ssleay32", "libeay32"] + } else if target.contains("windows") { + ["libssl", "libcrypto"] } else { - "dylib" + ["ssl", "crypto"] }; - if let Some(lib_dir) = lib_dir { - println!("cargo:rustc-link-search=native={}", lib_dir); - } - - for lib in libs { - println!("cargo:rustc-link-lib={}={}", mode, lib); - } - - if let Some(include_dir) = include_dir { - println!("cargo:include={}", include_dir); + let kind = determine_mode(Path::new(&lib_dir), &libs); + for lib in libs.iter() { + println!("cargo:rustc-link-lib={}={}", kind, lib); } } -fn get_mingw_in_path() -> Option> { - match env::var_os("PATH") { - Some(env_path) => { - let paths: Vec = env::split_paths(&env_path).filter_map(|path| { - use std::ascii::AsciiExt; +fn find_openssl_dir(target: &str) -> OsString { + let host = env::var("HOST").unwrap(); - match path.to_str() { - Some(path_str) => { - if path_str.to_ascii_lowercase().contains("mingw") { - Some(path_str.to_string()) - } else { None } - }, - None => None + if host.contains("apple-darwin") && target.contains("apple-darwin") { + let homebrew = Path::new("/usr/local/opt/openssl"); + if homebrew.exists() { + return homebrew.to_path_buf().into() + } + let homebrew = Path::new("/usr/local/opt/openssl@1.1"); + if homebrew.exists() { + return homebrew.to_path_buf().into() + } + } + + try_pkg_config(); + + let mut msg = format!(" + +Could not find directory of OpenSSL installation, and this `-sys` crate cannot +proceed without this knowledge. If OpenSSL is installed and this crate had +trouble finding it, you can set the `OPENSSL_DIR` environment variable for the +compilation process. + +If you're in a situation where you think the directory *should* be found +automatically, please open a bug at https://github.com/sfackler/rust-openssl +and include information about your system as well as this message. + + $HOST = {} + $TARGET = {} + openssl-sys = {} + +", + host, target, env!("CARGO_PKG_VERSION")); + + if host.contains("apple-darwin") && target.contains("apple-darwin") { + let system = Path::new("/usr/lib/libssl.0.9.8.dylib"); + if system.exists() { + msg.push_str(&format!(" + +It looks like you're compiling on macOS, where the system contains a version of +OpenSSL 0.9.8. This crate no longer supports OpenSSL 0.9.8. + +As a consumer of this crate, you can fix this error by using Homebrew to +install the `openssl` package, or as a maintainer you can use the openssl-sys +0.7 crate for support with OpenSSL 0.9.8. + +Unfortunately though the compile cannot continue, so aborting. + +")); + } + } + + if host.contains("windows") && target.contains("windows-gnu") { + msg.push_str(&format!(" +It looks like you're compiling for MinGW but you may not have either OpenSSL or +pkg-config installed. You can install these two dependencies with: + + pacman -S openssl pkg-config + +and try building this crate again. + +" +)); + } + + if host.contains("windows") && target.contains("windows-msvc") { + msg.push_str(&format!(" +It looks like you're compiling for MSVC but we couldn't detect an OpenSSL +installation. If there isn't one installed then you can try the rust-openssl +README for more information about how to download precompiled binaries of +OpenSSL: + + https://github.com/sfackler/rust-openssl#windows + +" +)); + } + + panic!(msg); +} + +/// Attempt to find OpenSSL through pkg-config. +/// +/// Note that if this succeeds then the function does not return as pkg-config +/// typically tells us all the information that we need. +fn try_pkg_config() { + let target = env::var("TARGET").unwrap(); + let host = env::var("HOST").unwrap(); + + // If we're going to windows-gnu we can use pkg-config, but only so long as + // we're coming from a windows host. + // + // Otherwise if we're going to windows we probably can't use pkg-config. + if target.contains("windows-gnu") && host.contains("windows") { + env::set_var("PKG_CONFIG_ALLOW_CROSS", "1"); + } else if target.contains("windows") { + return + } + + // We're going to be looking at header files, so show us all the system + // cflags dirs for showing us lots of `-I`. + env::set_var("PKG_CONFIG_ALLOW_SYSTEM_CFLAGS", "1"); + + let lib = match pkg_config::find_library("openssl") { + Ok(lib) => lib, + Err(_) => return, + }; + + if lib.include_paths.len() == 0 { + panic!(" + +Used pkg-config to discover the OpenSSL installation, but pkg-config did not +return any include paths for the installation. This crate needs to take a peek +at the header files so it cannot proceed unless they're found. + +You can try fixing this by setting the `OPENSSL_DIR` environment variable +pointing to your OpenSSL installation. + +"); + } + + validate_headers(&lib.include_paths, &lib.link_paths); + + for include in lib.include_paths.iter() { + println!("cargo:include={}", include.display()); + } + + std::process::exit(0); +} + +/// Validates the header files found in `include_dir` and then returns the +/// version string of OpenSSL. +fn validate_headers(include_dirs: &[PathBuf], + libdirs: &[PathBuf]) -> String { + // This `*-sys` crate only works with OpenSSL 1.0.1, 1.0.2, and 1.1.0. To + // correctly expose the right API from this crate, take a look at + // `opensslv.h` to see what version OpenSSL claims to be. + let mut version_header = String::new(); + let mut include = include_dirs.iter() + .map(|p| p.join("openssl/opensslv.h")) + .filter(|p| p.exists()); + let mut f = match include.next() { + Some(f) => File::open(f).unwrap(), + None => { + panic!("failed to open header file at `openssl/opensslv.h` to learn + about OpenSSL's version number, looked inside:\n\n{:#?}\n\n", + include_dirs); + } + }; + f.read_to_string(&mut version_header).unwrap(); + + // Do a bit of string parsing to find `#define OPENSSL_VERSION_NUMBER ...` + let version_line = version_header.lines().find(|l| { + l.contains("define ") && l.contains("OPENSSL_VERSION_NUMBER") + }).and_then(|line| { + let start = match line.find("0x") { + Some(start) => start, + None => return None, + }; + Some(line[start..].trim()) + }); + let version_text = match version_line { + Some(text) => text, + None => { + panic!("header file at `{}` did not include `OPENSSL_VERSION_NUMBER` \ + that this crate recognized, failed to learn about the \ + OpenSSL version number"); + } + }; + if version_text.contains("0x10001") { + println!("cargo:rustc-cfg=ossl101"); + println!("cargo:is_101=1"); + } else if version_text.contains("0x10002") { + println!("cargo:rustc-cfg=ossl102"); + println!("cargo:is_102=1"); + } else if version_text.contains("0x10100") { + println!("cargo:rustc-cfg=ossl110"); + println!("cargo:is_110=1"); + } else { + panic!(" + +This crate is only compatible with OpenSSL 1.0.1, 1.0.2, and 1.1.0, but a +different version of OpenSSL was found: + + {} + +The build is now aborting due to this version mismatch. + +", version_text); + } + + // OpenSSL has a number of build-time configuration options which affect + // various structs and such. Since OpenSSL 1.1.0 this isn't really a problem + // as the library is much more FFI-friendly, but 1.0.{1,2} suffer this problem. + // + // To handle all this conditional compilation we slurp up the configuration + // file of OpenSSL, `opensslconf.h`, and then dump out everything it defines + // as our own #[cfg] directives. That way the `ossl10x.rs` bindings can + // account for compile differences and such. + if version_text.contains("0x1000") { + let mut conf_header = String::new(); + let mut include = include_dirs.iter() + .map(|p| p.join("openssl/opensslconf.h")) + .filter(|p| p.exists()); + let mut f = match include.next() { + Some(f) => File::open(f).unwrap(), + None => { + // It's been seen that on linux the include dir printed out by + // `pkg-config` doesn't actually have opensslconf.h. Instead + // it's in an architecture-specific include directory. + // + // Try to detect that case to see if it exists. + let mut libdirs = libdirs.iter().map(|p| { + p.iter() + .map(|p| if p == "lib" {"include".as_ref()} else {p}) + .collect::() + }).map(|p| { + p.join("openssl/opensslconf.h") + }).filter(|p| p.exists()); + match libdirs.next() { + Some(f) => File::open(f).unwrap(), + None => { + panic!("failed to open header file at + `openssl/opensslconf.h` to learn about \ + OpenSSL's version number, looked \ + inside:\n\n{:#?}\n\n", + include_dirs); + } } - }).collect(); + } + }; + f.read_to_string(&mut conf_header).unwrap(); - if paths.len() > 0 { Some(paths) } else { None } - }, - None => None + // Look for `#define OPENSSL_FOO`, print out everything as our own + // #[cfg] flag. + for line in conf_header.lines() { + let i = match line.find("define ") { + Some(i) => i, + None => continue, + }; + let var = line[i + "define ".len()..].trim(); + if var.starts_with("OPENSSL") && !var.contains(" ") { + println!("cargo:rustc-cfg=osslconf=\"{}\"", var); + } + } } + + return version_text.to_string() +} + +/// Given a libdir for OpenSSL (where artifacts are located) as well as the name +/// of the libraries we're linking to, figure out whether we should link them +/// statically or dynamically. +fn determine_mode(libdir: &Path, libs: &[&str]) -> &'static str { + // First see if a mode was explicitly requested + let kind = env::var("OPENSSL_STATIC").ok(); + match kind.as_ref().map(|s| &s[..]) { + Some("0") => return "dylib", + Some(_) => return "static", + None => {} + } + + // Next, see what files we actually have to link against, and see what our + // possibilities even are. + let files = libdir.read_dir().unwrap() + .map(|e| e.unwrap()) + .map(|e| e.file_name()) + .filter_map(|e| e.into_string().ok()) + .collect::>(); + let can_static = libs.iter().all(|l| { + files.contains(&format!("lib{}.a", l)) || + files.contains(&format!("{}.lib", l)) + }); + let can_dylib = libs.iter().all(|l| { + files.contains(&format!("lib{}.so", l)) || + files.contains(&format!("{}.dll", l)) || + files.contains(&format!("lib{}.dylib", l)) + }); + match (can_static, can_dylib) { + (true, false) => return "static", + (false, true) => return "dylib", + (false, false) => { + panic!("OpenSSL libdir at `{}` does not contain the required files \ + to either statically or dynamically link OpenSSL", + libdir.display()); + } + (true, true) => {} + } + + // Ok, we've got not explicit preference and can *either* link statically or + // link dynamically. In the interest of "security upgrades" and/or "best + // practices with security libs", let's link dynamically. + "dylib" } diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index b7a61c52..1c1df579 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1,64 +1,45 @@ #![allow(non_camel_case_types, non_upper_case_globals, non_snake_case)] -#![allow(dead_code)] +#![allow(dead_code, overflowing_literals)] #![doc(html_root_url="https://sfackler.github.io/rust-openssl/doc/v0.7.17")] extern crate libc; -#[cfg(target_os = "nacl")] -extern crate libressl_pnacl_sys; - use libc::{c_void, c_int, c_char, c_ulong, c_long, c_uint, c_uchar, size_t, FILE}; -use std::mem; use std::ptr; -use std::sync::{Mutex, MutexGuard}; -use std::sync::{Once, ONCE_INIT}; -pub type ASN1_INTEGER = c_void; -pub type ASN1_STRING = c_void; -pub type ASN1_TIME = c_void; -pub type ASN1_TYPE = c_void; -pub type BN_CTX = c_void; -pub type BN_GENCB = c_void; -pub type COMP_METHOD = c_void; -pub type DH = c_void; -pub type ENGINE = c_void; -pub type EVP_CIPHER_CTX = c_void; -pub type EVP_MD = c_void; -pub type EVP_PKEY_CTX = c_void; -pub type SSL = c_void; -pub type SSL_CIPHER = c_void; -pub type SSL_CTX = c_void; -pub type SSL_METHOD = c_void; -pub type X509 = c_void; -pub type X509_CRL = c_void; -pub type X509_EXTENSION = c_void; -pub type X509_NAME = c_void; -pub type X509_NAME_ENTRY = c_void; -pub type X509_REQ = c_void; -pub type X509_STORE_CTX = c_void; -pub type bio_st = c_void; -#[repr(C)] -pub struct PKCS12(c_void); +#[cfg(any(ossl101, ossl102))] +mod ossl10x; +#[cfg(any(ossl101, ossl102))] +pub use ossl10x::*; -#[repr(C)] -pub struct stack_st_X509 { - pub stack: _STACK, -} +#[cfg(ossl110)] +mod ossl110; +#[cfg(ossl110)] +pub use ossl110::*; -#[repr(C)] -pub struct stack_st_X509_EXTENSION { - pub stack: _STACK, -} - -#[repr(C)] -pub struct stack_st_GENERAL_NAME { - pub stack: _STACK, -} - -#[repr(C)] -pub struct stack_st_void { - pub stack: _STACK, -} +pub enum ASN1_INTEGER {} +pub enum ASN1_STRING {} +pub enum ASN1_TIME {} +pub enum ASN1_TYPE {} +pub enum BN_CTX {} +pub enum BN_GENCB {} +pub enum COMP_METHOD {} +pub enum ENGINE {} +pub enum EVP_CIPHER_CTX {} +pub enum EVP_MD {} +pub enum EVP_PKEY_CTX {} +pub enum SSL {} +pub enum SSL_CIPHER {} +pub enum SSL_METHOD {} +pub enum X509_CRL {} +pub enum X509_EXTENSION {} +pub enum X509_NAME {} +pub enum X509_NAME_ENTRY {} +pub enum X509_REQ {} +pub enum X509_STORE_CTX {} +pub enum bio_st {} +pub enum PKCS12 {} +pub enum DH_METHOD {} pub type bio_info_cb = Option; +pub enum RSA_METHOD {} +pub enum BN_MONT_CTX {} +pub enum BN_BLINDING {} +pub enum DSA_METHOD {} +pub enum EVP_PKEY_ASN1_METHOD {} + #[repr(C)] -#[derive(Copy, Clone)] -pub struct BIO_METHOD { +pub struct GENERAL_NAME { pub type_: c_int, - pub name: *const c_char, - pub bwrite: Option c_int>, - pub bread: Option c_int>, - pub bputs: Option c_int>, - pub bgets: Option c_int>, - pub ctrl: Option c_long>, - pub create: Option c_int>, - pub destroy: Option c_int>, - pub callback_ctrl: Option c_long>, -} - -// so we can create static BIO_METHODs -unsafe impl Sync for BIO_METHOD {} - -#[repr(C)] -pub struct _STACK { - pub num: c_int, - pub data: *mut *mut c_char, - pub sorted: c_int, - pub num_alloc: c_int, - pub comp: Option, -} - -#[repr(C)] -pub struct RSA { - pub pad: c_int, - pub version: c_long, - pub meth: *const c_void, - - pub engine: *mut c_void, - pub n: *mut BIGNUM, - pub e: *mut BIGNUM, - pub d: *mut BIGNUM, - pub p: *mut BIGNUM, - pub q: *mut BIGNUM, - pub dmp1: *mut BIGNUM, - pub dmq1: *mut BIGNUM, - pub iqmp: *mut BIGNUM, - - pub ex_data: *mut c_void, - pub references: c_int, - pub flags: c_int, - - pub _method_mod_n: *mut c_void, - pub _method_mod_p: *mut c_void, - pub _method_mod_q: *mut c_void, - - pub bignum_data: *mut c_char, - pub blinding: *mut c_void, - pub mt_blinding: *mut c_void, -} - -#[repr(C)] -pub struct DSA { - pub pad: c_int, - pub version: c_long, - pub write_params: c_int, - - pub p: *mut BIGNUM, - pub q: *mut BIGNUM, - pub g: *mut BIGNUM, - pub pub_key: *mut BIGNUM, - pub priv_key: *mut BIGNUM, - pub kinv: *mut BIGNUM, - pub r: *mut BIGNUM, - - pub flags: c_int, - pub _method_mont_p: *mut c_void, - pub references: c_int, - pub ex_data: *mut c_void, - pub meth: *const c_void, - pub engine: *const c_void, -} - -#[repr(C)] -pub struct EVP_PKEY { - pub type_: c_int, - pub save_type: c_int, - pub references: c_int, - pub ameth: *const c_void, - pub engine: *mut ENGINE, - pub pkey: *mut c_void, - pub save_parameters: c_int, - pub attributes: *mut c_void, -} - -#[repr(C)] -pub struct BIO { - pub method: *mut BIO_METHOD, - pub callback: Option c_long>, - pub cb_arg: *mut c_char, - pub init: c_int, - pub shutdown: c_int, - pub flags: c_int, - pub retry_reason: c_int, - pub num: c_int, - pub ptr: *mut c_void, - pub next_bio: *mut BIO, - pub prev_bio: *mut BIO, - pub references: c_int, - pub num_read: c_ulong, - pub num_write: c_ulong, - pub ex_data: CRYPTO_EX_DATA, -} - -#[repr(C)] -pub struct CRYPTO_EX_DATA { - pub sk: *mut stack_st_void, - pub dummy: c_int, -} - -#[repr(C)] -pub struct EVP_MD_CTX { - digest: *mut EVP_MD, - engine: *mut c_void, - flags: c_ulong, - md_data: *mut c_void, - pctx: *mut EVP_PKEY_CTX, - update: *mut c_void -} - -impl Copy for EVP_MD_CTX {} -impl Clone for EVP_MD_CTX { - fn clone(&self) -> EVP_MD_CTX { *self } -} - -#[repr(C)] -pub struct EVP_CIPHER { - pub nid: c_int, - pub block_size: c_int, - pub key_len: c_int, - pub iv_len: c_int, - pub flags: c_ulong, - pub init: Option c_int>, - pub do_cipher: Option c_int>, - pub cleanup: Option c_int>, - pub ctx_size: c_int, - pub set_asn1_parameters: Option c_int>, - pub get_asn1_parameters: Option c_int>, - pub ctrl: Option c_int>, - pub app_data: *mut c_void, -} - -impl Copy for EVP_CIPHER {} -impl Clone for EVP_CIPHER { - fn clone(&self) -> EVP_CIPHER { *self } -} - -#[repr(C)] -pub struct HMAC_CTX { - md: *mut EVP_MD, - md_ctx: EVP_MD_CTX, - i_ctx: EVP_MD_CTX, - o_ctx: EVP_MD_CTX, - key_length: c_uint, - key: [c_uchar; 128] -} - -impl Copy for HMAC_CTX {} -impl Clone for HMAC_CTX { - fn clone(&self) -> HMAC_CTX { *self } + pub d: *mut c_void, } #[repr(C)] @@ -264,35 +73,10 @@ pub struct X509V3_CTX { // Maybe more here } -#[repr(C)] -pub struct GENERAL_NAME { - pub type_: c_int, - pub d: *mut c_void, -} - -impl Copy for GENERAL_NAME {} -impl Clone for GENERAL_NAME { - fn clone(&self) -> GENERAL_NAME { *self } -} - -impl Copy for X509V3_CTX {} -impl Clone for X509V3_CTX { - fn clone(&self) -> X509V3_CTX { *self } -} - -#[repr(C)] -pub struct BIGNUM { - pub d: *mut c_void, - pub top: c_int, - pub dmax: c_int, - pub neg: c_int, - pub flags: c_int, -} - -impl Copy for BIGNUM {} -impl Clone for BIGNUM { - fn clone(&self) -> BIGNUM { *self } -} +#[cfg(target_pointer_width = "64")] +pub type BN_ULONG = libc::c_ulonglong; +#[cfg(target_pointer_width = "32")] +pub type BN_ULONG = c_uint; pub type CRYPTO_EX_new = extern "C" fn(parent: *mut c_void, ptr: *mut c_void, ad: *const CRYPTO_EX_DATA, idx: c_int, @@ -348,15 +132,11 @@ pub const RSA_X931_PADDING: c_int = 5; pub const SSL_CTRL_SET_TMP_DH: c_int = 3; pub const SSL_CTRL_EXTRA_CHAIN_CERT: c_int = 14; -pub const SSL_CTRL_OPTIONS: c_int = 32; pub const SSL_CTRL_MODE: c_int = 33; pub const SSL_CTRL_SET_READ_AHEAD: c_int = 41; pub const SSL_CTRL_SET_TLSEXT_SERVERNAME_CB: c_int = 53; pub const SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG: c_int = 54; pub const SSL_CTRL_SET_TLSEXT_HOSTNAME: c_int = 55; -pub const SSL_CTRL_CLEAR_OPTIONS: c_int = 77; -#[cfg(feature = "ecdh_auto")] -pub const SSL_CTRL_SET_ECDH_AUTO: c_int = 94; pub const SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER: c_long = 2; pub const SSL_MODE_AUTO_RETRY: c_long = 4; @@ -374,30 +154,21 @@ pub const SSL_VERIFY_NONE: c_int = 0; pub const SSL_VERIFY_PEER: c_int = 1; pub const SSL_VERIFY_FAIL_IF_NO_PEER_CERT: c_int = 2; -pub const SSL_OP_MICROSOFT_SESS_ID_BUG: c_long = 0x00000001; -pub const SSL_OP_NETSCAPE_CHALLENGE_BUG: c_long = 0x00000002; -pub const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: c_long = 0x00000008; -pub const SSL_OP_TLSEXT_PADDING: c_long = 0x00000010; -pub const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: c_long = 0x00000020; -pub const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: c_long = 0x00000080; -pub const SSL_OP_TLS_D5_BUG: c_long = 0x00000100; -pub const SSL_OP_TLS_BLOCK_PADDING_BUG: c_long = 0x00000200; -pub const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: c_long = 0x00000800; -pub const SSL_OP_ALL: c_long = 0x80000BFF; -pub const SSL_OP_NO_QUERY_MTU: c_long = 0x00001000; -pub const SSL_OP_COOKIE_EXCHANGE: c_long = 0x00002000; -pub const SSL_OP_NO_TICKET: c_long = 0x00004000; -pub const SSL_OP_CISCO_ANYCONNECT: c_long = 0x00008000; -pub const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: c_long = 0x00010000; -pub const SSL_OP_NO_COMPRESSION: c_long = 0x00020000; -pub const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: c_long = 0x00040000; -pub const SSL_OP_SINGLE_ECDH_USE: c_long = 0x00080000; -pub const SSL_OP_SINGLE_DH_USE: c_long = 0x00100000; -pub const SSL_OP_CIPHER_SERVER_PREFERENCE: c_long = 0x00400000; -pub const SSL_OP_TLS_ROLLBACK_BUG: c_long = 0x00800000; -pub const SSL_OP_NO_SSLv2: c_long = 0x01000000; -pub const SSL_OP_NO_SSLv3: c_long = 0x02000000; -pub const SSL_OP_NO_TLSv1: c_long = 0x04000000; +#[cfg(not(ossl101))] +pub const SSL_OP_TLSEXT_PADDING: c_ulong = 0x00000010; +pub const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: c_ulong = 0x00000800; +pub const SSL_OP_ALL: c_ulong = 0x80000BFF; +pub const SSL_OP_NO_QUERY_MTU: c_ulong = 0x00001000; +pub const SSL_OP_COOKIE_EXCHANGE: c_ulong = 0x00002000; +pub const SSL_OP_NO_TICKET: c_ulong = 0x00004000; +pub const SSL_OP_CISCO_ANYCONNECT: c_ulong = 0x00008000; +pub const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: c_ulong = 0x00010000; +pub const SSL_OP_NO_COMPRESSION: c_ulong = 0x00020000; +pub const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: c_ulong = 0x00040000; +pub const SSL_OP_CIPHER_SERVER_PREFERENCE: c_ulong = 0x00400000; +pub const SSL_OP_TLS_ROLLBACK_BUG: c_ulong = 0x00800000; +pub const SSL_OP_NO_SSLv3: c_ulong = 0x02000000; +pub const SSL_OP_NO_TLSv1: c_ulong = 0x04000000; // Intentionally not bound since they conflict with SSL_OP_PKCS1_CHECK_1 and // SSL_OP_PKCS1_CHECK_2 on 0.9.8 :( @@ -410,24 +181,15 @@ pub const SSL_OP_NO_SSL_MASK: c_long = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2; */ -pub const TLSEXT_NAMETYPE_host_name: c_long = 0; +pub const TLSEXT_NAMETYPE_host_name: c_int = 0; pub const SSL_TLSEXT_ERR_OK: c_int = 0; pub const SSL_TLSEXT_ERR_ALERT_WARNING: c_int = 1; pub const SSL_TLSEXT_ERR_ALERT_FATAL: c_int = 2; pub const SSL_TLSEXT_ERR_NOACK: c_int = 3; -pub const SSLEAY_VERSION : c_int = 0; -pub const SSLEAY_CFLAGS : c_int = 2; -pub const SSLEAY_BUILT_ON : c_int = 3; -pub const SSLEAY_PLATFORM : c_int = 4; -pub const SSLEAY_DIR : c_int = 5; - -#[cfg(any(feature = "npn", feature = "alpn"))] pub const OPENSSL_NPN_UNSUPPORTED: c_int = 0; -#[cfg(any(feature = "npn", feature = "alpn"))] pub const OPENSSL_NPN_NEGOTIATED: c_int = 1; -#[cfg(any(feature = "npn", feature = "alpn"))] pub const OPENSSL_NPN_NO_OVERLAP: c_int = 2; pub const V_ASN1_GENERALIZEDTIME: c_int = 24; @@ -501,59 +263,6 @@ pub const GEN_URI: c_int = 6; pub const GEN_IPADD: c_int = 7; pub const GEN_RID: c_int = 8; -static mut MUTEXES: *mut Vec> = 0 as *mut Vec>; -static mut GUARDS: *mut Vec>> = 0 as *mut Vec>>; - -unsafe extern fn locking_function(mode: c_int, n: c_int, _file: *const c_char, - _line: c_int) { - let mutex = &(*MUTEXES)[n as usize]; - - if mode & CRYPTO_LOCK != 0 { - (*GUARDS)[n as usize] = Some(mutex.lock().unwrap()); - } else { - &(*GUARDS)[n as usize].take(); - } -} - -pub fn init() { - static INIT: Once = ONCE_INIT; - - INIT.call_once(|| { - unsafe { - SSL_library_init(); - SSL_load_error_strings(); - OPENSSL_add_all_algorithms_noconf(); - - let num_locks = CRYPTO_num_locks(); - let mut mutexes = Box::new(Vec::new()); - for _ in 0..num_locks { - mutexes.push(Mutex::new(())); - } - MUTEXES = mem::transmute(mutexes); - let guards: Box>>> = - Box::new((0..num_locks).map(|_| None).collect()); - GUARDS = mem::transmute(guards); - - CRYPTO_set_locking_callback(locking_function); - set_id_callback(); - } - }) -} - -#[cfg(unix)] -fn set_id_callback() { - unsafe extern "C" fn thread_id() -> c_ulong { - libc::pthread_self() as c_ulong - } - - unsafe { - CRYPTO_set_id_callback(thread_id); - } -} - -#[cfg(not(unix))] -fn set_id_callback() {} - // macros pub unsafe fn BIO_get_mem_data(b: *mut BIO, pp: *mut *mut c_char) -> c_long { BIO_ctrl(b, BIO_CTRL_INFO, 0, pp as *mut c_void) @@ -575,18 +284,6 @@ pub unsafe fn SSL_CTX_set_mode(ctx: *mut SSL_CTX, op: c_long) -> c_long { SSL_CTX_ctrl(ctx, SSL_CTRL_MODE, op, ptr::null_mut()) } -pub unsafe fn SSL_CTX_set_options(ctx: *mut SSL_CTX, op: c_long) -> c_long { - SSL_CTX_ctrl(ctx, SSL_CTRL_OPTIONS, op, ptr::null_mut()) -} - -pub unsafe fn SSL_CTX_clear_options(ctx: *mut SSL_CTX, op: c_long) -> c_long { - SSL_CTX_ctrl(ctx, SSL_CTRL_CLEAR_OPTIONS, op, ptr::null_mut()) -} - -pub unsafe fn SSL_CTX_get_options(ctx: *mut SSL_CTX) -> c_long { - SSL_CTX_ctrl(ctx, SSL_CTRL_OPTIONS, 0, ptr::null_mut()) -} - pub unsafe fn SSL_CTX_set_read_ahead(ctx: *mut SSL_CTX, m: c_long) -> c_long { SSL_CTX_ctrl(ctx, SSL_CTRL_SET_READ_AHEAD, m, ptr::null_mut()) } @@ -599,11 +296,6 @@ pub unsafe fn SSL_CTX_add_extra_chain_cert(ctx: *mut SSL_CTX, x509: *mut X509) - SSL_CTX_ctrl(ctx, SSL_CTRL_EXTRA_CHAIN_CERT, 0, x509 as *mut c_void) } -#[cfg(feature = "ecdh_auto")] -pub unsafe fn SSL_CTX_set_ecdh_auto(ctx: *mut SSL_CTX, onoff: c_long) -> c_long { - SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, ptr::null_mut()) -} - pub unsafe fn SSL_CTX_set_tlsext_servername_callback(ctx: *mut SSL_CTX, cb: Option) -> c_long { @@ -611,23 +303,12 @@ pub unsafe fn SSL_CTX_set_tlsext_servername_callback(ctx: *mut SSL_CTX, } pub unsafe fn SSL_set_tlsext_host_name(s: *mut SSL, name: *mut c_char) -> c_long { - SSL_ctrl(s, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, name as *mut c_void) + SSL_ctrl(s, SSL_CTRL_SET_TLSEXT_HOSTNAME, + TLSEXT_NAMETYPE_host_name as c_long, + name as *mut c_void) } -pub unsafe fn EVP_CIPHER_block_size(e: *const EVP_CIPHER) -> c_int { - (*e).block_size -} - -pub unsafe fn EVP_CIPHER_key_length(e: *const EVP_CIPHER) -> c_int { - (*e).key_len -} - -pub unsafe fn EVP_CIPHER_iv_length(e: *const EVP_CIPHER) -> c_int { - (*e).iv_len -} - -// True functions -extern "C" { +extern { pub fn ASN1_INTEGER_set(dest: *mut ASN1_INTEGER, value: c_long) -> c_int; pub fn ASN1_STRING_type_new(ty: c_int) -> *mut ASN1_STRING; pub fn ASN1_TIME_free(tm: *mut ASN1_TIME); @@ -635,116 +316,101 @@ extern "C" { 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); - pub fn BIO_new(type_: *const BIO_METHOD) -> *mut BIO; pub fn BIO_new_fp(stream: *mut FILE, close_flag: c_int) -> *mut BIO; pub fn BIO_new_socket(sock: c_int, close_flag: c_int) -> *mut BIO; pub fn BIO_read(b: *mut BIO, buf: *mut c_void, len: c_int) -> c_int; pub fn BIO_write(b: *mut BIO, buf: *const c_void, len: c_int) -> c_int; - pub fn BIO_s_file() -> *const BIO_METHOD; - pub fn BIO_s_mem() -> *const BIO_METHOD; pub fn BIO_new_mem_buf(buf: *const c_void, len: c_int) -> *mut BIO; 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_new() -> *mut BIGNUM; - pub fn BN_dup(n: *mut BIGNUM) -> *mut BIGNUM; + pub fn BN_dup(n: *const BIGNUM) -> *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: *mut BIGNUM) -> c_int; + 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: c_ulong) -> 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: *mut BIGNUM, b: *mut BIGNUM) -> c_int; - pub fn BN_div(dv: *mut BIGNUM, rem: *mut BIGNUM, a: *mut BIGNUM, b: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; - pub fn BN_exp(r: *mut BIGNUM, a: *mut BIGNUM, p: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; - pub fn BN_gcd(r: *mut BIGNUM, a: *mut BIGNUM, b: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; - pub fn BN_mod_add(r: *mut BIGNUM, a: *mut BIGNUM, b: *mut BIGNUM, m: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; - pub fn BN_mod_exp(r: *mut BIGNUM, a: *mut BIGNUM, p: *mut BIGNUM, m: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; - pub fn BN_mod_inverse(r: *mut BIGNUM, a: *mut BIGNUM, n: *mut BIGNUM, ctx: *mut BN_CTX) -> *const BIGNUM; - pub fn BN_mod_mul(r: *mut BIGNUM, a: *mut BIGNUM, b: *mut BIGNUM, m: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; - pub fn BN_mod_sqr(r: *mut BIGNUM, a: *mut BIGNUM, m: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; - pub fn BN_mod_sub(r: *mut BIGNUM, a: *mut BIGNUM, b: *mut BIGNUM, m: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; - pub fn BN_mul(r: *mut BIGNUM, a: *mut BIGNUM, b: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; - pub fn BN_nnmod(rem: *mut BIGNUM, a: *mut BIGNUM, m: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; - pub fn BN_add_word(r: *mut BIGNUM, w: c_ulong) -> c_int; - pub fn BN_sub_word(r: *mut BIGNUM, w: c_ulong) -> c_int; - pub fn BN_mul_word(r: *mut BIGNUM, w: c_ulong) -> c_int; - pub fn BN_div_word(r: *mut BIGNUM, w: c_ulong) -> c_ulong; - pub fn BN_mod_word(r: *const BIGNUM, w: c_ulong) -> c_ulong; - pub fn BN_sqr(r: *mut BIGNUM, a: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; - pub fn BN_sub(r: *mut BIGNUM, a: *mut BIGNUM, b: *mut BIGNUM) -> c_int; + 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; + pub fn BN_gcd(r: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; + pub fn BN_mod_add(r: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM, m: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; + pub fn BN_mod_exp(r: *mut BIGNUM, a: *const BIGNUM, p: *const BIGNUM, m: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; + pub fn BN_mod_inverse(r: *mut BIGNUM, a: *const BIGNUM, n: *const BIGNUM, ctx: *mut BN_CTX) -> *mut BIGNUM; + pub fn BN_mod_mul(r: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM, m: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; + pub fn BN_mod_sqr(r: *mut BIGNUM, a: *const BIGNUM, m: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; + pub fn BN_mod_sub(r: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM, m: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; + pub fn BN_mul(r: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; + pub fn BN_nnmod(rem: *mut BIGNUM, a: *const BIGNUM, m: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; + pub fn BN_add_word(r: *mut BIGNUM, w: BN_ULONG) -> c_int; + pub fn BN_sub_word(r: *mut BIGNUM, w: BN_ULONG) -> c_int; + pub fn BN_mul_word(r: *mut BIGNUM, w: BN_ULONG) -> c_int; + pub fn BN_div_word(r: *mut BIGNUM, w: BN_ULONG) -> BN_ULONG; + 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: *mut BIGNUM, n: c_int) -> c_int; - pub fn BN_lshift(r: *mut BIGNUM, a: *mut BIGNUM, n: c_int) -> c_int; - pub fn BN_lshift1(r: *mut BIGNUM, a: *mut BIGNUM) -> 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; + pub fn BN_lshift1(r: *mut BIGNUM, a: *const BIGNUM) -> c_int; pub fn BN_mask_bits(a: *mut BIGNUM, n: c_int) -> c_int; - pub fn BN_rshift(r: *mut BIGNUM, a: *mut BIGNUM, n: c_int) -> c_int; + 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: *mut BIGNUM) -> c_int; + pub fn BN_rshift1(r: *mut BIGNUM, a: *const BIGNUM) -> c_int; /* Comparisons on BIGNUMs */ - pub fn BN_cmp(a: *mut BIGNUM, b: *mut BIGNUM) -> c_int; - pub fn BN_ucmp(a: *mut BIGNUM, b: *mut BIGNUM) -> c_int; + 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: *mut BIGNUM, rem: *mut BIGNUM, cb: *const c_void) -> c_int; - pub fn BN_is_prime_ex(p: *mut BIGNUM, checks: c_int, ctx: *mut BN_CTX, cb: *const c_void) -> c_int; - pub fn BN_is_prime_fasttest_ex(p: *mut BIGNUM, checks: c_int, ctx: *mut BN_CTX, do_trial_division: c_int, cb: *const c_void) -> c_int; + 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: *mut BIGNUM) -> c_int; - pub fn BN_pseudo_rand_range(r: *mut BIGNUM, range: *mut BIGNUM) -> 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: *mut BIGNUM, to: *mut u8) -> c_int; + pub fn BN_bn2bin(a: *const BIGNUM, to: *mut u8) -> c_int; /* Conversion from/to decimal string representation */ - pub fn BN_dec2bn(a: *const *mut BIGNUM, s: *const c_char) -> c_int; - pub fn BN_bn2dec(a: *mut BIGNUM) -> *const c_char; + 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: *const *mut BIGNUM, s: *const c_char) -> c_int; - pub fn BN_bn2hex(a: *mut BIGNUM) -> *const c_char; + 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 CRYPTO_num_locks() -> c_int; - pub fn CRYPTO_set_locking_callback(func: unsafe extern "C" fn(mode: c_int, - n: c_int, - file: *const c_char, - line: c_int)); - pub fn CRYPTO_set_id_callback(func: unsafe extern "C" fn() -> c_ulong); - pub fn CRYPTO_free(buf: *mut c_void); pub fn CRYPTO_memcmp(a: *const c_void, b: *const c_void, len: size_t) -> c_int; pub fn DH_free(dh: *mut DH); - #[cfg(feature = "rfc5114")] + #[cfg(not(ossl101))] pub fn DH_get_1024_160() -> *mut DH; - #[cfg(feature = "rfc5114")] + #[cfg(not(ossl101))] pub fn DH_get_2048_224() -> *mut DH; - #[cfg(feature = "rfc5114")] + #[cfg(not(ossl101))] pub fn DH_get_2048_256() -> *mut DH; - // FIXME delete on next version bump - pub fn DH_new_from_params(p: *mut BIGNUM, g: *mut BIGNUM, q: *mut BIGNUM) -> *mut DH; - pub fn ERR_get_error() -> c_ulong; pub fn ERR_lib_error_string(err: c_ulong) -> *const c_char; pub fn ERR_func_error_string(err: c_ulong) -> *const c_char; pub fn ERR_reason_error_string(err: c_ulong) -> *const c_char; - pub fn ERR_load_crypto_strings(); - pub fn EVP_md5() -> *const EVP_MD; pub fn EVP_ripemd160() -> *const EVP_MD; pub fn EVP_sha1() -> *const EVP_MD; @@ -755,9 +421,7 @@ extern "C" { pub fn EVP_aes_128_cbc() -> *const EVP_CIPHER; pub fn EVP_aes_128_ecb() -> *const EVP_CIPHER; - #[cfg(feature = "aes_xts")] pub fn EVP_aes_128_xts() -> *const EVP_CIPHER; - #[cfg(feature = "aes_ctr")] pub fn EVP_aes_128_ctr() -> *const EVP_CIPHER; // fn EVP_aes_128_gcm() -> EVP_CIPHER; pub fn EVP_aes_128_cfb1() -> *const EVP_CIPHER; @@ -765,9 +429,7 @@ extern "C" { pub fn EVP_aes_128_cfb8() -> *const EVP_CIPHER; pub fn EVP_aes_256_cbc() -> *const EVP_CIPHER; pub fn EVP_aes_256_ecb() -> *const EVP_CIPHER; - #[cfg(feature = "aes_xts")] pub fn EVP_aes_256_xts() -> *const EVP_CIPHER; - #[cfg(feature = "aes_ctr")] pub fn EVP_aes_256_ctr() -> *const EVP_CIPHER; // fn EVP_aes_256_gcm() -> EVP_CIPHER; pub fn EVP_aes_256_cfb1() -> *const EVP_CIPHER; @@ -792,35 +454,34 @@ extern "C" { pub fn EVP_CipherInit_ex(ctx: *mut EVP_CIPHER_CTX, type_: *const EVP_CIPHER, impl_: *mut ENGINE, - key: *mut c_uchar, - iv: *mut c_uchar, + key: *const c_uchar, + iv: *const c_uchar, enc: c_int) -> c_int; pub fn EVP_CipherUpdate(ctx: *mut EVP_CIPHER_CTX, outbuf: *mut u8, - outlen: &mut c_int, inbuf: *const u8, inlen: c_int) -> c_int; - pub fn EVP_CipherFinal(ctx: *mut EVP_CIPHER_CTX, res: *mut u8, len: &mut c_int) -> c_int; + outlen: *mut c_int, inbuf: *const u8, inlen: c_int) -> c_int; + pub fn EVP_CipherFinal(ctx: *mut EVP_CIPHER_CTX, res: *mut u8, len: *mut c_int) -> c_int; pub fn EVP_DigestInit(ctx: *mut EVP_MD_CTX, typ: *const EVP_MD) -> c_int; - pub fn EVP_DigestInit_ex(ctx: *mut EVP_MD_CTX, typ: *const EVP_MD, imple: *const ENGINE) -> c_int; - pub fn EVP_DigestUpdate(ctx: *mut EVP_MD_CTX, data: *const u8, n: c_uint) -> c_int; + pub fn EVP_DigestInit_ex(ctx: *mut EVP_MD_CTX, typ: *const EVP_MD, imple: *mut ENGINE) -> c_int; + pub fn EVP_DigestUpdate(ctx: *mut EVP_MD_CTX, data: *const c_void, n: size_t) -> c_int; pub fn EVP_DigestFinal(ctx: *mut EVP_MD_CTX, res: *mut u8, n: *mut u32) -> c_int; pub fn EVP_DigestFinal_ex(ctx: *mut EVP_MD_CTX, res: *mut u8, n: *mut u32) -> c_int; - pub fn EVP_MD_CTX_create() -> *mut EVP_MD_CTX; + #[cfg_attr(any(ossl101, ossl102), link_name = "EVP_MD_CTX_create")] + pub fn EVP_MD_CTX_new() -> *mut EVP_MD_CTX; pub fn EVP_MD_CTX_copy_ex(dst: *mut EVP_MD_CTX, src: *const EVP_MD_CTX) -> c_int; - pub fn EVP_MD_CTX_destroy(ctx: *mut EVP_MD_CTX); + #[cfg_attr(any(ossl101, ossl102), link_name = "EVP_MD_CTX_destroy")] + pub fn EVP_MD_CTX_free(ctx: *mut EVP_MD_CTX); pub fn EVP_PKEY_new() -> *mut EVP_PKEY; pub fn EVP_PKEY_free(k: *mut EVP_PKEY); - pub fn EVP_PKEY_assign(pkey: *mut EVP_PKEY, typ: c_int, key: *const c_void) -> c_int; + pub fn EVP_PKEY_assign(pkey: *mut EVP_PKEY, typ: c_int, key: *mut c_void) -> c_int; pub fn EVP_PKEY_copy_parameters(to: *mut EVP_PKEY, from: *const EVP_PKEY) -> c_int; pub fn EVP_PKEY_get1_RSA(k: *mut EVP_PKEY) -> *mut RSA; pub fn EVP_PKEY_set1_RSA(k: *mut EVP_PKEY, r: *mut RSA) -> c_int; pub fn EVP_PKEY_cmp(a: *const EVP_PKEY, b: *const EVP_PKEY) -> c_int; - pub fn HMAC_CTX_init(ctx: *mut HMAC_CTX); - pub fn HMAC_CTX_cleanup(ctx: *mut HMAC_CTX); - #[cfg(feature = "hmac_clone")] - pub fn HMAC_CTX_copy(dst: *mut HMAC_CTX, src: *const HMAC_CTX) -> c_int; + pub fn HMAC_CTX_copy(dst: *mut HMAC_CTX, src: *mut HMAC_CTX) -> c_int; pub fn PEM_read_bio_DHparams(bio: *mut BIO, out: *mut *mut DH, callback: Option, user_data: *mut c_void) -> *mut DH; @@ -845,7 +506,7 @@ extern "C" { kstr: *mut c_uchar, klen: c_int, callback: Option, user_data: *mut c_void) -> c_int; - pub fn PEM_write_bio_RSAPublicKey(bp: *mut BIO, rsa: *mut RSA) -> c_int; + pub fn PEM_write_bio_RSAPublicKey(bp: *mut BIO, rsa: *const RSA) -> c_int; pub fn PEM_write_bio_RSA_PUBKEY(bp: *mut BIO, rsa: *mut RSA) -> c_int; pub fn PEM_read_bio_DSAPrivateKey(bp: *mut BIO, dsa: *mut *mut DSA, callback: Option, @@ -862,13 +523,12 @@ extern "C" { pub fn PEM_write_bio_X509(bio: *mut BIO, x509: *mut X509) -> c_int; pub fn PEM_write_bio_X509_REQ(bio: *mut BIO, x509: *mut X509_REQ) -> c_int; - pub fn PKCS5_PBKDF2_HMAC_SHA1(pass: *const u8, passlen: c_int, + pub fn PKCS5_PBKDF2_HMAC_SHA1(pass: *const c_char, passlen: c_int, salt: *const u8, saltlen: c_int, iter: c_int, keylen: c_int, out: *mut u8) -> c_int; - #[cfg(feature = "pkcs5_pbkdf2_hmac")] - pub fn PKCS5_PBKDF2_HMAC(pass: *const u8, passlen: c_int, - salt: *const u8, saltlen: c_int, + pub fn PKCS5_PBKDF2_HMAC(pass: *const c_char, passlen: c_int, + salt: *const c_uchar, saltlen: c_int, iter: c_int, digest: *const EVP_MD, keylen: c_int, out: *mut u8) -> c_int; @@ -877,7 +537,6 @@ extern "C" { pub fn RSA_new() -> *mut RSA; pub fn RSA_free(rsa: *mut RSA); - pub fn RSA_generate_key(modsz: c_int, e: c_ulong, cb: *const c_void, cbarg: *const c_void) -> *mut RSA; pub fn RSA_generate_key_ex(rsa: *mut RSA, bits: c_int, e: *mut BIGNUM, cb: *mut BN_GENCB) -> c_int; pub fn RSA_private_decrypt(flen: c_int, from: *const u8, to: *mut u8, k: *mut RSA, pad: c_int) -> c_int; @@ -889,7 +548,7 @@ extern "C" { pad: c_int) -> c_int; pub fn RSA_sign(t: c_int, m: *const u8, mlen: c_uint, sig: *mut u8, siglen: *mut c_uint, k: *mut RSA) -> c_int; - pub fn RSA_size(k: *mut RSA) -> c_int; + pub fn RSA_size(k: *const RSA) -> c_int; pub fn RSA_verify(t: c_int, m: *const u8, mlen: c_uint, sig: *const u8, siglen: c_uint, k: *mut RSA) -> c_int; @@ -898,75 +557,51 @@ extern "C" { pub fn DSA_size(dsa: *const DSA) -> c_int; pub fn DSA_generate_parameters_ex(dsa: *mut DSA, bits: c_int, seed: *const c_uchar, seed_len: c_int, counter_ref: *mut c_int, h_ret: *mut c_ulong, - cb: *const c_void) -> c_int; + cb: *mut BN_GENCB) -> c_int; pub fn DSA_generate_key(dsa: *mut DSA) -> c_int; pub fn DSA_sign(dummy: c_int, dgst: *const c_uchar, len: c_int, sigret: *mut c_uchar, siglen: *mut c_uint, dsa: *mut DSA) -> c_int; pub fn DSA_verify(dummy: c_int, dgst: *const c_uchar, len: c_int, sigbuf: *const c_uchar, siglen: c_int, dsa: *mut DSA) -> c_int; - pub fn SSL_library_init() -> c_int; - pub fn SSL_load_error_strings(); - pub fn OPENSSL_add_all_algorithms_noconf(); - - #[cfg(feature = "sslv2")] - pub fn SSLv2_method() -> *const SSL_METHOD; - pub fn SSLv3_method() -> *const SSL_METHOD; - pub fn TLSv1_method() -> *const SSL_METHOD; - #[cfg(feature = "tlsv1_1")] - pub fn TLSv1_1_method() -> *const SSL_METHOD; - #[cfg(feature = "tlsv1_2")] - pub fn TLSv1_2_method() -> *const SSL_METHOD; - #[cfg(feature = "dtlsv1")] - pub fn DTLSv1_method() -> *const SSL_METHOD; - #[cfg(feature = "dtlsv1_2")] - pub fn DTLSv1_2_method() -> *const SSL_METHOD; - pub fn SSLv23_method() -> *const SSL_METHOD; - pub fn SSL_new(ctx: *mut SSL_CTX) -> *mut SSL; pub fn SSL_pending(ssl: *const SSL) -> c_int; pub fn SSL_free(ssl: *mut SSL); pub fn SSL_set_bio(ssl: *mut SSL, rbio: *mut BIO, wbio: *mut BIO); - pub fn SSL_get_rbio(ssl: *mut SSL) -> *mut BIO; - pub fn SSL_get_wbio(ssl: *mut SSL) -> *mut BIO; + pub fn SSL_get_rbio(ssl: *const SSL) -> *mut BIO; + pub fn SSL_get_wbio(ssl: *const SSL) -> *mut BIO; pub fn SSL_accept(ssl: *mut SSL) -> c_int; pub fn SSL_connect(ssl: *mut SSL) -> c_int; pub fn SSL_do_handshake(ssl: *mut SSL) -> c_int; pub fn SSL_ctrl(ssl: *mut SSL, cmd: c_int, larg: c_long, parg: *mut c_void) -> c_long; - pub fn SSL_get_error(ssl: *mut SSL, ret: c_int) -> c_int; + pub fn SSL_get_error(ssl: *const SSL, ret: c_int) -> c_int; pub fn SSL_read(ssl: *mut SSL, buf: *mut c_void, num: c_int) -> c_int; pub fn SSL_write(ssl: *mut SSL, buf: *const c_void, num: c_int) -> c_int; pub fn SSL_get_ex_data_X509_STORE_CTX_idx() -> c_int; - pub fn SSL_get_SSL_CTX(ssl: *mut SSL) -> *mut SSL_CTX; + pub fn SSL_get_SSL_CTX(ssl: *const SSL) -> *mut SSL_CTX; pub fn SSL_set_SSL_CTX(ssl: *mut SSL, ctx: *mut SSL_CTX) -> *mut SSL_CTX; pub fn SSL_get_current_compression(ssl: *mut SSL) -> *const COMP_METHOD; - pub fn SSL_get_peer_certificate(ssl: *mut SSL) -> *mut X509; + pub fn SSL_get_peer_certificate(ssl: *const SSL) -> *mut X509; pub fn SSL_get_ssl_method(ssl: *mut SSL) -> *const SSL_METHOD; - pub fn SSL_get_version(ssl: *mut SSL) -> *const c_char; - pub fn SSL_state_string(ssl: *mut SSL) -> *const c_char; - pub fn SSL_state_string_long(ssl: *mut SSL) -> *const c_char; + pub fn SSL_get_version(ssl: *const SSL) -> *const c_char; + pub fn SSL_state_string(ssl: *const SSL) -> *const c_char; + pub fn SSL_state_string_long(ssl: *const SSL) -> *const c_char; pub fn SSL_set_verify(ssl: *mut SSL, mode: c_int, verify_callback: Option c_int>); - pub fn SSL_get_ex_new_index(argl: c_long, argp: *const c_void, - new_func: Option, - dup_func: Option, - free_func: Option) - -> c_int; pub fn SSL_set_ex_data(ssl: *mut SSL, idx: c_int, data: *mut c_void) -> c_int; - pub fn SSL_get_ex_data(ssl: *mut SSL, idx: c_int) -> *mut c_void; + pub fn SSL_get_ex_data(ssl: *const SSL, idx: c_int) -> *mut c_void; - pub fn SSL_get_servername(ssl: *const SSL, name_type: c_long) -> *const c_char; + pub fn SSL_get_servername(ssl: *const SSL, name_type: c_int) -> *const c_char; pub fn SSL_COMP_get_name(comp: *const COMP_METHOD) -> *const c_char; pub fn SSL_get_current_cipher(ssl: *const SSL) -> *const SSL_CIPHER; pub fn SSL_CIPHER_get_name(cipher: *const SSL_CIPHER) -> *const c_char; - pub fn SSL_CIPHER_get_bits(cipher: *const SSL_CIPHER, alg_bits: *const c_int) -> c_int; - pub fn SSL_CIPHER_get_version(cipher: *const SSL_CIPHER) -> *const c_char; - pub fn SSL_CIPHER_description(cipher: *const SSL_CIPHER, buf: *mut c_char, size: c_int) -> *const c_char; + pub fn SSL_CIPHER_get_bits(cipher: *const SSL_CIPHER, alg_bits: *mut c_int) -> c_int; + pub fn SSL_CIPHER_description(cipher: *const SSL_CIPHER, buf: *mut c_char, size: c_int) -> *mut c_char; pub fn SSL_CTX_new(method: *const SSL_METHOD) -> *mut SSL_CTX; pub fn SSL_CTX_free(ctx: *mut SSL_CTX); @@ -978,34 +613,27 @@ extern "C" { pub fn SSL_CTX_load_verify_locations(ctx: *mut SSL_CTX, CAfile: *const c_char, CApath: *const c_char) -> c_int; pub fn SSL_CTX_set_default_verify_paths(ctx: *mut SSL_CTX) -> c_int; - pub fn SSL_CTX_get_ex_new_index(argl: c_long, argp: *const c_void, - new_func: Option, - dup_func: Option, - free_func: Option) - -> c_int; pub fn SSL_CTX_set_ex_data(ctx: *mut SSL_CTX, idx: c_int, data: *mut c_void) -> c_int; - pub fn SSL_CTX_get_ex_data(ctx: *mut SSL_CTX, idx: c_int) -> *mut c_void; + pub fn SSL_CTX_get_ex_data(ctx: *const SSL_CTX, idx: c_int) -> *mut c_void; pub fn SSL_CTX_set_session_id_context(ssl: *mut SSL_CTX, sid_ctx: *const c_uchar, sid_ctx_len: c_uint) -> c_int; pub fn SSL_CTX_use_certificate_file(ctx: *mut SSL_CTX, cert_file: *const c_char, file_type: c_int) -> c_int; - pub fn SSL_CTX_use_certificate_chain_file(ctx: *mut SSL_CTX, cert_chain_file: *const c_char, file_type: c_int) -> c_int; + pub fn SSL_CTX_use_certificate_chain_file(ctx: *mut SSL_CTX, cert_chain_file: *const c_char) -> c_int; pub fn SSL_CTX_use_certificate(ctx: *mut SSL_CTX, cert: *mut X509) -> c_int; pub fn SSL_CTX_use_PrivateKey_file(ctx: *mut SSL_CTX, key_file: *const c_char, file_type: c_int) -> c_int; pub fn SSL_CTX_use_PrivateKey(ctx: *mut SSL_CTX, key: *mut EVP_PKEY) -> c_int; - pub fn SSL_CTX_check_private_key(ctx: *mut SSL_CTX) -> c_int; + pub fn SSL_CTX_check_private_key(ctx: *const SSL_CTX) -> c_int; pub fn SSL_CTX_set_cipher_list(ssl: *mut SSL_CTX, s: *const c_char) -> c_int; - #[cfg(feature = "npn")] pub fn SSL_CTX_set_next_protos_advertised_cb(ssl: *mut SSL_CTX, cb: extern "C" fn(ssl: *mut SSL, out: *mut *const c_uchar, outlen: *mut c_uint, arg: *mut c_void) -> c_int, arg: *mut c_void); - #[cfg(feature = "npn")] pub fn SSL_CTX_set_next_proto_select_cb(ssl: *mut SSL_CTX, cb: extern "C" fn(ssl: *mut SSL, out: *mut *mut c_uchar, @@ -1014,59 +642,49 @@ extern "C" { inlen: c_uint, arg: *mut c_void) -> c_int, arg: *mut c_void); - #[cfg(any(feature = "alpn", feature = "npn"))] pub fn SSL_select_next_proto(out: *mut *mut c_uchar, outlen: *mut c_uchar, inbuf: *const c_uchar, inlen: c_uint, client: *const c_uchar, client_len: c_uint) -> c_int; - #[cfg(feature = "npn")] pub fn SSL_get0_next_proto_negotiated(s: *const SSL, data: *mut *const c_uchar, len: *mut c_uint); - #[cfg(feature = "alpn")] + #[cfg(not(ossl101))] pub fn SSL_CTX_set_alpn_protos(s: *mut SSL_CTX, data: *const c_uchar, len: c_uint) -> c_int; - #[cfg(feature = "alpn")] + #[cfg(not(ossl101))] pub fn SSL_set_alpn_protos(s: *mut SSL, data: *const c_uchar, len: c_uint) -> c_int; - #[cfg(feature = "alpn")] + #[cfg(not(ossl101))] pub fn SSL_CTX_set_alpn_select_cb(ssl: *mut SSL_CTX, - cb: extern "C" fn(ssl: *mut SSL, - out: *mut *mut c_uchar, - outlen: *mut c_uchar, - inbuf: *const c_uchar, - inlen: c_uint, - arg: *mut c_void) -> c_int, - arg: *mut c_void); - #[cfg(feature = "alpn")] + cb: extern fn(ssl: *mut SSL, + out: *mut *const c_uchar, + outlen: *mut c_uchar, + inbuf: *const c_uchar, + inlen: c_uint, + arg: *mut c_void) -> c_int, + arg: *mut c_void); + #[cfg(not(ossl101))] pub fn SSL_get0_alpn_selected(s: *const SSL, data: *mut *const c_uchar, len: *mut c_uint); pub fn X509_add_ext(x: *mut X509, ext: *mut X509_EXTENSION, loc: c_int) -> c_int; - pub fn X509_digest(x: *mut X509, digest: *const EVP_MD, buf: *mut c_char, len: *mut c_uint) -> c_int; + pub fn X509_digest(x: *const X509, digest: *const EVP_MD, buf: *mut c_uchar, len: *mut c_uint) -> c_int; pub fn X509_free(x: *mut X509); pub fn X509_REQ_free(x: *mut X509_REQ); pub fn X509_get_serialNumber(x: *mut X509) -> *mut ASN1_INTEGER; - pub fn X509_get_subject_name(x: *mut X509) -> *mut X509_NAME; 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_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_set_version(x: *mut X509, version: c_ulong) -> 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; pub fn X509_get_pubkey(x: *mut X509) -> *mut EVP_PKEY; pub fn X509_to_X509_REQ(x: *mut X509, pkey: *mut EVP_PKEY, md: *const EVP_MD) -> *mut X509_REQ; - 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_EXTENSION_free(ext: *mut X509_EXTENSION); - pub fn X509_NAME_add_entry_by_txt(x: *mut X509, field: *const c_char, ty: c_int, bytes: *const c_char, len: c_int, loc: c_int, set: c_int) -> c_int; + 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; - 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 ASN1_STRING_to_UTF8(out: *mut *mut c_char, s: *mut ASN1_STRING) -> c_int; - pub fn ASN1_STRING_length(x: *mut ASN1_STRING) -> c_int; - pub fn ASN1_STRING_data(x: *mut ASN1_STRING) -> *mut c_uchar; + pub fn ASN1_STRING_length(x: *const ASN1_STRING) -> c_int; pub fn X509_STORE_CTX_get_current_cert(ct: *mut X509_STORE_CTX) -> *mut X509; pub fn X509_STORE_CTX_get_error(ctx: *mut X509_STORE_CTX) -> c_int; @@ -1080,14 +698,14 @@ extern "C" { 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; - pub fn d2i_X509(a: *mut *mut X509, pp: *mut *mut c_uchar, length: c_long) -> *mut X509; + pub fn d2i_X509(a: *mut *mut X509, pp: *mut *const c_uchar, length: c_long) -> *mut X509; pub fn i2d_X509_bio(b: *mut BIO, x: *mut X509) -> c_int; pub fn i2d_X509_REQ_bio(b: *mut BIO, x: *mut X509_REQ) -> c_int; - pub fn i2d_RSA_PUBKEY(k: *mut RSA, buf: *const *mut u8) -> c_int; - pub fn d2i_RSA_PUBKEY(k: *const *mut RSA, buf: *const *const u8, len: c_uint) -> *mut RSA; - pub fn i2d_RSAPrivateKey(k: *mut RSA, buf: *const *mut u8) -> c_int; - pub fn d2i_RSAPrivateKey(k: *const *mut RSA, buf: *const *const u8, len: c_uint) -> *mut RSA; + pub fn i2d_RSA_PUBKEY(k: *mut RSA, buf: *mut *mut u8) -> c_int; + pub fn d2i_RSA_PUBKEY(k: *mut *mut RSA, buf: *mut *const u8, len: c_long) -> *mut RSA; + pub fn i2d_RSAPrivateKey(k: *const RSA, buf: *mut *mut u8) -> c_int; + pub fn d2i_RSAPrivateKey(k: *mut *mut RSA, buf: *mut *const u8, len: c_long) -> *mut RSA; pub fn d2i_PKCS12(a: *mut *mut PKCS12, pp: *mut *const u8, length: c_long) -> *mut PKCS12; pub fn PKCS12_parse(p12: *mut PKCS12, @@ -1098,14 +716,18 @@ extern "C" { -> c_int; pub fn PKCS12_free(p12: *mut PKCS12); - pub fn sk_free(st: *mut _STACK); - pub fn sk_pop_free(st: *mut _STACK, free: Option); - pub fn sk_pop(st: *mut _STACK) -> *mut c_char; - pub fn GENERAL_NAME_free(name: *mut GENERAL_NAME); - pub fn SSLeay() -> c_long; - pub fn SSLeay_version(key: c_int) -> *const c_char; + pub fn HMAC_Init_ex(ctx: *mut HMAC_CTX, + key: *const c_void, + len: c_int, + md: *const EVP_MD, + impl_: *mut ENGINE) -> c_int; + pub fn HMAC_Update(ctx: *mut HMAC_CTX, + data: *const c_uchar, + len: size_t) -> c_int; + pub fn HMAC_Final(ctx: *mut HMAC_CTX, + md: *mut c_uchar, + len: *mut c_uint) -> c_int; + pub fn DH_new() -> *mut DH; } - -pub mod probe; diff --git a/openssl-sys/src/ossl10x.rs b/openssl-sys/src/ossl10x.rs new file mode 100644 index 00000000..8420846a --- /dev/null +++ b/openssl-sys/src/ossl10x.rs @@ -0,0 +1,569 @@ +use std::sync::{Mutex, MutexGuard}; +use std::sync::{Once, ONCE_INIT}; +use std::mem; + +use libc::{c_int, c_char, c_void, c_long, c_uchar, size_t, c_uint, c_ulong}; + +#[repr(C)] +pub struct stack_st_X509 { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_X509_ATTRIBUTE { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_X509_EXTENSION { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_GENERAL_NAME { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_void { + pub stack: _STACK, +} + +#[repr(C)] +pub struct _STACK { + pub num: c_int, + pub data: *mut *mut c_char, + pub sorted: c_int, + pub num_alloc: c_int, + pub comp: Option c_int>, +} + +#[repr(C)] +pub struct BIO_METHOD { + pub type_: c_int, + pub name: *const c_char, + pub bwrite: Option c_int>, + pub bread: Option c_int>, + pub bputs: Option c_int>, + pub bgets: Option c_int>, + pub ctrl: Option c_long>, + pub create: Option c_int>, + pub destroy: Option c_int>, + pub callback_ctrl: Option c_long>, +} + +#[repr(C)] +pub struct RSA { + pub pad: c_int, + pub version: c_long, + pub meth: *const ::RSA_METHOD, + + pub engine: *mut ::ENGINE, + pub n: *mut ::BIGNUM, + pub e: *mut ::BIGNUM, + pub d: *mut ::BIGNUM, + pub p: *mut ::BIGNUM, + pub q: *mut ::BIGNUM, + pub dmp1: *mut ::BIGNUM, + pub dmq1: *mut ::BIGNUM, + pub iqmp: *mut ::BIGNUM, + + pub ex_data: ::CRYPTO_EX_DATA, + pub references: c_int, + pub flags: c_int, + + pub _method_mod_n: *mut ::BN_MONT_CTX, + pub _method_mod_p: *mut ::BN_MONT_CTX, + pub _method_mod_q: *mut ::BN_MONT_CTX, + + pub bignum_data: *mut c_char, + pub blinding: *mut ::BN_BLINDING, + pub mt_blinding: *mut ::BN_BLINDING, +} + +#[repr(C)] +pub struct DSA { + pub pad: c_int, + pub version: c_long, + pub write_params: c_int, + + pub p: *mut ::BIGNUM, + pub q: *mut ::BIGNUM, + pub g: *mut ::BIGNUM, + pub pub_key: *mut ::BIGNUM, + pub priv_key: *mut ::BIGNUM, + pub kinv: *mut ::BIGNUM, + pub r: *mut ::BIGNUM, + + pub flags: c_int, + pub method_mont_p: *mut ::BN_MONT_CTX, + pub references: c_int, + pub ex_data: ::CRYPTO_EX_DATA, + pub meth: *const ::DSA_METHOD, + pub engine: *mut ::ENGINE, +} + +#[repr(C)] +pub struct EVP_PKEY { + pub type_: c_int, + pub save_type: c_int, + pub references: c_int, + pub ameth: *const ::EVP_PKEY_ASN1_METHOD, + pub engine: *mut ::ENGINE, + pub pkey: *mut c_void, + pub save_parameters: c_int, + pub attributes: *mut stack_st_X509_ATTRIBUTE, +} + +#[repr(C)] +pub struct BIO { + pub method: *mut ::BIO_METHOD, + pub callback: Option c_long>, + pub cb_arg: *mut c_char, + pub init: c_int, + pub shutdown: c_int, + pub flags: c_int, + pub retry_reason: c_int, + pub num: c_int, + pub ptr: *mut c_void, + pub next_bio: *mut ::BIO, + pub prev_bio: *mut ::BIO, + pub references: c_int, + pub num_read: c_ulong, + pub num_write: c_ulong, + pub ex_data: ::CRYPTO_EX_DATA, +} + +#[repr(C)] +pub struct CRYPTO_EX_DATA { + pub sk: *mut ::stack_st_void, + pub dummy: c_int, +} + +#[repr(C)] +pub struct EVP_MD_CTX { + digest: *mut ::EVP_MD, + engine: *mut ::ENGINE, + flags: c_ulong, + md_data: *mut c_void, + pctx: *mut ::EVP_PKEY_CTX, + update: *mut c_void +} + +#[repr(C)] +pub struct EVP_CIPHER { + pub nid: c_int, + pub block_size: c_int, + pub key_len: c_int, + pub iv_len: c_int, + pub flags: c_ulong, + pub init: Option c_int>, + pub do_cipher: Option c_int>, + pub cleanup: Option c_int>, + pub ctx_size: c_int, + pub set_asn1_parameters: Option c_int>, + pub get_asn1_parameters: Option c_int>, + pub ctrl: Option c_int>, + pub app_data: *mut c_void, +} + +#[repr(C)] +pub struct HMAC_CTX { + md: *mut ::EVP_MD, + md_ctx: ::EVP_MD_CTX, + i_ctx: ::EVP_MD_CTX, + o_ctx: ::EVP_MD_CTX, + key_length: c_uint, + key: [c_uchar; 128] +} + +#[repr(C)] +pub struct BIGNUM { + pub d: *mut ::BN_ULONG, + pub top: c_int, + pub dmax: c_int, + pub neg: c_int, + pub flags: c_int, +} + +#[repr(C)] +pub struct DH { + pub pad: c_int, + pub version: c_int, + pub p: *mut ::BIGNUM, + pub g: *mut ::BIGNUM, + pub length: c_long, + pub pub_key: *mut ::BIGNUM, + pub priv_key: *mut ::BIGNUM, + pub flags: c_int, + pub method_mont_p: *mut ::BN_MONT_CTX, + pub q: *mut ::BIGNUM, + pub j: *mut ::BIGNUM, + pub seed: *mut c_uchar, + pub seedlen: c_int, + pub counter: *mut ::BIGNUM, + pub references: c_int, + pub ex_data: ::CRYPTO_EX_DATA, + pub meth: *const ::DH_METHOD, + pub engine: *mut ::ENGINE, +} + +#[repr(C)] +pub struct X509 { + pub cert_info: *mut X509_CINF, + sig_alg: *mut c_void, + signature: *mut c_void, + pub valid: c_int, + pub references: c_int, + pub name: *mut c_char, + pub ex_data: ::CRYPTO_EX_DATA, + pub ex_pathlen: c_long, + pub ex_pcpathlen: c_long, + pub ex_flags: c_ulong, + pub ex_kusage: c_ulong, + pub ex_xkusage: c_ulong, + pub ex_nscert: c_ulong, + skid: *mut c_void, + akid: *mut c_void, + policy_cache: *mut c_void, + crldp: *mut c_void, + altname: *mut c_void, + nc: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_RFC3779"))] + rfc3779_addr: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_RFC3779"))] + rfc3779_asid: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_SHA"))] + sha1_hash: [c_uchar; 20], + aux: *mut c_void, +} + +#[repr(C)] +pub struct X509_CINF { + version: *mut c_void, + serialNumber: *mut c_void, + signature: *mut c_void, + issuer: *mut c_void, + pub validity: *mut X509_VAL, + subject: *mut c_void, + key: *mut c_void, + issuerUID: *mut c_void, + subjectUID: *mut c_void, + pub extensions: *mut stack_st_X509_EXTENSION, + enc: ASN1_ENCODING, +} + +#[repr(C)] +pub struct ASN1_ENCODING { + pub enc: *mut c_uchar, + pub len: c_long, + pub modified: c_int, +} + +#[repr(C)] +pub struct X509_VAL { + pub notBefore: *mut ::ASN1_TIME, + pub notAfter: *mut ::ASN1_TIME, +} + +#[repr(C)] +pub struct SSL_CTX { + method: *mut c_void, + cipher_list: *mut c_void, + cipher_list_by_id: *mut c_void, + cert_store: *mut c_void, + sessions: *mut c_void, + session_cache_size: c_ulong, + session_cache_head: *mut c_void, + session_cache_tail: *mut c_void, + session_cache_mode: c_int, + session_timeout: c_long, + new_session_cb: *mut c_void, + remove_session_cb: *mut c_void, + get_session_cb: *mut c_void, + stats: [c_int; 11], + pub references: c_int, + app_verify_callback: *mut c_void, + app_verify_arg: *mut c_void, + default_passwd_callback: *mut c_void, + default_passwd_callback_userdata: *mut c_void, + client_cert_cb: *mut c_void, + app_gen_cookie_cb: *mut c_void, + app_verify_cookie_cb: *mut c_void, + ex_dat: ::CRYPTO_EX_DATA, + rsa_md5: *mut c_void, + md5: *mut c_void, + sha1: *mut c_void, + extra_certs: *mut c_void, + comp_methods: *mut c_void, + info_callback: *mut c_void, + client_CA: *mut c_void, + options: c_ulong, + mode: c_ulong, + max_cert_list: c_long, + cert: *mut c_void, + read_ahead: c_int, + msg_callback: *mut c_void, + msg_callback_arg: *mut c_void, + verify_mode: c_int, + sid_ctx_length: c_uint, + sid_ctx: [c_uchar; 32], + default_verify_callback: *mut c_void, + generate_session_id: *mut c_void, + param: *mut c_void, + quiet_shutdown: c_int, + max_send_fragment: c_uint, + + #[cfg(not(osslconf = "OPENSSL_NO_ENGINE"))] + client_cert_engine: *mut c_void, + + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_servername_callback: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsect_servername_arg: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_tick_key_name: [c_uchar; 16], + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_tick_hmac_key: [c_uchar; 16], + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_tick_aes_key: [c_uchar; 16], + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_ticket_key_cb: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_status_cb: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_status_arg: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_opaque_prf_input_callback: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_opaque_prf_input_callback_arg: *mut c_void, + + #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] + psk_identity_hint: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] + psk_client_callback: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] + psk_server_callback: *mut c_void, + + #[cfg(not(osslconf = "OPENSSL_NO_BUF_FREELISTS"))] + freelist_max_len: c_uint, + #[cfg(not(osslconf = "OPENSSL_NO_BUF_FREELISTS"))] + wbuf_freelist: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_BUF_FREELISTS"))] + rbuf_freelist: *mut c_void, + + #[cfg(not(osslconf = "OPENSSL_NO_SRP"))] + srp_ctx: SRP_CTX, + + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_NEXTPROTONEG")))] + next_protos_advertised_cb: *mut c_void, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_NEXTPROTONEG")))] + next_protos_advertised_cb_arg: *mut c_void, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_NEXTPROTONEG")))] + next_proto_select_cb: *mut c_void, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_NEXTPROTONEG")))] + next_proto_select_cb_arg: *mut c_void, + + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl101))] + srtp_profiles: *mut c_void, + + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] + srtp_profiles: *mut c_void, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] + alpn_select_cb: *mut c_void, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] + alpn_select_cb_arg: *mut c_void, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] + alpn_client_proto_list: *mut c_void, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] + alpn_client_proto_list_len: c_uint, + + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC"), ossl102))] + tlsext_ecpointformatlist_length: size_t, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC"), ossl102))] + tlsext_ecpointformatlist: *mut c_uchar, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC"), ossl102))] + tlsext_ellipticcurvelist_length: size_t, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC"), ossl102))] + tlsext_ellipticcurvelist: *mut c_uchar, +} + +#[repr(C)] +pub struct SRP_CTX { + SRP_cb_arg: *mut c_void, + TLS_ext_srp_username_callback: *mut c_void, + SRP_verify_param_callback: *mut c_void, + SRP_give_srp_client_pwd_callback: *mut c_void, + login: *mut c_void, + N: *mut c_void, + g: *mut c_void, + s: *mut c_void, + B: *mut c_void, + A: *mut c_void, + a: *mut c_void, + b: *mut c_void, + v: *mut c_void, + info: *mut c_void, + stringth: c_int, + srp_Mask: c_ulong, +} + +pub const SSL_CTRL_OPTIONS: c_int = 32; +pub const SSL_CTRL_CLEAR_OPTIONS: c_int = 77; +#[cfg(ossl102)] +pub const SSL_CTRL_SET_ECDH_AUTO: c_int = 94; + +pub const SSL_OP_MICROSOFT_SESS_ID_BUG: c_ulong = 0x00000001; +pub const SSL_OP_NETSCAPE_CHALLENGE_BUG: c_ulong = 0x00000002; +pub const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: c_ulong = 0x00000008; +pub const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: c_ulong = 0x00000020; +pub const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: c_ulong = 0x00000080; +pub const SSL_OP_TLS_D5_BUG: c_ulong = 0x00000100; +pub const SSL_OP_TLS_BLOCK_PADDING_BUG: c_ulong = 0x00000200; +pub const SSL_OP_SINGLE_ECDH_USE: c_ulong = 0x00080000; +pub const SSL_OP_SINGLE_DH_USE: c_ulong = 0x00100000; +pub const SSL_OP_NO_SSLv2: c_ulong = 0x01000000; + +pub const SSLEAY_VERSION : c_int = 0; +pub const SSLEAY_CFLAGS : c_int = 2; +pub const SSLEAY_BUILT_ON : c_int = 3; +pub const SSLEAY_PLATFORM : c_int = 4; +pub const SSLEAY_DIR : c_int = 5; + +pub const CRYPTO_LOCK_X509: c_int = 3; +pub const CRYPTO_LOCK_SSL_CTX: c_int = 12; + +static mut MUTEXES: *mut Vec> = 0 as *mut Vec>; +static mut GUARDS: *mut Vec>> = 0 as *mut Vec>>; + +unsafe extern fn locking_function(mode: c_int, n: c_int, _file: *const c_char, + _line: c_int) { + let mutex = &(*MUTEXES)[n as usize]; + + if mode & ::CRYPTO_LOCK != 0 { + (*GUARDS)[n as usize] = Some(mutex.lock().unwrap()); + } else { + &(*GUARDS)[n as usize].take(); + } +} + +pub fn init() { + static INIT: Once = ONCE_INIT; + + INIT.call_once(|| { + unsafe { + SSL_library_init(); + SSL_load_error_strings(); + OPENSSL_add_all_algorithms_noconf(); + + let num_locks = ::CRYPTO_num_locks(); + let mut mutexes = Box::new(Vec::new()); + for _ in 0..num_locks { + mutexes.push(Mutex::new(())); + } + MUTEXES = mem::transmute(mutexes); + let guards: Box>>> = + Box::new((0..num_locks).map(|_| None).collect()); + GUARDS = mem::transmute(guards); + + CRYPTO_set_locking_callback(locking_function); + set_id_callback(); + } + }) +} + +#[cfg(unix)] +fn set_id_callback() { + unsafe extern fn thread_id() -> c_ulong { + ::libc::pthread_self() as c_ulong + } + + unsafe { + CRYPTO_set_id_callback(thread_id); + } +} + +#[cfg(not(unix))] +fn set_id_callback() {} + +extern { + pub fn BIO_new(type_: *mut BIO_METHOD) -> *mut BIO; + pub fn BIO_s_file() -> *mut BIO_METHOD; + pub fn BIO_s_mem() -> *mut BIO_METHOD; + pub fn CRYPTO_free(buf: *mut c_void); + pub fn CRYPTO_num_locks() -> c_int; + pub fn CRYPTO_set_locking_callback(func: unsafe extern "C" fn(mode: c_int, + n: c_int, + file: *const c_char, + line: c_int)); + pub fn CRYPTO_set_id_callback(func: unsafe extern "C" fn() -> c_ulong); + + pub fn ERR_load_crypto_strings(); + + pub fn RSA_generate_key(modsz: c_int, + e: c_ulong, + cb: Option, + cbarg: *mut c_void) -> *mut RSA; + + pub fn SSL_library_init() -> c_int; + pub fn SSL_load_error_strings(); + pub fn OPENSSL_add_all_algorithms_noconf(); + pub fn HMAC_CTX_init(ctx: *mut ::HMAC_CTX); + pub fn HMAC_CTX_cleanup(ctx: *mut ::HMAC_CTX); + pub fn SSLv3_method() -> *const ::SSL_METHOD; + pub fn TLSv1_method() -> *const ::SSL_METHOD; + pub fn SSLv23_method() -> *const ::SSL_METHOD; + pub fn TLSv1_1_method() -> *const ::SSL_METHOD; + pub fn TLSv1_2_method() -> *const ::SSL_METHOD; + pub fn DTLSv1_method() -> *const ::SSL_METHOD; + #[cfg(ossl102)] + pub fn DTLSv1_2_method() -> *const ::SSL_METHOD; + pub fn SSL_get_ex_new_index(argl: c_long, argp: *mut c_void, + new_func: Option<::CRYPTO_EX_new>, + dup_func: Option<::CRYPTO_EX_dup>, + free_func: Option<::CRYPTO_EX_free>) + -> c_int; + pub fn SSL_CIPHER_get_version(cipher: *const ::SSL_CIPHER) -> *mut c_char; + pub fn SSL_CTX_get_ex_new_index(argl: c_long, argp: *mut c_void, + new_func: Option<::CRYPTO_EX_new>, + dup_func: Option<::CRYPTO_EX_dup>, + free_func: Option<::CRYPTO_EX_free>) + -> c_int; + pub fn X509_get_subject_name(x: *mut ::X509) -> *mut ::X509_NAME; + 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_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 ASN1_STRING_to_UTF8(out: *mut *mut c_uchar, s: *mut ::ASN1_STRING) -> c_int; + pub fn ASN1_STRING_data(x: *mut ::ASN1_STRING) -> *mut c_uchar; + pub fn CRYPTO_add_lock(pointer: *mut c_int, + amount: c_int, + type_: c_int, + file: *const c_char, + line: c_int) -> c_int; + + pub fn sk_free(st: *mut _STACK); + 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; + pub fn SSLeay_version(key: c_int) -> *const c_char; +} diff --git a/openssl-sys/src/ossl110.rs b/openssl-sys/src/ossl110.rs new file mode 100644 index 00000000..62a66cd5 --- /dev/null +++ b/openssl-sys/src/ossl110.rs @@ -0,0 +1,146 @@ +use libc::{c_int, c_void, c_char, c_uchar, c_ulong, c_long}; + +pub enum stack_st_X509 {} +pub enum stack_st_X509_ATTRIBUTE {} +pub enum stack_st_X509_EXTENSION {} +pub enum stack_st_GENERAL_NAME {} +pub enum stack_st_void {} +pub enum _STACK {} +pub enum BIO_METHOD {} +pub enum RSA {} +pub enum DSA {} +pub enum EVP_PKEY {} +pub enum BIO {} +pub enum CRYPTO_EX_DATA {} +pub enum EVP_MD_CTX {} +pub enum EVP_CIPHER {} +pub enum HMAC_CTX {} +pub enum BIGNUM {} +pub enum OPENSSL_STACK {} +pub enum DH {} +pub enum X509 {} +pub enum SSL_CTX {} + +pub const SSL_OP_MICROSOFT_SESS_ID_BUG: c_ulong = 0x00000000; +pub const SSL_OP_NETSCAPE_CHALLENGE_BUG: c_ulong = 0x00000000; +pub const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: c_ulong = 0x00000000; +pub const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: c_ulong = 0x00000000; +pub const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: c_ulong = 0x00000000; +pub const SSL_OP_TLS_D5_BUG: c_ulong = 0x00000000; +pub const SSL_OP_TLS_BLOCK_PADDING_BUG: c_ulong = 0x00000000; +pub const SSL_OP_SINGLE_ECDH_USE: c_ulong = 0x00000000; +pub const SSL_OP_SINGLE_DH_USE: c_ulong = 0x00000000; +pub const SSL_OP_NO_SSLv2: c_ulong = 0x00000000; + +pub const OPENSSL_VERSION: c_int = 0; +pub const OPENSSL_CFLAGS: c_int = 1; +pub const OPENSSL_BUILT_ON: c_int = 2; +pub const OPENSSL_PLATFORM: c_int = 3; +pub const OPENSSL_DIR: c_int = 4; + +pub const CRYPTO_EX_INDEX_SSL: c_int = 0; +pub const CRYPTO_EX_INDEX_SSL_CTX: c_int = 1; + +pub fn init() {} + +extern { + pub fn BIO_new(type_: *const BIO_METHOD) -> *mut BIO; + pub fn BIO_s_file() -> *const BIO_METHOD; + pub fn BIO_s_mem() -> *const BIO_METHOD; + pub fn CRYPTO_free(buf: *mut c_void, file: *const c_char, line: c_int); + pub fn HMAC_CTX_new() -> *mut HMAC_CTX; + pub fn HMAC_CTX_free(ctx: *mut HMAC_CTX); + pub fn TLS_method() -> *const ::SSL_METHOD; + pub fn DTLS_method() -> *const ::SSL_METHOD; + pub fn SSL_CIPHER_get_version(cipher: *const ::SSL_CIPHER) -> *const c_char; + pub fn X509_get_subject_name(x: *const ::X509) -> *mut ::X509_NAME; + 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_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 ASN1_STRING_to_UTF8(out: *mut *mut c_uchar, s: *const ::ASN1_STRING) -> c_int; + pub fn BN_is_negative(b: *const ::BIGNUM) -> c_int; + pub fn EVP_CIPHER_key_length(cipher: *const EVP_CIPHER) -> c_int; + pub fn EVP_CIPHER_block_size(cipher: *const EVP_CIPHER) -> c_int; + pub fn EVP_CIPHER_iv_length(cipher: *const EVP_CIPHER) -> c_int; + pub fn DSA_get0_pqg(d: *const ::DSA, + p: *mut *const ::BIGNUM, + q: *mut *const ::BIGNUM, + q: *mut *const ::BIGNUM); + pub fn DSA_get0_key(d: *const ::DSA, + pub_key: *mut *const ::BIGNUM, + priv_key: *mut *const ::BIGNUM); + pub fn RSA_get0_key(r: *const ::RSA, + n: *mut *const ::BIGNUM, + e: *mut *const ::BIGNUM, + d: *mut *const ::BIGNUM); + pub fn RSA_get0_factors(r: *const ::RSA, + p: *mut *const ::BIGNUM, + q: *mut *const ::BIGNUM); + pub fn RSA_set0_key(r: *mut ::RSA, + n: *mut ::BIGNUM, + e: *mut ::BIGNUM, + d: *mut ::BIGNUM) -> c_int; + pub fn RSA_set0_factors(r: *mut ::RSA, + p: *mut ::BIGNUM, + q: *mut ::BIGNUM) -> c_int; + pub fn RSA_set0_crt_params(r: *mut ::RSA, + dmp1: *mut ::BIGNUM, + dmq1: *mut ::BIGNUM, + iqmp: *mut ::BIGNUM) -> c_int; + pub fn ASN1_STRING_get0_data(x: *const ::ASN1_STRING) -> *const c_uchar; + pub fn OPENSSL_sk_num(stack: *const ::OPENSSL_STACK) -> c_int; + pub fn OPENSSL_sk_value(stack: *const ::OPENSSL_STACK, + idx: c_int) -> *mut c_void; + pub fn SSL_CTX_get_options(ctx: *const ::SSL_CTX) -> c_ulong; + pub fn SSL_CTX_set_options(ctx: *mut ::SSL_CTX, op: c_ulong) -> c_ulong; + pub fn SSL_CTX_clear_options(ctx: *mut ::SSL_CTX, op: c_ulong) -> c_ulong; + pub fn X509_getm_notAfter(x: *const ::X509) -> *mut ::ASN1_TIME; + pub fn X509_getm_notBefore(x: *const ::X509) -> *mut ::ASN1_TIME; + pub fn DH_set0_pqg(dh: *mut ::DH, + p: *mut ::BIGNUM, + q: *mut ::BIGNUM, + g: *mut ::BIGNUM) -> c_int; + pub fn BIO_set_init(a: *mut ::BIO, init: c_int); + pub fn BIO_set_data(a: *mut ::BIO, data: *mut c_void); + pub fn BIO_get_data(a: *mut ::BIO) -> *mut c_void; + pub fn BIO_meth_new(type_: c_int, name: *const c_char) -> *mut ::BIO_METHOD; + pub fn BIO_meth_free(biom: *mut ::BIO_METHOD); + pub fn BIO_meth_set_write(biom: *mut ::BIO_METHOD, + write: unsafe extern fn(*mut ::BIO, + *const c_char, + c_int) -> c_int) -> c_int; + pub fn BIO_meth_set_read(biom: *mut ::BIO_METHOD, + read: unsafe extern fn(*mut ::BIO, + *mut c_char, + c_int) -> c_int) -> c_int; + pub fn BIO_meth_set_puts(biom: *mut ::BIO_METHOD, + read: unsafe extern fn(*mut ::BIO, + *const c_char) -> c_int) -> c_int; + pub fn BIO_meth_set_ctrl(biom: *mut ::BIO_METHOD, + read: unsafe extern fn(*mut ::BIO, + c_int, + c_long, + *mut c_void) -> c_long) -> c_int; + pub fn BIO_meth_set_create(biom: *mut ::BIO_METHOD, + create: unsafe extern fn(*mut ::BIO) -> c_int) -> c_int; + pub fn BIO_meth_set_destroy(biom: *mut ::BIO_METHOD, + destroy: unsafe extern fn(*mut ::BIO) -> c_int) -> c_int; + pub fn CRYPTO_get_ex_new_index(class_index: c_int, + argl: c_long, + argp: *mut c_void, + new_func: Option<::CRYPTO_EX_new>, + dup_func: Option<::CRYPTO_EX_dup>, + free_func: Option<::CRYPTO_EX_free>) + -> c_int; + pub fn X509_up_ref(x: *mut X509) -> c_int; + pub fn SSL_CTX_up_ref(x: *mut SSL_CTX) -> c_int; + pub fn X509_get0_extensions(req: *const ::X509) -> *const stack_st_X509_EXTENSION; + + pub fn OpenSSL_version_num() -> c_ulong; + pub fn OpenSSL_version(key: c_int) -> *const c_char; + pub fn OPENSSL_sk_free(st: *mut _STACK); + pub fn OPENSSL_sk_pop_free(st: *mut _STACK, free: Option); + pub fn OPENSSL_sk_pop(st: *mut _STACK) -> *mut c_void; +} diff --git a/openssl-sys/src/probe.rs b/openssl-sys/src/probe.rs deleted file mode 100644 index e3711b54..00000000 --- a/openssl-sys/src/probe.rs +++ /dev/null @@ -1,77 +0,0 @@ -use std::env; -use std::fs; -use std::path::PathBuf; - -pub struct ProbeResult { - pub cert_file: Option, - pub cert_dir: Option, -} - -/// Probe the system for the directory in which CA certificates should likely be -/// found. -/// -/// This will only search known system locations. -pub fn find_certs_dirs() -> Vec { - // see http://gagravarr.org/writing/openssl-certs/others.shtml - [ - "/var/ssl", - "/usr/share/ssl", - "/usr/local/ssl", - "/usr/local/openssl", - "/usr/local/share", - "/usr/lib/ssl", - "/usr/ssl", - "/etc/openssl", - "/etc/pki/tls", - "/etc/ssl", - ].iter().map(|s| PathBuf::from(*s)).filter(|p| { - fs::metadata(p).is_ok() - }).collect() -} - -pub fn init_ssl_cert_env_vars() { - let ProbeResult { cert_file, cert_dir } = probe(); - match cert_file { - Some(path) => put("SSL_CERT_FILE", path), - None => {} - } - match cert_dir { - Some(path) => put("SSL_CERT_DIR", path), - None => {} - } - - fn put(var: &str, path: PathBuf) { - // Don't stomp over what anyone else has set - match env::var(var) { - Ok(..) => {} - Err(..) => env::set_var(var, &path), - } - } -} - -pub fn probe() -> ProbeResult { - let mut result = ProbeResult { - cert_file: env::var_os("SSL_CERT_FILE").map(PathBuf::from), - cert_dir: env::var_os("SSL_CERT_DIR").map(PathBuf::from), - }; - for certs_dir in find_certs_dirs().iter() { - // cert.pem looks to be an openssl 1.0.1 thing, while - // certs/ca-certificates.crt appears to be a 0.9.8 thing - for cert in [ - "cert.pem", - "certs.pem", - "certs/ca-certificates.crt", - "certs/ca-root-nss.crt" - ].iter() { - try(&mut result.cert_file, certs_dir.join(cert)); - } - try(&mut result.cert_dir, certs_dir.join("certs")); - } - result -} - -fn try(dst: &mut Option, val: PathBuf) { - if dst.is_none() && fs::metadata(&val).is_ok() { - *dst = Some(val); - } -} diff --git a/openssl/Cargo.toml b/openssl/Cargo.toml index 3fd46c4b..d9691403 100644 --- a/openssl/Cargo.toml +++ b/openssl/Cargo.toml @@ -12,28 +12,23 @@ build = "build.rs" exclude = ["test/*"] [features] -tlsv1_2 = ["openssl-sys/tlsv1_2"] -tlsv1_1 = ["openssl-sys/tlsv1_1"] -dtlsv1 = ["openssl-sys/dtlsv1"] -dtlsv1_2 = ["openssl-sys/dtlsv1_2"] -sslv2 = ["openssl-sys/sslv2"] -sslv3 = ["openssl-sys/sslv3"] -aes_xts = ["openssl-sys/aes_xts"] -aes_ctr = ["openssl-sys/aes_ctr"] -npn = ["openssl-sys/npn"] -alpn = ["openssl-sys/alpn"] -rfc5114 = ["openssl-sys/rfc5114"] -ecdh_auto = ["openssl-sys/ecdh_auto"] -pkcs5_pbkdf2_hmac = ["openssl-sys/pkcs5_pbkdf2_hmac"] -hmac_clone = ["openssl-sys/hmac_clone"] +aes_xts = [] +aes_ctr = [] -c_helpers = ["gcc"] -x509_clone = ["c_helpers"] -x509_generator_request = ["c_helpers"] -x509_expiry = ["c_helpers"] -ssl_context_clone = ["c_helpers"] -hmac = ["c_helpers"] -dh_from_params = ["c_helpers"] +# Added in OpenSSL 1.0.2 +rfc5114 = [] + +# TODO: what to do about these features? +# tlsv1_2 = [] +# tlsv1_1 = [] +# dtlsv1 = [] +# dtlsv1_2 = [] +# sslv2 = [] +# sslv3 = [] + +npn = [] +alpn = [] +ecdh_auto = [] [dependencies] bitflags = "0.7" @@ -41,11 +36,9 @@ lazy_static = "0.2" libc = "0.2" openssl-sys = { version = "0.7.17", path = "../openssl-sys" } -[build-dependencies] -gcc = { version = "0.3", optional = true } - [dev-dependencies] -rustc-serialize = "0.3" net2 = "0.2.16" +rustc-serialize = "0.3" +tempdir = "0.3" winapi = "0.2" ws2_32-sys = "0.2" diff --git a/openssl/build.rs b/openssl/build.rs index b07c1b3e..15d4b4db 100644 --- a/openssl/build.rs +++ b/openssl/build.rs @@ -1,28 +1,15 @@ -#[cfg(feature = "c_helpers")] -mod imp { - extern crate gcc; - - use std::env; - use std::path::PathBuf; - - pub fn main() { - let mut config = gcc::Config::new(); - - if let Some(paths) = env::var_os("DEP_OPENSSL_INCLUDE") { - for path in env::split_paths(&paths) { - config.include(PathBuf::from(path)); - } - } - - config.file("src/c_helpers.c").compile("libc_helpers.a"); - } -} - -#[cfg(not(feature = "c_helpers"))] -mod imp { - pub fn main() {} -} +use std::env; fn main() { - imp::main() + if env::var("DEP_OPENSSL_IS_101").is_ok() { + println!("cargo:rustc-cfg=ossl101"); + println!("cargo:rustc-cfg=ossl10x"); + } + if env::var("DEP_OPENSSL_IS_102").is_ok() { + println!("cargo:rustc-cfg=ossl102"); + println!("cargo:rustc-cfg=ossl10x"); + } + if env::var("DEP_OPENSSL_IS_110").is_ok() { + println!("cargo:rustc-cfg=ossl110"); + } } diff --git a/openssl/src/bn/mod.rs b/openssl/src/bn/mod.rs index de9d0d2a..7d1f5458 100644 --- a/openssl/src/bn/mod.rs +++ b/openssl/src/bn/mod.rs @@ -1,4 +1,4 @@ -use libc::{c_int, c_ulong, c_void}; +use libc::{c_int, c_void}; use std::ffi::{CStr, CString}; use std::cmp::Ordering; use std::{fmt, ptr}; @@ -185,10 +185,11 @@ impl<'a> BigNumRef<'a> { } } - /// Add an `unsigned long` to `self`. This is more efficient than adding a `BigNum`. - pub fn add_word(&mut self, w: c_ulong) -> Result<(), ErrorStack> { + /// Add a `u32` to `self`. This is more efficient than adding a + /// `BigNum`. + pub fn add_word(&mut self, w: u32) -> Result<(), ErrorStack> { unsafe { - if ffi::BN_add_word(self.as_ptr(), w) == 1 { + if ffi::BN_add_word(self.as_ptr(), w as ffi::BN_ULONG) == 1 { Ok(()) } else { Err(ErrorStack::get()) @@ -196,9 +197,9 @@ impl<'a> BigNumRef<'a> { } } - pub fn sub_word(&mut self, w: c_ulong) -> Result<(), ErrorStack> { + pub fn sub_word(&mut self, w: u32) -> Result<(), ErrorStack> { unsafe { - if ffi::BN_sub_word(self.as_ptr(), w) == 1 { + if ffi::BN_sub_word(self.as_ptr(), w as ffi::BN_ULONG) == 1 { Ok(()) } else { Err(ErrorStack::get()) @@ -206,9 +207,9 @@ impl<'a> BigNumRef<'a> { } } - pub fn mul_word(&mut self, w: c_ulong) -> Result<(), ErrorStack> { + pub fn mul_word(&mut self, w: u32) -> Result<(), ErrorStack> { unsafe { - if ffi::BN_mul_word(self.as_ptr(), w) == 1 { + if ffi::BN_mul_word(self.as_ptr(), w as ffi::BN_ULONG) == 1 { Ok(()) } else { Err(ErrorStack::get()) @@ -216,22 +217,22 @@ impl<'a> BigNumRef<'a> { } } - pub fn div_word(&mut self, w: c_ulong) -> Result { + pub fn div_word(&mut self, w: u32) -> Result { unsafe { - let result = ffi::BN_div_word(self.as_ptr(), w); - if result != !0 as c_ulong { - Ok(result) + let result = ffi::BN_div_word(self.as_ptr(), w as ffi::BN_ULONG); + if result != !0 { + Ok(result.into()) } else { Err(ErrorStack::get()) } } } - pub fn mod_word(&self, w: c_ulong) -> Result { + pub fn mod_word(&self, w: u32) -> Result { unsafe { - let result = ffi::BN_mod_word(self.as_ptr(), w); - if result != !0 as c_ulong { - Ok(result) + let result = ffi::BN_mod_word(self.as_ptr(), w as ffi::BN_ULONG); + if result != !0 { + Ok(result as u64) } else { Err(ErrorStack::get()) } @@ -257,7 +258,10 @@ impl<'a> BigNumRef<'a> { pub fn is_prime(&self, checks: i32) -> Result { unsafe { with_ctx!(ctx, { - Ok(ffi::BN_is_prime_ex(self.as_ptr(), checks as c_int, ctx, ptr::null()) == 1) + Ok(ffi::BN_is_prime_ex(self.as_ptr(), + checks as c_int, + ctx, + ptr::null_mut()) == 1) }) } } @@ -278,7 +282,7 @@ impl<'a> BigNumRef<'a> { checks as c_int, ctx, do_trial_division as c_int, - ptr::null()) == 1) + ptr::null_mut()) == 1) }) } } @@ -483,9 +487,19 @@ impl<'a> BigNumRef<'a> { } pub fn is_negative(&self) -> bool { + self._is_negative() + } + + #[cfg(ossl10x)] + fn _is_negative(&self) -> bool { unsafe { (*self.as_ptr()).neg == 1 } } + #[cfg(ossl110)] + fn _is_negative(&self) -> bool { + unsafe { ffi::BN_is_negative(self.as_ptr()) == 1 } + } + /// Returns the number of significant bits in `self`. pub fn num_bits(&self) -> i32 { unsafe { ffi::BN_num_bits(self.as_ptr()) as i32 } @@ -536,7 +550,7 @@ impl<'a> BigNumRef<'a> { assert!(!buf.is_null()); let str = String::from_utf8(CStr::from_ptr(buf as *const _).to_bytes().to_vec()) .unwrap(); - ffi::CRYPTO_free(buf as *mut c_void); + CRYPTO_free!(buf as *mut c_void); str } } @@ -555,7 +569,7 @@ impl<'a> BigNumRef<'a> { assert!(!buf.is_null()); let str = String::from_utf8(CStr::from_ptr(buf as *const _).to_bytes().to_vec()) .unwrap(); - ffi::CRYPTO_free(buf as *mut c_void); + CRYPTO_free!(buf as *mut c_void); str } } @@ -580,27 +594,27 @@ impl BigNum { } /// Creates a new `BigNum` with the given value. - pub fn new_from(n: c_ulong) -> Result { + pub fn new_from(n: u32) -> Result { BigNum::new().and_then(|v| unsafe { - try_ssl!(ffi::BN_set_word(v.as_ptr(), n)); + try_ssl!(ffi::BN_set_word(v.as_ptr(), n as ffi::BN_ULONG)); Ok(v) }) } /// Creates a `BigNum` from a decimal string. pub fn from_dec_str(s: &str) -> Result { - BigNum::new().and_then(|v| unsafe { + BigNum::new().and_then(|mut v| unsafe { let c_str = CString::new(s.as_bytes()).unwrap(); - try_ssl!(ffi::BN_dec2bn(&(v.0).0, c_str.as_ptr() as *const _)); + try_ssl!(ffi::BN_dec2bn(&mut (v.0).0, c_str.as_ptr() as *const _)); Ok(v) }) } /// Creates a `BigNum` from a hexadecimal string. pub fn from_hex_str(s: &str) -> Result { - BigNum::new().and_then(|v| unsafe { + BigNum::new().and_then(|mut v| unsafe { let c_str = CString::new(s.as_bytes()).unwrap(); - try_ssl!(ffi::BN_hex2bn(&(v.0).0, c_str.as_ptr() as *const _)); + try_ssl!(ffi::BN_hex2bn(&mut (v.0).0, c_str.as_ptr() as *const _)); Ok(v) }) } @@ -646,7 +660,7 @@ impl BigNum { safe as c_int, add_arg, rem_arg, - ptr::null()) == 1 + ptr::null_mut()) == 1 }) } } diff --git a/openssl/src/c_helpers.c b/openssl/src/c_helpers.c deleted file mode 100644 index 6e6a5021..00000000 --- a/openssl/src/c_helpers.c +++ /dev/null @@ -1,67 +0,0 @@ -#include -#include -#include -#include - -void rust_0_8_SSL_CTX_clone(SSL_CTX *ctx) { - CRYPTO_add(&ctx->references,1,CRYPTO_LOCK_SSL_CTX); -} - -void rust_0_8_X509_clone(X509 *x509) { - CRYPTO_add(&x509->references,1,CRYPTO_LOCK_X509); -} - -STACK_OF(X509_EXTENSION) *rust_0_8_X509_get_extensions(X509 *x) { - return x->cert_info ? x->cert_info->extensions : NULL; -} - -ASN1_TIME* rust_0_8_X509_get_notAfter(X509 *x) { - return X509_get_notAfter(x); -} - -ASN1_TIME* rust_0_8_X509_get_notBefore(X509 *x) { - return X509_get_notBefore(x); -} - -DH *rust_0_8_DH_new_from_params(BIGNUM *p, BIGNUM *g, BIGNUM *q) { - DH *dh; - - if ((dh = DH_new()) == NULL) { - return NULL; - } - dh->p = p; - dh->g = g; - dh->q = q; - return dh; -} - -#if OPENSSL_VERSION_NUMBER < 0x10000000L -int rust_0_8_HMAC_Init_ex(HMAC_CTX *ctx, const void *key, int key_len, const EVP_MD *md, ENGINE *impl) { - HMAC_Init_ex(ctx, key, key_len, md, impl); - return 1; -} - -int rust_0_8_HMAC_Update(HMAC_CTX *ctx, const unsigned char *data, int len) { - HMAC_Update(ctx, data, len); - return 1; -} - -int rust_0_8_HMAC_Final(HMAC_CTX *ctx, unsigned char *md, unsigned int *len) { - HMAC_Final(ctx, md, len); - return 1; -} - -#else - -int rust_0_8_HMAC_Init_ex(HMAC_CTX *ctx, const void *key, int key_len, const EVP_MD *md, ENGINE *impl) { - return HMAC_Init_ex(ctx, key, key_len, md, impl); -} - -int rust_0_8_HMAC_Update(HMAC_CTX *ctx, const unsigned char *data, int len) { - return HMAC_Update(ctx, data, len); -} - -int rust_0_8_HMAC_Final(HMAC_CTX *ctx, unsigned char *md, unsigned int *len) { - return HMAC_Final(ctx, md, len); -} -#endif diff --git a/openssl/src/c_helpers.rs b/openssl/src/c_helpers.rs deleted file mode 100644 index d16c3125..00000000 --- a/openssl/src/c_helpers.rs +++ /dev/null @@ -1,15 +0,0 @@ -use ffi; -use libc::{c_int, c_void, c_uint, c_uchar}; - -#[allow(dead_code)] -extern "C" { - pub fn rust_0_8_SSL_CTX_clone(cxt: *mut ffi::SSL_CTX); - pub fn rust_0_8_X509_clone(x509: *mut ffi::X509); - pub fn rust_0_8_X509_get_extensions(x: *mut ffi::X509) -> *mut ffi::stack_st_X509_EXTENSION; - pub fn rust_0_8_X509_get_notAfter(x: *mut ffi::X509) -> *mut ffi::ASN1_TIME; - pub fn rust_0_8_X509_get_notBefore(x: *mut ffi::X509) -> *mut ffi::ASN1_TIME; - pub fn rust_0_8_HMAC_Init_ex(ctx: *mut ffi::HMAC_CTX, key: *const c_void, keylen: c_int, md: *const ffi::EVP_MD, impl_: *mut ffi::ENGINE) -> c_int; - pub fn rust_0_8_HMAC_Final(ctx: *mut ffi::HMAC_CTX, output: *mut c_uchar, len: *mut c_uint) -> c_int; - pub fn rust_0_8_HMAC_Update(ctx: *mut ffi::HMAC_CTX, input: *const c_uchar, len: c_uint) -> c_int; - pub fn rust_0_8_DH_new_from_params(p: *mut ffi::BIGNUM, g: *mut ffi::BIGNUM, q: *mut ffi::BIGNUM) -> *mut ffi::DH; -} diff --git a/openssl/src/crypto/dsa.rs b/openssl/src/crypto/dsa.rs index 97ba7a97..bb4fe474 100644 --- a/openssl/src/crypto/dsa.rs +++ b/openssl/src/crypto/dsa.rs @@ -19,8 +19,13 @@ impl DSAParams { unsafe { // Wrap it so that if we panic we'll call the dtor let dsa = DSAParams(try_ssl_null!(ffi::DSA_new())); - try_ssl!(ffi::DSA_generate_parameters_ex(dsa.0, size as c_int, ptr::null(), 0, - ptr::null_mut(), ptr::null_mut(), ptr::null())); + try_ssl!(ffi::DSA_generate_parameters_ex(dsa.0, + size as c_int, + ptr::null(), + 0, + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut())); Ok(dsa) } } @@ -190,43 +195,74 @@ impl DSA { pub fn p<'a>(&'a self) -> Option> { unsafe { - let p = (*self.0).p; + let p = compat::pqg(self.0)[0]; if p.is_null() { None } else { - Some(BigNumRef::from_ptr((*self.0).p)) + Some(BigNumRef::from_ptr(p as *mut _)) } } } pub fn q<'a>(&'a self) -> Option> { unsafe { - let q = (*self.0).q; + let q = compat::pqg(self.0)[1]; if q.is_null() { None } else { - Some(BigNumRef::from_ptr((*self.0).q)) + Some(BigNumRef::from_ptr(q as *mut _)) } } } pub fn g<'a>(&'a self) -> Option> { unsafe { - let g = (*self.0).g; + let g = compat::pqg(self.0)[2]; if g.is_null() { None } else { - Some(BigNumRef::from_ptr((*self.0).g)) + Some(BigNumRef::from_ptr(g as *mut _)) } } } pub fn has_public_key(&self) -> bool { - unsafe { !(*self.0).pub_key.is_null() } + unsafe { !compat::keys(self.0)[0].is_null() } } pub fn has_private_key(&self) -> bool { - unsafe { !(*self.0).priv_key.is_null() } + unsafe { !compat::keys(self.0)[1].is_null() } + } +} + +#[cfg(ossl110)] +mod compat { + use std::ptr; + use ffi::{self, BIGNUM, DSA}; + + pub unsafe fn pqg(d: *const DSA) -> [*const BIGNUM; 3] { + let (mut p, mut q, mut g) = (ptr::null(), ptr::null(), ptr::null()); + ffi::DSA_get0_pqg(d, &mut p, &mut q, &mut g); + [p, q, g] + } + + pub unsafe fn keys(d: *const DSA) -> [*const BIGNUM; 2] { + let (mut pub_key, mut priv_key) = (ptr::null(), ptr::null()); + ffi::DSA_get0_key(d, &mut pub_key, &mut priv_key); + [pub_key, priv_key] + } +} + +#[cfg(ossl10x)] +mod compat { + use ffi::{BIGNUM, DSA}; + + pub unsafe fn pqg(d: *const DSA) -> [*const BIGNUM; 3] { + [(*d).p, (*d).q, (*d).g] + } + + pub unsafe fn keys(d: *const DSA) -> [*const BIGNUM; 2] { + [(*d).pub_key, (*d).priv_key] } } diff --git a/openssl/src/crypto/hash.rs b/openssl/src/crypto/hash.rs index 207a55f5..d87c43c5 100644 --- a/openssl/src/crypto/hash.rs +++ b/openssl/src/crypto/hash.rs @@ -1,8 +1,6 @@ -use libc::c_uint; use std::io::prelude::*; use std::io; use std::ptr; -use std::cmp; use ffi; use HashTypeInternals; @@ -102,7 +100,7 @@ impl Hasher { pub fn new(ty: Type) -> Result { ffi::init(); - let ctx = unsafe { try_ssl_null!(ffi::EVP_MD_CTX_create()) }; + let ctx = unsafe { try_ssl_null!(ffi::EVP_MD_CTX_new()) }; let md = ty.evp_md(); let mut h = Hasher { @@ -123,22 +121,20 @@ impl Hasher { } Finalized => (), } - unsafe { try_ssl!(ffi::EVP_DigestInit_ex(self.ctx, self.md, 0 as *const _)); } + unsafe { try_ssl!(ffi::EVP_DigestInit_ex(self.ctx, self.md, 0 as *mut _)); } self.state = Reset; Ok(()) } /// Feeds data into the hasher. - pub fn update(&mut self, mut data: &[u8]) -> Result<(), ErrorStack> { + pub fn update(&mut self, data: &[u8]) -> Result<(), ErrorStack> { if self.state == Finalized { try!(self.init()); } - while !data.is_empty() { - let len = cmp::min(data.len(), c_uint::max_value() as usize); - unsafe { - try_ssl!(ffi::EVP_DigestUpdate(self.ctx, data.as_ptr(), len as c_uint)); - } - data = &data[len..]; + unsafe { + try_ssl!(ffi::EVP_DigestUpdate(self.ctx, + data.as_ptr() as *mut _, + data.len())); } self.state = Updated; Ok(()) @@ -176,7 +172,7 @@ impl Write for Hasher { impl Clone for Hasher { fn clone(&self) -> Hasher { let ctx = unsafe { - let ctx = ffi::EVP_MD_CTX_create(); + let ctx = ffi::EVP_MD_CTX_new(); assert!(!ctx.is_null()); let r = ffi::EVP_MD_CTX_copy_ex(ctx, self.ctx); assert_eq!(r, 1); @@ -197,7 +193,7 @@ impl Drop for Hasher { if self.state != Finalized { drop(self.finish()); } - ffi::EVP_MD_CTX_destroy(self.ctx); + ffi::EVP_MD_CTX_free(self.ctx); } } } diff --git a/openssl/src/crypto/hmac.rs b/openssl/src/crypto/hmac.rs index 1847d6b1..8f44ed7f 100644 --- a/openssl/src/crypto/hmac.rs +++ b/openssl/src/crypto/hmac.rs @@ -13,16 +13,14 @@ // limitations under the License. // -use libc::{c_int, c_uint}; +use libc::{c_int}; use std::io; use std::io::prelude::*; -use std::cmp; use ffi; use HashTypeInternals; use crypto::hash::Type; use error::ErrorStack; -use c_helpers; #[derive(PartialEq, Copy, Clone)] enum State { @@ -66,7 +64,7 @@ use self::State::*; /// assert_eq!(res, spec); /// ``` pub struct HMAC { - ctx: ffi::HMAC_CTX, + ctx: compat::HMAC_CTX, state: State, } @@ -75,11 +73,7 @@ impl HMAC { pub fn new(ty: Type, key: &[u8]) -> Result { ffi::init(); - let ctx = unsafe { - let mut ctx = ::std::mem::uninitialized(); - ffi::HMAC_CTX_init(&mut ctx); - ctx - }; + let ctx = compat::HMAC_CTX::new(); let md = ty.evp_md(); let mut h = HMAC { @@ -92,11 +86,11 @@ impl HMAC { fn init_once(&mut self, md: *const ffi::EVP_MD, key: &[u8]) -> Result<(), ErrorStack> { unsafe { - try_ssl!(c_helpers::rust_0_8_HMAC_Init_ex(&mut self.ctx, - key.as_ptr() as *const _, - key.len() as c_int, - md, - 0 as *mut _)); + try_ssl!(ffi::HMAC_Init_ex(self.ctx.get(), + key.as_ptr() as *const _, + key.len() as c_int, + md, + 0 as *mut _)); } self.state = Reset; Ok(()) @@ -113,26 +107,24 @@ impl HMAC { // If the key and/or md is not supplied it's reused from the last time // avoiding redundant initializations unsafe { - try_ssl!(c_helpers::rust_0_8_HMAC_Init_ex(&mut self.ctx, - 0 as *const _, - 0, - 0 as *const _, - 0 as *mut _)); + try_ssl!(ffi::HMAC_Init_ex(self.ctx.get(), + 0 as *const _, + 0, + 0 as *const _, + 0 as *mut _)); } self.state = Reset; Ok(()) } - pub fn update(&mut self, mut data: &[u8]) -> Result<(), ErrorStack> { + pub fn update(&mut self, data: &[u8]) -> Result<(), ErrorStack> { if self.state == Finalized { try!(self.init()); } - while !data.is_empty() { - let len = cmp::min(data.len(), c_uint::max_value() as usize); - unsafe { - try_ssl!(c_helpers::rust_0_8_HMAC_Update(&mut self.ctx, data.as_ptr(), len as c_uint)); - } - data = &data[len..]; + unsafe { + try_ssl!(ffi::HMAC_Update(self.ctx.get(), + data.as_ptr(), + data.len())); } self.state = Updated; Ok(()) @@ -147,7 +139,9 @@ impl HMAC { unsafe { let mut len = ffi::EVP_MAX_MD_SIZE; let mut res = vec![0; len as usize]; - try_ssl!(c_helpers::rust_0_8_HMAC_Final(&mut self.ctx, res.as_mut_ptr(), &mut len)); + try_ssl!(ffi::HMAC_Final(self.ctx.get(), + res.as_mut_ptr(), + &mut len)); res.truncate(len as usize); self.state = Finalized; Ok(res) @@ -167,14 +161,11 @@ impl Write for HMAC { } } -#[cfg(feature = "hmac_clone")] impl Clone for HMAC { - /// Requires the `hmac_clone` feature. fn clone(&self) -> HMAC { - let mut ctx: ffi::HMAC_CTX; + let ctx = compat::HMAC_CTX::new(); unsafe { - ctx = ::std::mem::uninitialized(); - let r = ffi::HMAC_CTX_copy(&mut ctx, &self.ctx); + let r = ffi::HMAC_CTX_copy(ctx.get(), self.ctx.get()); assert_eq!(r, 1); } HMAC { @@ -186,11 +177,8 @@ impl Clone for HMAC { impl Drop for HMAC { fn drop(&mut self) { - unsafe { - if self.state != Finalized { - drop(self.finish()); - } - ffi::HMAC_CTX_cleanup(&mut self.ctx); + if self.state != Finalized { + drop(self.finish()); } } } @@ -202,6 +190,73 @@ pub fn hmac(t: Type, key: &[u8], data: &[u8]) -> Result, ErrorStack> { h.finish() } +#[cfg(ossl110)] +#[allow(bad_style)] +mod compat { + use ffi; + + pub struct HMAC_CTX { + ctx: *mut ffi::HMAC_CTX, + } + + impl HMAC_CTX { + pub fn new() -> HMAC_CTX { + unsafe { + let ctx = ffi::HMAC_CTX_new(); + assert!(!ctx.is_null()); + HMAC_CTX { ctx: ctx } + } + } + + pub fn get(&self) -> *mut ffi::HMAC_CTX { + self.ctx + } + } + + impl Drop for HMAC_CTX { + fn drop(&mut self) { + unsafe { + ffi::HMAC_CTX_free(self.ctx); + } + } + } +} + +#[cfg(ossl10x)] +#[allow(bad_style)] +mod compat { + use std::mem; + use std::cell::UnsafeCell; + + use ffi; + + pub struct HMAC_CTX { + ctx: UnsafeCell, + } + + impl HMAC_CTX { + pub fn new() -> HMAC_CTX { + unsafe { + let mut ctx = mem::zeroed(); + ffi::HMAC_CTX_init(&mut ctx); + HMAC_CTX { ctx: UnsafeCell::new(ctx) } + } + } + + pub fn get(&self) -> *mut ffi::HMAC_CTX { + self.ctx.get() + } + } + + impl Drop for HMAC_CTX { + fn drop(&mut self) { + unsafe { + ffi::HMAC_CTX_cleanup(self.get()); + } + } + } +} + #[cfg(test)] mod tests { use std::iter::repeat; @@ -289,7 +344,6 @@ mod tests { } #[test] - #[cfg(feature = "hmac_clone")] fn test_clone() { let tests: [(Vec, Vec, Vec); 2] = [(repeat(0xaa_u8).take(80).collect(), diff --git a/openssl/src/crypto/mod.rs b/openssl/src/crypto/mod.rs index b8b109a2..389b7cc9 100644 --- a/openssl/src/crypto/mod.rs +++ b/openssl/src/crypto/mod.rs @@ -15,7 +15,6 @@ // pub mod hash; -#[cfg(feature = "hmac")] pub mod hmac; pub mod pkcs5; pub mod pkcs12; diff --git a/openssl/src/crypto/pkcs12.rs b/openssl/src/crypto/pkcs12.rs index 89bcbd5c..5f03a3d5 100644 --- a/openssl/src/crypto/pkcs12.rs +++ b/openssl/src/crypto/pkcs12.rs @@ -44,13 +44,14 @@ impl Pkcs12 { let pkey = PKey::from_ptr(pkey); let cert = X509::from_ptr(cert); + let chain = chain as *mut _; let mut chain_out = vec![]; - for i in 0..(*chain).stack.num { - let x509 = *(*chain).stack.data.offset(i as isize) as *mut _; - chain_out.push(X509::from_ptr(x509)); + for i in 0..compat::OPENSSL_sk_num(chain) { + let x509 = compat::OPENSSL_sk_value(chain, i); + chain_out.push(X509::from_ptr(x509 as *mut _)); } - ffi::sk_free(&mut (*chain).stack); + compat::OPENSSL_sk_free(chain as *mut _); Ok(ParsedPkcs12 { pkey: pkey, @@ -69,6 +70,31 @@ pub struct ParsedPkcs12 { _p: (), } +#[cfg(ossl110)] +mod compat { + pub use ffi::OPENSSL_sk_free; + pub use ffi::OPENSSL_sk_num; + pub use ffi::OPENSSL_sk_value; +} + +#[cfg(ossl10x)] +#[allow(bad_style)] +mod compat { + use libc::{c_int, c_void}; + use ffi; + + pub use ffi::sk_free as OPENSSL_sk_free; + + pub unsafe fn OPENSSL_sk_num(stack: *mut ffi::_STACK) -> c_int { + (*stack).num + } + + pub unsafe fn OPENSSL_sk_value(stack: *const ffi::_STACK, idx: c_int) + -> *mut c_void { + *(*stack).data.offset(idx as isize) as *mut c_void + } +} + #[cfg(test)] mod test { use crypto::hash::Type::SHA1; diff --git a/openssl/src/crypto/pkcs5.rs b/openssl/src/crypto/pkcs5.rs index ef84fbe1..adcbc9db 100644 --- a/openssl/src/crypto/pkcs5.rs +++ b/openssl/src/crypto/pkcs5.rs @@ -82,7 +82,7 @@ pub fn pbkdf2_hmac_sha1(pass: &[u8], ffi::init(); - try_ssl!(ffi::PKCS5_PBKDF2_HMAC_SHA1(pass.as_ptr(), + try_ssl!(ffi::PKCS5_PBKDF2_HMAC_SHA1(pass.as_ptr() as *const _, pass.len() as c_int, salt.as_ptr(), salt.len() as c_int, @@ -94,7 +94,6 @@ pub fn pbkdf2_hmac_sha1(pass: &[u8], } /// Derives a key from a password and salt using the PBKDF2-HMAC algorithm with a digest function. -#[cfg(feature = "pkcs5_pbkdf2_hmac")] pub fn pbkdf2_hmac(pass: &[u8], salt: &[u8], iter: usize, @@ -104,7 +103,7 @@ pub fn pbkdf2_hmac(pass: &[u8], unsafe { let mut out = vec![0; keylen]; ffi::init(); - try_ssl!(ffi::PKCS5_PBKDF2_HMAC(pass.as_ptr(), + try_ssl!(ffi::PKCS5_PBKDF2_HMAC(pass.as_ptr() as *const _, pass.len() as c_int, salt.as_ptr(), salt.len() as c_int, @@ -162,7 +161,6 @@ mod tests { // Test vectors from // https://git.lysator.liu.se/nettle/nettle/blob/nettle_3.1.1_release_20150424/testsuite/pbkdf2-test.c #[test] - #[cfg(feature = "pkcs5_pbkdf2_hmac")] fn test_pbkdf2_hmac_sha256() { assert_eq!(super::pbkdf2_hmac(b"passwd", b"salt", 1, hash::Type::SHA256, 16).unwrap(), vec![0x55_u8, 0xac_u8, 0x04_u8, 0x6e_u8, 0x56_u8, 0xe3_u8, 0x08_u8, 0x9f_u8, @@ -176,7 +174,6 @@ mod tests { // Test vectors from // https://git.lysator.liu.se/nettle/nettle/blob/nettle_3.1.1_release_20150424/testsuite/pbkdf2-test.c #[test] - #[cfg(feature = "pkcs5_pbkdf2_hmac")] fn test_pbkdf2_hmac_sha512() { assert_eq!(super::pbkdf2_hmac(b"password", b"NaCL", 1, hash::Type::SHA512, 64).unwrap(), vec![0x73_u8, 0xde_u8, 0xcf_u8, 0xa5_u8, 0x8a_u8, 0xa2_u8, 0xe8_u8, 0x4f_u8, diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index 8a3f9188..f91f39fb 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -2,7 +2,7 @@ use ffi; use std::fmt; use std::ptr; use std::mem; -use libc::{c_int, c_void, c_char, c_ulong}; +use libc::{c_int, c_void, c_char}; use bn::{BigNum, BigNumRef}; use bio::{MemBio, MemBioSlice}; @@ -44,12 +44,13 @@ impl RSA { /// the supplied load and save methods for DER formatted keys. pub fn from_public_components(n: BigNum, e: BigNum) -> Result { unsafe { - let rsa = try_ssl_null!(ffi::RSA_new()); - (*rsa).n = n.as_ptr(); - (*rsa).e = e.as_ptr(); - mem::forget(n); - mem::forget(e); - Ok(RSA(rsa)) + let rsa = RSA(try_ssl_null!(ffi::RSA_new())); + try_ssl!(compat::set_key(rsa.0, + n.as_ptr(), + e.as_ptr(), + ptr::null_mut())); + mem::forget((n, e)); + Ok(rsa) } } @@ -63,24 +64,15 @@ impl RSA { qi: BigNum) -> Result { unsafe { - let rsa = try_ssl_null!(ffi::RSA_new()); - (*rsa).n = n.as_ptr(); - (*rsa).e = e.as_ptr(); - (*rsa).d = d.as_ptr(); - (*rsa).p = p.as_ptr(); - (*rsa).q = q.as_ptr(); - (*rsa).dmp1 = dp.as_ptr(); - (*rsa).dmq1 = dq.as_ptr(); - (*rsa).iqmp = qi.as_ptr(); - mem::forget(n); - mem::forget(e); - mem::forget(d); - mem::forget(p); - mem::forget(q); - mem::forget(dp); - mem::forget(dq); - mem::forget(qi); - Ok(RSA(rsa)) + let rsa = RSA(try_ssl_null!(ffi::RSA_new())); + try_ssl!(compat::set_key(rsa.0, n.as_ptr(), e.as_ptr(), d.as_ptr())); + mem::forget((n, e, d)); + try_ssl!(compat::set_factors(rsa.0, p.as_ptr(), q.as_ptr())); + mem::forget((p, q)); + try_ssl!(compat::set_crt_params(rsa.0, dp.as_ptr(), dq.as_ptr(), + qi.as_ptr())); + mem::forget((dp, dq, qi)); + Ok(rsa) } } @@ -95,7 +87,7 @@ impl RSA { unsafe { let rsa = try_ssl_null!(ffi::RSA_new()); let rsa = RSA(rsa); - let e = try!(BigNum::new_from(ffi::RSA_F4 as c_ulong)); + let e = try!(BigNum::new_from(ffi::RSA_F4 as u32)); try_ssl!(ffi::RSA_generate_key_ex(rsa.0, bits as c_int, e.as_ptr(), ptr::null_mut())); @@ -292,55 +284,55 @@ impl RSA { pub fn n<'a>(&'a self) -> Option> { unsafe { - let n = (*self.0).n; + let n = compat::key(self.0)[0]; if n.is_null() { None } else { - Some(BigNumRef::from_ptr(n)) + Some(BigNumRef::from_ptr(n as *mut _)) } } } pub fn d<'a>(&self) -> Option> { unsafe { - let d = (*self.0).d; + let d = compat::key(self.0)[2]; if d.is_null() { None } else { - Some(BigNumRef::from_ptr(d)) + Some(BigNumRef::from_ptr(d as *mut _)) } } } pub fn e<'a>(&'a self) -> Option> { unsafe { - let e = (*self.0).e; + let e = compat::key(self.0)[1]; if e.is_null() { None } else { - Some(BigNumRef::from_ptr(e)) + Some(BigNumRef::from_ptr(e as *mut _)) } } } pub fn p<'a>(&'a self) -> Option> { unsafe { - let p = (*self.0).p; + let p = compat::factors(self.0)[0]; if p.is_null() { None } else { - Some(BigNumRef::from_ptr(p)) + Some(BigNumRef::from_ptr(p as *mut _)) } } } pub fn q<'a>(&'a self) -> Option> { unsafe { - let q = (*self.0).q; + let q = compat::factors(self.0)[1]; if q.is_null() { None } else { - Some(BigNumRef::from_ptr(q)) + Some(BigNumRef::from_ptr(q as *mut _)) } } } @@ -352,6 +344,89 @@ impl fmt::Debug for RSA { } } +#[cfg(ossl110)] +mod compat { + use std::ptr; + + use ffi::{self, BIGNUM, RSA}; + use libc::c_int; + + pub unsafe fn key(r: *const RSA) -> [*const BIGNUM; 3] { + let (mut n, mut e, mut d) = (ptr::null(), ptr::null(), ptr::null()); + ffi::RSA_get0_key(r, &mut n, &mut e, &mut d); + [n, e, d] + } + + pub unsafe fn factors(r: *const RSA) -> [*const BIGNUM; 2] { + let (mut p, mut q) = (ptr::null(), ptr::null()); + ffi::RSA_get0_factors(r, &mut p, &mut q); + [p, q] + } + + pub unsafe fn set_key(r: *mut RSA, + n: *mut BIGNUM, + e: *mut BIGNUM, + d: *mut BIGNUM) -> c_int { + ffi::RSA_set0_key(r, n, e, d) + } + + pub unsafe fn set_factors(r: *mut RSA, + p: *mut BIGNUM, + q: *mut BIGNUM) -> c_int { + ffi::RSA_set0_factors(r, p, q) + } + + pub unsafe fn set_crt_params(r: *mut RSA, + dmp1: *mut BIGNUM, + dmq1: *mut BIGNUM, + iqmp: *mut BIGNUM) -> c_int { + ffi::RSA_set0_crt_params(r, dmp1, dmq1, iqmp) + } +} + +#[cfg(ossl10x)] +mod compat { + use libc::c_int; + use ffi::{BIGNUM, RSA}; + + pub unsafe fn key(r: *const RSA) -> [*const BIGNUM; 3] { + [(*r).n, (*r).e, (*r).d] + } + + pub unsafe fn factors(r: *const RSA) -> [*const BIGNUM; 2] { + [(*r).p, (*r).q] + } + + pub unsafe fn set_key(r: *mut RSA, + n: *mut BIGNUM, + e: *mut BIGNUM, + d: *mut BIGNUM) -> c_int { + (*r).n = n; + (*r).e = e; + (*r).d = d; + 1 // TODO: is this right? should it be 0? what's success? + } + + pub unsafe fn set_factors(r: *mut RSA, + p: *mut BIGNUM, + q: *mut BIGNUM) -> c_int { + (*r).p = p; + (*r).q = q; + 1 // TODO: is this right? should it be 0? what's success? + } + + pub unsafe fn set_crt_params(r: *mut RSA, + dmp1: *mut BIGNUM, + dmq1: *mut BIGNUM, + iqmp: *mut BIGNUM) -> c_int { + (*r).dmp1 = dmp1; + (*r).dmq1 = dmq1; + (*r).iqmp = iqmp; + 1 // TODO: is this right? should it be 0? what's success? + } +} + + #[cfg(test)] mod test { use std::io::Write; @@ -449,9 +524,9 @@ mod test { #[test] fn test_private_encrypt() { - let mut k0 = super::RSA::generate(512).unwrap(); + let k0 = super::RSA::generate(512).unwrap(); let k0pkey = k0.public_key_to_pem().unwrap(); - let mut k1 = super::RSA::public_key_from_pem(&k0pkey).unwrap(); + let k1 = super::RSA::public_key_from_pem(&k0pkey).unwrap(); let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); @@ -462,9 +537,9 @@ mod test { #[test] fn test_public_encrypt() { - let mut k0 = super::RSA::generate(512).unwrap(); + let k0 = super::RSA::generate(512).unwrap(); let k0pkey = k0.public_key_to_pem().unwrap(); - let mut k1 = super::RSA::public_key_from_pem(&k0pkey).unwrap(); + let k1 = super::RSA::public_key_from_pem(&k0pkey).unwrap(); let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); @@ -475,9 +550,9 @@ mod test { #[test] fn test_public_encrypt_pkcs() { - let mut k0 = super::RSA::generate(512).unwrap(); + let k0 = super::RSA::generate(512).unwrap(); let k0pkey = k0.public_key_to_pem().unwrap(); - let mut k1 = super::RSA::public_key_from_pem(&k0pkey).unwrap(); + let k1 = super::RSA::public_key_from_pem(&k0pkey).unwrap(); let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); diff --git a/openssl/src/crypto/symm.rs b/openssl/src/crypto/symm.rs index 93764e4d..c4021338 100644 --- a/openssl/src/crypto/symm.rs +++ b/openssl/src/crypto/symm.rs @@ -81,7 +81,7 @@ impl Type { /// Returns the length of keys used with this cipher. pub fn key_len(&self) -> usize { unsafe { - ffi::EVP_CIPHER_key_length(self.as_ptr()) as usize + EVP_CIPHER_key_length(self.as_ptr()) as usize } } @@ -89,7 +89,7 @@ impl Type { /// cipher does not use an IV. pub fn iv_len(&self) -> Option { unsafe { - let len = ffi::EVP_CIPHER_iv_length(self.as_ptr()) as usize; + let len = EVP_CIPHER_iv_length(self.as_ptr()) as usize; if len == 0 { None } else { @@ -105,7 +105,7 @@ impl Type { /// Stream ciphers such as RC4 have a block size of 1. pub fn block_size(&self) -> usize { unsafe { - ffi::EVP_CIPHER_block_size(self.as_ptr()) as usize + EVP_CIPHER_block_size(self.as_ptr()) as usize } } } @@ -272,6 +272,30 @@ fn cipher(t: Type, Ok(out) } +#[cfg(ossl110)] +use ffi::{EVP_CIPHER_iv_length, EVP_CIPHER_block_size, EVP_CIPHER_key_length}; + +#[cfg(ossl10x)] +#[allow(bad_style)] +mod compat { + use libc::c_int; + use ffi::EVP_CIPHER; + + pub unsafe fn EVP_CIPHER_iv_length(ptr: *const EVP_CIPHER) -> c_int { + (*ptr).iv_len + } + + pub unsafe fn EVP_CIPHER_block_size(ptr: *const EVP_CIPHER) -> c_int { + (*ptr).block_size + } + + pub unsafe fn EVP_CIPHER_key_length(ptr: *const EVP_CIPHER) -> c_int { + (*ptr).key_len + } +} +#[cfg(ossl10x)] +use self::compat::*; + #[cfg(test)] mod tests { use serialize::hex::{FromHex, ToHex}; diff --git a/openssl/src/dh/mod.rs b/openssl/src/dh/mod.rs index e0cf885a..4ee2d890 100644 --- a/openssl/src/dh/mod.rs +++ b/openssl/src/dh/mod.rs @@ -3,24 +3,22 @@ use error::ErrorStack; use bio::MemBioSlice; use std::ptr; -#[cfg(feature = "dh_from_params")] use bn::BigNum; -#[cfg(feature = "dh_from_params")] use std::mem; pub struct DH(*mut ffi::DH); impl DH { - /// Requires the `dh_from_params` feature. - #[cfg(feature = "dh_from_params")] pub fn from_params(p: BigNum, g: BigNum, q: BigNum) -> Result { - let dh = unsafe { - try_ssl_null!(::c_helpers::rust_0_8_DH_new_from_params(p.as_ptr(), g.as_ptr(), q.as_ptr())) - }; - mem::forget(p); - mem::forget(g); - mem::forget(q); - Ok(DH(dh)) + unsafe { + let dh = DH(try_ssl_null!(ffi::DH_new())); + try_ssl!(compat::DH_set0_pqg(dh.0, + p.as_ptr(), + q.as_ptr(), + g.as_ptr())); + mem::forget((p, g, q)); + Ok(dh) + } } pub fn from_pem(buf: &[u8]) -> Result { @@ -32,19 +30,19 @@ impl DH { Ok(DH(dh)) } - #[cfg(feature = "rfc5114")] + #[cfg(all(feature = "rfc5114", not(ossl101)))] pub fn get_1024_160() -> Result { let dh = try_ssl_null!(unsafe { ffi::DH_get_1024_160() }); Ok(DH(dh)) } - #[cfg(feature = "rfc5114")] + #[cfg(all(feature = "rfc5114", not(ossl101)))] pub fn get_2048_224() -> Result { let dh = try_ssl_null!(unsafe { ffi::DH_get_2048_224() }); Ok(DH(dh)) } - #[cfg(feature = "rfc5114")] + #[cfg(all(feature = "rfc5114", not(ossl101)))] pub fn get_2048_256() -> Result { let dh = try_ssl_null!(unsafe { ffi::DH_get_2048_256() }); Ok(DH(dh)) @@ -64,17 +62,39 @@ impl Drop for DH { } } +#[cfg(ossl110)] +mod compat { + pub use ffi::DH_set0_pqg; +} + +#[cfg(ossl10x)] +#[allow(bad_style)] +mod compat { + use ffi; + use libc::c_int; + + pub unsafe fn DH_set0_pqg(dh: *mut ffi::DH, + p: *mut ffi::BIGNUM, + q: *mut ffi::BIGNUM, + g: *mut ffi::BIGNUM) -> c_int { + (*dh).p = p; + (*dh).q = q; + (*dh).g = g; + 1 + } +} + #[cfg(test)] mod tests { use super::DH; use bn::BigNum; use ssl::SslContext; - use ssl::SslMethod::Sslv23; + use ssl::SslMethod::Tls; #[test] - #[cfg(feature = "rfc5114")] + #[cfg(all(feature = "rfc5114", not(ossl101)))] fn test_dh_rfc5114() { - let mut ctx = SslContext::new(Sslv23).unwrap(); + let mut ctx = SslContext::new(Tls).unwrap(); let dh1 = DH::get_1024_160().unwrap(); ctx.set_tmp_dh(&dh1).unwrap(); let dh2 = DH::get_2048_224().unwrap(); @@ -84,9 +104,8 @@ mod tests { } #[test] - #[cfg(feature = "dh_from_params")] fn test_dh() { - let mut ctx = SslContext::new(Sslv23).unwrap(); + let mut ctx = SslContext::new(Tls).unwrap(); let p = BigNum::from_hex_str("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435\ E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF429\ 6D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C02\ @@ -116,7 +135,7 @@ mod tests { #[test] fn test_dh_from_pem() { - let mut ctx = SslContext::new(Sslv23).unwrap(); + let mut ctx = SslContext::new(Tls).unwrap(); let params = include_bytes!("../../test/dhparams.pem"); let dh = DH::from_pem(params).ok().expect("Failed to load PEM"); ctx.set_tmp_dh(&dh).unwrap(); diff --git a/openssl/src/error.rs b/openssl/src/error.rs index d76e7cbd..f54d7bda 100644 --- a/openssl/src/error.rs +++ b/openssl/src/error.rs @@ -71,7 +71,7 @@ impl Error { match unsafe { ffi::ERR_get_error() } { 0 => None, - err => Some((Error(err))), + err => Some(Error(err)), } } @@ -121,6 +121,7 @@ impl error::Error for Error { fn get_lib(err: c_ulong) -> &'static str { unsafe { let cstr = ffi::ERR_lib_error_string(err); + assert!(!cstr.is_null(), "bad lib: {}", err); let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); str::from_utf8(bytes).unwrap() } @@ -129,6 +130,7 @@ fn get_lib(err: c_ulong) -> &'static str { fn get_func(err: c_ulong) -> &'static str { unsafe { let cstr = ffi::ERR_func_error_string(err); + assert!(!cstr.is_null(), "bad func: {}", err); let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); str::from_utf8(bytes).unwrap() } @@ -137,6 +139,7 @@ fn get_func(err: c_ulong) -> &'static str { fn get_reason(err: c_ulong) -> &'static str { unsafe { let cstr = ffi::ERR_reason_error_string(err); + assert!(!cstr.is_null(), "bad reason: {}", err); let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); str::from_utf8(bytes).unwrap() } diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index 879681f4..66c767dc 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -13,6 +13,9 @@ extern crate rustc_serialize as serialize; #[cfg(test)] extern crate net2; +#[cfg(test)] +extern crate tempdir; + #[doc(inline)] pub use ffi::init; @@ -23,8 +26,6 @@ mod macros; pub mod asn1; mod bio; pub mod bn; -#[cfg(feature = "c_helpers")] -mod c_helpers; pub mod crypto; pub mod dh; pub mod error; diff --git a/openssl/src/macros.rs b/openssl/src/macros.rs index e2d9cae5..31c298fa 100644 --- a/openssl/src/macros.rs +++ b/openssl/src/macros.rs @@ -80,3 +80,17 @@ macro_rules! lift_ssl_returns_size { } }) } + +#[cfg(ossl10x)] +macro_rules! CRYPTO_free { + ($e:expr) => (::ffi::CRYPTO_free($e)) +} + +#[cfg(ossl110)] +macro_rules! CRYPTO_free { + ($e:expr) => ( + ::ffi::CRYPTO_free($e, + concat!(file!(), "\0").as_ptr() as *const _, + line!() as i32) + ) +} diff --git a/openssl/src/ssl/bio.rs b/openssl/src/ssl/bio.rs index c5663eb1..ccf3a472 100644 --- a/openssl/src/ssl/bio.rs +++ b/openssl/src/ssl/bio.rs @@ -1,5 +1,5 @@ use libc::{c_char, c_int, c_long, c_void, strlen}; -use ffi::{self, BIO, BIO_CTRL_FLUSH, BIO_TYPE_NONE, BIO_new, BIO_clear_retry_flags, +use ffi::{BIO, BIO_CTRL_FLUSH, BIO_new, BIO_clear_retry_flags, BIO_set_retry_read, BIO_set_retry_write}; use std::any::Any; use std::io; @@ -18,22 +18,11 @@ pub struct StreamState { } /// Safe wrapper for BIO_METHOD -pub struct BioMethod(ffi::BIO_METHOD); +pub struct BioMethod(compat::BIO_METHOD); impl BioMethod { pub fn new() -> BioMethod { - BioMethod(ffi::BIO_METHOD { - type_: BIO_TYPE_NONE, - name: b"rust\0".as_ptr() as *const _, - bwrite: Some(bwrite::), - bread: Some(bread::), - bputs: Some(bputs::), - bgets: None, - ctrl: Some(ctrl::), - create: Some(create), - destroy: Some(destroy::), - callback_ctrl: None, - }) + BioMethod(compat::BIO_METHOD::new::()) } } @@ -49,9 +38,9 @@ pub fn new(stream: S) -> Result<(*mut BIO, Arc), Err }); unsafe { - let bio = try_ssl_null!(BIO_new(&method.0)); - (*bio).ptr = Box::into_raw(state) as *mut _; - (*bio).init = 1; + let bio = try_ssl_null!(BIO_new(method.0.get())); + compat::BIO_set_data(bio, Box::into_raw(state) as *mut _); + compat::BIO_set_init(bio, 1); return Ok((bio, method)); } @@ -62,14 +51,13 @@ pub unsafe fn take_error(bio: *mut BIO) -> Option { state.error.take() } -#[cfg_attr(not(feature = "nightly"), allow(dead_code))] pub unsafe fn take_panic(bio: *mut BIO) -> Option> { let state = state::(bio); state.panic.take() } pub unsafe fn get_ref<'a, S: 'a>(bio: *mut BIO) -> &'a S { - let state: &'a StreamState = mem::transmute((*bio).ptr); + let state: &'a StreamState = mem::transmute(compat::BIO_get_data(bio)); &state.stream } @@ -78,24 +66,16 @@ pub unsafe fn get_mut<'a, S: 'a>(bio: *mut BIO) -> &'a mut S { } unsafe fn state<'a, S: 'a>(bio: *mut BIO) -> &'a mut StreamState { - mem::transmute((*bio).ptr) + mem::transmute(compat::BIO_get_data(bio)) } -#[cfg(feature = "nightly")] fn catch_unwind(f: F) -> Result> where F: FnOnce() -> T { ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(f)) } -#[cfg(not(feature = "nightly"))] -fn catch_unwind(f: F) -> Result> - where F: FnOnce() -> T -{ - Ok(f()) -} - -unsafe extern "C" fn bwrite(bio: *mut BIO, buf: *const c_char, len: c_int) -> c_int { +unsafe extern fn bwrite(bio: *mut BIO, buf: *const c_char, len: c_int) -> c_int { BIO_clear_retry_flags(bio); let state = state::(bio); @@ -117,7 +97,7 @@ unsafe extern "C" fn bwrite(bio: *mut BIO, buf: *const c_char, len: c_ } } -unsafe extern "C" fn bread(bio: *mut BIO, buf: *mut c_char, len: c_int) -> c_int { +unsafe extern fn bread(bio: *mut BIO, buf: *mut c_char, len: c_int) -> c_int { BIO_clear_retry_flags(bio); let state = state::(bio); @@ -147,15 +127,15 @@ fn retriable_error(err: &io::Error) -> bool { } } -unsafe extern "C" fn bputs(bio: *mut BIO, s: *const c_char) -> c_int { +unsafe extern fn bputs(bio: *mut BIO, s: *const c_char) -> c_int { bwrite::(bio, s, strlen(s) as c_int) } -unsafe extern "C" fn ctrl(bio: *mut BIO, - cmd: c_int, - _num: c_long, - _ptr: *mut c_void) - -> c_long { +unsafe extern fn ctrl(bio: *mut BIO, + cmd: c_int, + _num: c_long, + _ptr: *mut c_void) + -> c_long { if cmd == BIO_CTRL_FLUSH { let state = state::(bio); @@ -175,22 +155,126 @@ unsafe extern "C" fn ctrl(bio: *mut BIO, } } -unsafe extern "C" fn create(bio: *mut BIO) -> c_int { - (*bio).init = 0; - (*bio).num = 0; - (*bio).ptr = ptr::null_mut(); - (*bio).flags = 0; +unsafe extern fn create(bio: *mut BIO) -> c_int { + compat::BIO_set_init(bio, 0); + compat::BIO_set_num(bio, 0); + compat::BIO_set_data(bio, ptr::null_mut()); + compat::BIO_set_flags(bio, 0); 1 } -unsafe extern "C" fn destroy(bio: *mut BIO) -> c_int { +unsafe extern fn destroy(bio: *mut BIO) -> c_int { if bio.is_null() { return 0; } - assert!(!(*bio).ptr.is_null()); - Box::>::from_raw((*bio).ptr as *mut _); - (*bio).ptr = ptr::null_mut(); - (*bio).init = 0; + let data = compat::BIO_get_data(bio); + assert!(!data.is_null()); + Box::>::from_raw(data as *mut _); + compat::BIO_set_data(bio, ptr::null_mut()); + compat::BIO_set_init(bio, 0); 1 } + +#[cfg(ossl110)] +#[allow(bad_style)] +mod compat { + use std::io::{Read, Write}; + + use libc::c_int; + use ffi; + pub use ffi::{BIO_set_init, BIO_set_flags, BIO_set_data, BIO_get_data}; + + pub unsafe fn BIO_set_num(_bio: *mut ffi::BIO, _num: c_int) {} + + pub struct BIO_METHOD { + inner: *mut ffi::BIO_METHOD, + } + + impl BIO_METHOD { + pub fn new() -> BIO_METHOD { + unsafe { + let ptr = ffi::BIO_meth_new(ffi::BIO_TYPE_NONE, + b"rust\0".as_ptr() as *const _); + assert!(!ptr.is_null()); + let ret = BIO_METHOD { inner: ptr }; + assert!(ffi::BIO_meth_set_write(ptr, super::bwrite::) != 0); + assert!(ffi::BIO_meth_set_read(ptr, super::bread::) != 0); + assert!(ffi::BIO_meth_set_puts(ptr, super::bputs::) != 0); + assert!(ffi::BIO_meth_set_ctrl(ptr, super::ctrl::) != 0); + assert!(ffi::BIO_meth_set_create(ptr, super::create) != 0); + assert!(ffi::BIO_meth_set_destroy(ptr, super::destroy::) != 0); + return ret + } + } + + pub fn get(&self) -> *mut ffi::BIO_METHOD { + self.inner + } + } + + impl Drop for BIO_METHOD { + fn drop(&mut self) { + unsafe { + ffi::BIO_meth_free(self.inner); + } + } + } +} + +#[cfg(ossl10x)] +#[allow(bad_style)] +mod compat { + use std::io::{Read, Write}; + use std::cell::UnsafeCell; + + use ffi; + use libc::{c_int, c_void}; + + pub struct BIO_METHOD { + inner: UnsafeCell, + } + + impl BIO_METHOD { + pub fn new() -> BIO_METHOD { + BIO_METHOD { + inner: UnsafeCell::new(ffi::BIO_METHOD { + type_: ffi::BIO_TYPE_NONE, + name: b"rust\0".as_ptr() as *const _, + bwrite: Some(super::bwrite::), + bread: Some(super::bread::), + bputs: Some(super::bputs::), + bgets: None, + ctrl: Some(super::ctrl::), + create: Some(super::create), + destroy: Some(super::destroy::), + callback_ctrl: None, + }), + } + } + + pub fn get(&self) -> *mut ffi::BIO_METHOD { + self.inner.get() + } + } + + pub unsafe fn BIO_set_init(bio: *mut ffi::BIO, init: c_int) { + (*bio).init = init; + } + + pub unsafe fn BIO_set_flags(bio: *mut ffi::BIO, flags: c_int) { + (*bio).flags = flags; + } + + pub unsafe fn BIO_get_data(bio: *mut ffi::BIO) -> *mut c_void { + (*bio).ptr + } + + pub unsafe fn BIO_set_data(bio: *mut ffi::BIO, data: *mut c_void) { + (*bio).ptr = data; + } + + pub unsafe fn BIO_set_num(bio: *mut ffi::BIO, num: c_int) { + (*bio).num = num; + } +} diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 6e365af6..51bfc790 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -1,4 +1,4 @@ -use libc::{c_int, c_void, c_long}; +use libc::{c_int, c_void, c_long, c_ulong}; use std::any::Any; use std::any::TypeId; use std::cmp; @@ -38,12 +38,11 @@ use self::bio::BioMethod; pub use ssl::error::Error; bitflags! { - pub flags SslContextOptions: c_long { + pub flags SslContextOptions: c_ulong { const SSL_OP_MICROSOFT_SESS_ID_BUG = ffi::SSL_OP_MICROSOFT_SESS_ID_BUG, const SSL_OP_NETSCAPE_CHALLENGE_BUG = ffi::SSL_OP_NETSCAPE_CHALLENGE_BUG, const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = ffi::SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG, - const SSL_OP_TLSEXT_PADDING = ffi::SSL_OP_TLSEXT_PADDING, const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER = ffi::SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER, const SSL_OP_SSLEAY_080_CLIENT_DH_BUG = ffi::SSL_OP_SSLEAY_080_CLIENT_DH_BUG, const SSL_OP_TLS_D5_BUG = ffi::SSL_OP_TLS_D5_BUG, @@ -73,74 +72,11 @@ bitflags! { #[allow(non_camel_case_types)] #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] pub enum SslMethod { - #[cfg(feature = "sslv2")] - /// Only support the SSLv2 protocol, requires the `sslv2` feature. - Sslv2, - /// Support the SSLv2, SSLv3, TLSv1, TLSv1.1, and TLSv1.2 protocols depending on what the - /// linked OpenSSL library supports. - Sslv23, - #[cfg(feature = "sslv3")] - /// Only support the SSLv3 protocol. - Sslv3, - /// Only support the TLSv1 protocol. - Tlsv1, - #[cfg(feature = "tlsv1_1")] - /// Support TLSv1.1 protocol, requires the `tlsv1_1` feature. - Tlsv1_1, - #[cfg(feature = "tlsv1_2")] - /// Support TLSv1.2 protocol, requires the `tlsv1_2` feature. - Tlsv1_2, - #[cfg(feature = "dtlsv1")] - /// Support DTLSv1 protocol, requires the `dtlsv1` feature. - Dtlsv1, - #[cfg(feature = "dtlsv1_2")] - /// Support DTLSv1.2 protocol, requires the `dtlsv1_2` feature. - Dtlsv1_2, -} - -impl SslMethod { - fn to_raw(&self) -> *const ffi::SSL_METHOD { - unsafe { - match *self { - #[cfg(feature = "sslv2")] - SslMethod::Sslv2 => ffi::SSLv2_method(), - #[cfg(feature = "sslv3")] - SslMethod::Sslv3 => ffi::SSLv3_method(), - SslMethod::Tlsv1 => ffi::TLSv1_method(), - SslMethod::Sslv23 => ffi::SSLv23_method(), - #[cfg(feature = "tlsv1_1")] - SslMethod::Tlsv1_1 => ffi::TLSv1_1_method(), - #[cfg(feature = "tlsv1_2")] - SslMethod::Tlsv1_2 => ffi::TLSv1_2_method(), - #[cfg(feature = "dtlsv1")] - SslMethod::Dtlsv1 => ffi::DTLSv1_method(), - #[cfg(feature = "dtlsv1_2")] - SslMethod::Dtlsv1_2 => ffi::DTLSv1_2_method(), - } - } - } - - fn from_raw(method: *const ffi::SSL_METHOD) -> Option { - unsafe { - match method { - #[cfg(feature = "sslv2")] - x if x == ffi::SSLv2_method() => Some(SslMethod::Sslv2), - #[cfg(feature = "sslv3")] - x if x == ffi::SSLv3_method() => Some(SslMethod::Sslv3), - x if x == ffi::TLSv1_method() => Some(SslMethod::Tlsv1), - x if x == ffi::SSLv23_method() => Some(SslMethod::Sslv23), - #[cfg(feature = "tlsv1_1")] - x if x == ffi::TLSv1_1_method() => Some(SslMethod::Tlsv1_1), - #[cfg(feature = "tlsv1_2")] - x if x == ffi::TLSv1_2_method() => Some(SslMethod::Tlsv1_2), - #[cfg(feature = "dtlsv1")] - x if x == ffi::DTLSv1_method() => Some(SslMethod::Dtlsv1), - #[cfg(feature = "dtlsv1_2")] - x if x == ffi::DTLSv1_2_method() => Some(SslMethod::Dtlsv1_2), - _ => None, - } - } - } + // TODO: support more methods + /// Support the TLS protocol + Tls, + /// Support DTLS protocol + Dtls, } /// Determines the type of certificate verification used @@ -172,11 +108,11 @@ fn get_ssl_verify_data_idx() -> c_int { *SSL_INDEXES.lock().unwrap().entry(TypeId::of::()).or_insert_with(|| get_new_ssl_idx::()) } -#[cfg(feature = "npn")] +#[cfg(all(feature = "npn", not(ossl101)))] lazy_static! { static ref NPN_PROTOS_IDX: c_int = get_new_idx::>(); } -#[cfg(feature = "alpn")] +#[cfg(all(feature = "alpn", not(ossl101)))] lazy_static! { static ref ALPN_PROTOS_IDX: c_int = get_new_idx::>(); } @@ -184,52 +120,50 @@ lazy_static! { /// Determine a new index to use for SSL CTX ex data. /// Registers a destruct for the data which will be called by openssl when the context is freed. fn get_new_idx() -> c_int { - extern "C" fn free_data_box(_parent: *mut c_void, - ptr: *mut c_void, - _ad: *mut ffi::CRYPTO_EX_DATA, - _idx: c_int, - _argl: c_long, - _argp: *mut c_void) { + extern fn free_data_box(_parent: *mut c_void, + ptr: *mut c_void, + _ad: *mut ffi::CRYPTO_EX_DATA, + _idx: c_int, + _argl: c_long, + _argp: *mut c_void) { if !ptr.is_null() { let _: Box = unsafe { mem::transmute(ptr) }; } } unsafe { - let f: ffi::CRYPTO_EX_free = free_data_box::; - let idx = ffi::SSL_CTX_get_ex_new_index(0, ptr::null(), None, None, Some(f)); + let idx = compat::get_new_idx(free_data_box::); assert!(idx >= 0); idx } } fn get_new_ssl_idx() -> c_int { - extern "C" fn free_data_box(_parent: *mut c_void, - ptr: *mut c_void, - _ad: *mut ffi::CRYPTO_EX_DATA, - _idx: c_int, - _argl: c_long, - _argp: *mut c_void) { + extern fn free_data_box(_parent: *mut c_void, + ptr: *mut c_void, + _ad: *mut ffi::CRYPTO_EX_DATA, + _idx: c_int, + _argl: c_long, + _argp: *mut c_void) { if !ptr.is_null() { let _: Box = unsafe { mem::transmute(ptr) }; } } unsafe { - let f: ffi::CRYPTO_EX_free = free_data_box::; - let idx = ffi::SSL_get_ex_new_index(0, ptr::null(), None, None, Some(f)); + let idx = compat::get_new_ssl_idx(free_data_box::); assert!(idx >= 0); idx } } -extern "C" fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int +extern fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int where F: Fn(bool, &X509StoreContext) -> bool + Any + 'static + Sync + Send { unsafe { let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx(); let ssl = ffi::X509_STORE_CTX_get_ex_data(x509_ctx, idx); - let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); + let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); let verify = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_verify_data_idx::()); let verify: &F = mem::transmute(verify); @@ -239,13 +173,14 @@ extern "C" fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_ } } -extern "C" fn ssl_raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int +extern fn ssl_raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int where F: Fn(bool, &X509StoreContext) -> bool + Any + 'static + Sync + Send { unsafe { let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx(); let ssl = ffi::X509_STORE_CTX_get_ex_data(x509_ctx, idx); - let verify = ffi::SSL_get_ex_data(ssl, get_ssl_verify_data_idx::()); + let verify = ffi::SSL_get_ex_data(ssl as *const _, + get_ssl_verify_data_idx::()); let verify: &F = mem::transmute(verify); let ctx = X509StoreContext::new(x509_ctx); @@ -254,7 +189,7 @@ extern "C" fn ssl_raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_ST } } -extern "C" fn raw_sni(ssl: *mut ffi::SSL, al: *mut c_int, _arg: *mut c_void) -> c_int +extern fn raw_sni(ssl: *mut ffi::SSL, al: *mut c_int, _arg: *mut c_void) -> c_int where F: Fn(&mut SslRef) -> Result<(), SniError> + Any + 'static + Sync + Send { unsafe { @@ -278,7 +213,7 @@ extern "C" fn raw_sni(ssl: *mut ffi::SSL, al: *mut c_int, _arg: *mut c_void) } } -#[cfg(any(feature = "npn", feature = "alpn"))] +#[cfg(all(any(feature = "npn", feature = "alpn"), not(ossl101)))] unsafe fn select_proto_using(ssl: *mut ffi::SSL, out: *mut *mut c_uchar, outlen: *mut c_uchar, @@ -311,26 +246,26 @@ unsafe fn select_proto_using(ssl: *mut ffi::SSL, /// supported by the server. It achieves this by delegating to the `SSL_select_next_proto` /// function. The list of protocols supported by the client is found in the extra data of the /// OpenSSL context. -#[cfg(feature = "npn")] -extern "C" fn raw_next_proto_select_cb(ssl: *mut ffi::SSL, - out: *mut *mut c_uchar, - outlen: *mut c_uchar, - inbuf: *const c_uchar, - inlen: c_uint, - _arg: *mut c_void) - -> c_int { +#[cfg(all(feature = "npn", not(ossl101)))] +extern fn raw_next_proto_select_cb(ssl: *mut ffi::SSL, + out: *mut *mut c_uchar, + outlen: *mut c_uchar, + inbuf: *const c_uchar, + inlen: c_uint, + _arg: *mut c_void) + -> c_int { unsafe { select_proto_using(ssl, out, outlen, inbuf, inlen, *NPN_PROTOS_IDX) } } -#[cfg(feature = "alpn")] -extern "C" fn raw_alpn_select_cb(ssl: *mut ffi::SSL, - out: *mut *mut c_uchar, - outlen: *mut c_uchar, - inbuf: *const c_uchar, - inlen: c_uint, - _arg: *mut c_void) - -> c_int { - unsafe { select_proto_using(ssl, out, outlen, inbuf, inlen, *ALPN_PROTOS_IDX) } +#[cfg(all(feature = "alpn", not(ossl101)))] +extern fn raw_alpn_select_cb(ssl: *mut ffi::SSL, + out: *mut *const c_uchar, + outlen: *mut c_uchar, + inbuf: *const c_uchar, + inlen: c_uint, + _arg: *mut c_void) + -> c_int { + unsafe { select_proto_using(ssl, out as *mut _, outlen, inbuf, inlen, *ALPN_PROTOS_IDX) } } /// The function is given as the callback to `SSL_CTX_set_next_protos_advertised_cb`. @@ -340,12 +275,12 @@ extern "C" fn raw_alpn_select_cb(ssl: *mut ffi::SSL, /// that it supports. /// The list of supported protocols is found in the extra data of the OpenSSL /// context. -#[cfg(feature = "npn")] -extern "C" fn raw_next_protos_advertise_cb(ssl: *mut ffi::SSL, - out: *mut *const c_uchar, - outlen: *mut c_uint, - _arg: *mut c_void) - -> c_int { +#[cfg(all(feature = "npn", not(ossl101)))] +extern fn raw_next_protos_advertise_cb(ssl: *mut ffi::SSL, + out: *mut *const c_uchar, + outlen: *mut c_uint, + _arg: *mut c_void) + -> c_int { unsafe { // First, get the list of (supported) protocols saved in the context extra data. let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); @@ -367,7 +302,7 @@ extern "C" fn raw_next_protos_advertise_cb(ssl: *mut ffi::SSL, /// Convert a set of byte slices into a series of byte strings encoded for SSL. Encoding is a byte /// containing the length followed by the string. -#[cfg(any(feature = "npn", feature = "alpn"))] +#[cfg(all(any(feature = "alpn", feature = "npn"), not(ossl101)))] fn ssl_encode_byte_strings(strings: &[&[u8]]) -> Vec { let mut enc = Vec::new(); for string in strings { @@ -442,8 +377,8 @@ impl<'a> SslContextRef<'a> { ffi::SSL_CTX_set_ex_data(self.as_ptr(), get_verify_data_idx::(), mem::transmute(callback)); - let f: extern "C" fn(_, _, _) -> _ = raw_sni::; - let f: extern "C" fn() = mem::transmute(f); + let f: extern fn(_, _, _) -> _ = raw_sni::; + let f: extern fn() = mem::transmute(f); ffi::SSL_CTX_set_tlsext_servername_callback(self.as_ptr(), Some(f)); } } @@ -515,15 +450,12 @@ impl<'a> SslContextRef<'a> { } /// Specifies the file that contains certificate chain - pub fn set_certificate_chain_file>(&mut self, - file: P, - file_type: X509FileType) + pub fn set_certificate_chain_file>(&mut self, file: P) -> Result<(), ErrorStack> { let file = CString::new(file.as_ref().as_os_str().to_str().expect("invalid utf8")).unwrap(); wrap_ssl_result(unsafe { ffi::SSL_CTX_use_certificate_chain_file(self.as_ptr(), - file.as_ptr() as *const _, - file_type as c_int) + file.as_ptr() as *const _) }) } @@ -575,27 +507,44 @@ impl<'a> SslContextRef<'a> { }) } - /// If `onoff` is set to `true`, enable ECDHE for key exchange with compatible - /// clients, and automatically select an appropriate elliptic curve. + /// If `onoff` is set to `true`, enable ECDHE for key exchange with + /// compatible clients, and automatically select an appropriate elliptic + /// curve. /// - /// This method requires OpenSSL >= 1.0.2 or LibreSSL and the `ecdh_auto` feature. - #[cfg(feature = "ecdh_auto")] + /// This method requires OpenSSL >= 1.0.2 or LibreSSL and the `ecdh_auto` + /// feature. + #[cfg(all(feature = "ecdh_auto", not(ossl101)))] pub fn set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> { - wrap_ssl_result(unsafe { ffi::SSL_CTX_set_ecdh_auto(self.as_ptr(), onoff as c_long) as c_int }) + self._set_ecdh_auto(onoff) + } + + #[cfg(all(feature = "ecdh_auto", ossl102))] + fn _set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> { + wrap_ssl_result(unsafe { + ffi::SSL_CTX_ctrl(self.as_ptr(), + ffi::SSL_CTRL_SET_ECDH_AUTO, + onoff as c_long, + ptr::null_mut()) as c_int + }) + } + + #[cfg(all(feature = "ecdh_auto", ossl110))] + fn _set_ecdh_auto(&mut self, _onoff: bool) -> Result<(), ErrorStack> { + Ok(()) } pub fn set_options(&mut self, option: SslContextOptions) -> SslContextOptions { - let ret = unsafe { ffi::SSL_CTX_set_options(self.as_ptr(), option.bits()) }; + let ret = unsafe { compat::SSL_CTX_set_options(self.as_ptr(), option.bits()) }; SslContextOptions::from_bits(ret).unwrap() } pub fn options(&self) -> SslContextOptions { - let ret = unsafe { ffi::SSL_CTX_get_options(self.as_ptr()) }; + let ret = unsafe { compat::SSL_CTX_get_options(self.as_ptr()) }; SslContextOptions::from_bits(ret).unwrap() } pub fn clear_options(&mut self, option: SslContextOptions) -> SslContextOptions { - let ret = unsafe { ffi::SSL_CTX_clear_options(self.as_ptr(), option.bits()) }; + let ret = unsafe { compat::SSL_CTX_clear_options(self.as_ptr(), option.bits()) }; SslContextOptions::from_bits(ret).unwrap() } @@ -603,7 +552,7 @@ impl<'a> SslContextRef<'a> { /// supported by the application). /// /// This method needs the `npn` feature. - #[cfg(feature = "npn")] + #[cfg(all(feature = "npn", not(ossl101)))] pub fn set_npn_protocols(&mut self, protocols: &[&[u8]]) { // Firstly, convert the list of protocols to a byte-array that can be passed to OpenSSL // APIs -- a list of length-prefixed strings. @@ -635,7 +584,7 @@ impl<'a> SslContextRef<'a> { /// Note that ordering of the protocols controls the priority with which they are chosen. /// /// This method needs the `alpn` feature. - #[cfg(feature = "alpn")] + #[cfg(all(feature = "alpn", not(ossl101)))] pub fn set_alpn_protocols(&mut self, protocols: &[&[u8]]) { let protocols: Box> = Box::new(ssl_encode_byte_strings(protocols)); unsafe { @@ -662,12 +611,10 @@ pub struct SslContext(SslContextRef<'static>); unsafe impl Send for SslContext {} unsafe impl Sync for SslContext {} -#[cfg(feature = "ssl_context_clone")] impl Clone for SslContext { - /// Requires the `ssl_context_clone` feature. fn clone(&self) -> Self { unsafe { - ::c_helpers::rust_0_8_SSL_CTX_clone(self.as_ptr()); + compat::SSL_CTX_up_ref(self.as_ptr()); SslContext::from_ptr(self.as_ptr()) } } @@ -706,15 +653,13 @@ impl SslContext { init(); let mut ctx = unsafe { - let ctx = try_ssl_null!(ffi::SSL_CTX_new(method.to_raw())); + let method = compat::get_method(method); + let ctx = try_ssl_null!(ffi::SSL_CTX_new(method)); SslContext::from_ptr(ctx) }; match method { - #[cfg(feature = "dtlsv1")] - SslMethod::Dtlsv1 => ctx.set_read_ahead(1), - #[cfg(feature = "dtlsv1_2")] - SslMethod::Dtlsv1_2 => ctx.set_read_ahead(1), + SslMethod::Dtls => ctx.set_read_ahead(1), _ => {} } // this is a bit dubious (?) @@ -982,7 +927,7 @@ impl<'a> SslRef<'a> { /// to interpret it. /// /// This method needs the `alpn` feature. - #[cfg(feature = "alpn")] + #[cfg(all(feature = "alpn", not(ossl101)))] pub fn selected_alpn_protocol(&self) -> Option<&[u8]> { unsafe { let mut data: *const c_uchar = ptr::null(); @@ -1023,13 +968,6 @@ impl<'a> SslRef<'a> { Some(s) } - pub fn ssl_method(&self) -> SslMethod { - unsafe { - let method = ffi::SSL_get_ssl_method(self.as_ptr()); - SslMethod::from_raw(method).unwrap() - } - } - /// Returns the server's name for the current connection pub fn servername(&self) -> Option { let name = unsafe { ffi::SSL_get_servername(self.as_ptr(), ffi::TLSEXT_NAMETYPE_host_name) }; @@ -1319,16 +1257,12 @@ impl SslStream { } } - #[cfg(feature = "nightly")] fn check_panic(&mut self) { if let Some(err) = unsafe { bio::take_panic::(self.ssl.get_raw_rbio()) } { ::std::panic::resume_unwind(err) } } - #[cfg(not(feature = "nightly"))] - fn check_panic(&mut self) {} - fn get_bio_error(&mut self) -> io::Error { let error = unsafe { bio::take_error::(self.ssl.get_raw_rbio()) }; match error { @@ -1412,3 +1346,107 @@ impl<'a> IntoSsl for &'a SslContext { Ssl::new(self) } } + +#[cfg(ossl110)] +mod compat { + use std::ptr; + + use ffi; + use libc::c_int; + + pub use ffi::{SSL_CTX_get_options, SSL_CTX_set_options}; + pub use ffi::{SSL_CTX_clear_options, SSL_CTX_up_ref}; + + use super::SslMethod; + + pub unsafe fn get_new_idx(f: ffi::CRYPTO_EX_free) -> c_int { + ffi::CRYPTO_get_ex_new_index(ffi::CRYPTO_EX_INDEX_SSL_CTX, + 0, + ptr::null_mut(), + None, + None, + Some(f)) + } + + pub unsafe fn get_new_ssl_idx(f: ffi::CRYPTO_EX_free) -> c_int { + ffi::CRYPTO_get_ex_new_index(ffi::CRYPTO_EX_INDEX_SSL, + 0, + ptr::null_mut(), + None, + None, + Some(f)) + } + + pub unsafe fn get_method(method: SslMethod) -> *const ffi::SSL_METHOD { + match method { + SslMethod::Tls => ffi::TLS_method(), + SslMethod::Dtls => ffi::DTLS_method(), + } + } +} + +#[cfg(ossl10x)] +#[allow(bad_style)] +mod compat { + use std::ptr; + + use ffi; + use libc::{self, c_long, c_ulong, c_int}; + + use super::SslMethod; + + pub unsafe fn SSL_CTX_get_options(ctx: *const ffi::SSL_CTX) -> c_ulong { + ffi::SSL_CTX_ctrl(ctx as *mut _, + ffi::SSL_CTRL_OPTIONS, + 0, + ptr::null_mut()) as c_ulong + } + + pub unsafe fn SSL_CTX_set_options(ctx: *const ffi::SSL_CTX, + op: c_ulong) -> c_ulong { + ffi::SSL_CTX_ctrl(ctx as *mut _, + ffi::SSL_CTRL_OPTIONS, + op as c_long, + ptr::null_mut()) as c_ulong + } + + pub unsafe fn SSL_CTX_clear_options(ctx: *const ffi::SSL_CTX, + op: c_ulong) -> c_ulong { + ffi::SSL_CTX_ctrl(ctx as *mut _, + ffi::SSL_CTRL_CLEAR_OPTIONS, + op as c_long, + ptr::null_mut()) as c_ulong + } + + pub unsafe fn get_new_idx(f: ffi::CRYPTO_EX_free) -> c_int { + ffi::SSL_CTX_get_ex_new_index(0, + ptr::null_mut(), + None, + None, + Some(f)) + } + + pub unsafe fn get_new_ssl_idx(f: ffi::CRYPTO_EX_free) -> c_int { + ffi::SSL_get_ex_new_index(0, + ptr::null_mut(), + None, + None, + Some(f)) + } + + pub unsafe fn get_method(method: SslMethod) -> *const ffi::SSL_METHOD { + match method { + SslMethod::Tls => ffi::SSLv23_method(), + SslMethod::Dtls => ffi::DTLSv1_method(), + } + } + + pub unsafe fn SSL_CTX_up_ref(ssl: *mut ffi::SSL_CTX) -> libc::c_int { + ffi::CRYPTO_add_lock(&mut (*ssl).references, + 1, + ffi::CRYPTO_LOCK_SSL_CTX, + "mod.rs\0".as_ptr() as *const _, + line!() as libc::c_int); + 0 + } +} diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 3bbbed03..e5bdc8da 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -1,5 +1,6 @@ #![allow(unused_imports)] +use std::env; use std::fs::File; use std::io::prelude::*; use std::io::{self, BufReader}; @@ -12,11 +13,12 @@ use std::thread; use std::time::Duration; use net2::TcpStreamExt; +use tempdir::TempDir; use crypto::hash::Type::SHA256; use ssl; use ssl::SSL_VERIFY_PEER; -use ssl::SslMethod::Sslv23; +use ssl::SslMethod::Tls; use ssl::{SslMethod, HandshakeError}; use ssl::error::Error; use ssl::{SslContext, SslStream}; @@ -46,10 +48,21 @@ fn next_addr() -> SocketAddr { struct Server { p: Child, + _temp: TempDir, } impl Server { fn spawn(args: &[&str], input: Option>) -> (Server, SocketAddr) { + static CERT: &'static [u8] = include_bytes!("../../../test/cert.pem"); + static KEY: &'static [u8] = include_bytes!("../../../test/key.pem"); + + + let td = TempDir::new("openssl").unwrap(); + let cert = td.path().join("cert.pem"); + let key = td.path().join("key.pem"); + File::create(&cert).unwrap().write_all(CERT).unwrap(); + File::create(&key).unwrap().write_all(KEY).unwrap(); + let addr = next_addr(); let mut child = Command::new("openssl") .arg("s_server") @@ -57,11 +70,10 @@ impl Server { .arg(addr.port().to_string()) .args(args) .arg("-cert") - .arg("cert.pem") + .arg(&cert) .arg("-key") - .arg("key.pem") + .arg(&key) .arg("-no_dhe") - .current_dir("test") .stdout(Stdio::null()) .stderr(Stdio::null()) .stdin(Stdio::piped()) @@ -71,7 +83,7 @@ impl Server { if let Some(mut input) = input { thread::spawn(move || input(stdin)); } - (Server { p: child }, addr) + (Server { p: child, _temp: td }, addr) } fn new_tcp(args: &[&str]) -> (Server, TcpStream) { @@ -92,7 +104,7 @@ impl Server { Server::new_tcp(&["-www"]) } - #[cfg(any(feature = "alpn", feature = "npn"))] + #[cfg(all(any(feature = "alpn", feature = "npn"), not(ossl101)))] fn new_alpn() -> (Server, TcpStream) { Server::new_tcp(&["-www", "-nextprotoneg", @@ -119,7 +131,7 @@ impl Server { // but don't currently have a great way to do that so just wait for a // bit. thread::sleep(Duration::from_millis(100)); - let socket = UdpSocket::bind(next_addr()).unwrap(); + let socket = UdpSocket::bind("127.0.0.1:0").unwrap(); socket.connect(&addr).unwrap(); (s, UdpConnected(socket)) } @@ -205,7 +217,7 @@ macro_rules! run_test( #[test] fn sslv23() { let (_s, stream) = Server::new(); - $blk(SslMethod::Sslv23, stream); + $blk(SslMethod::Tls, stream); } #[test] @@ -226,11 +238,6 @@ run_test!(new_sslstream, |method, stream| { SslStream::connect(&SslContext::new(method).unwrap(), stream).unwrap(); }); -run_test!(get_ssl_method, |method, _| { - let ssl = Ssl::new(&SslContext::new(method).unwrap()).unwrap(); - assert_eq!(ssl.ssl_method(), method); -}); - run_test!(verify_untrusted, |method, stream| { let mut ctx = SslContext::new(method).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); @@ -391,11 +398,11 @@ run_test!(ssl_verify_callback, |method, stream| { // Make sure every write call translates to a write call to the underlying socket. #[test] fn test_write_hits_stream() { - let listener = TcpListener::bind(next_addr()).unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); let guard = thread::spawn(move || { - let ctx = SslContext::new(Sslv23).unwrap(); + let ctx = SslContext::new(Tls).unwrap(); let stream = TcpStream::connect(addr).unwrap(); let mut stream = SslStream::connect(&ctx, stream).unwrap(); @@ -403,7 +410,7 @@ fn test_write_hits_stream() { stream }); - let mut ctx = SslContext::new(Sslv23).unwrap(); + let mut ctx = SslContext::new(Tls).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM).unwrap(); ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM).unwrap(); @@ -423,7 +430,7 @@ fn test_set_certificate_and_private_key() { let cert = include_bytes!("../../../test/cert.pem"); let cert = X509::from_pem(cert).unwrap(); - let mut ctx = SslContext::new(Sslv23).unwrap(); + let mut ctx = SslContext::new(Tls).unwrap(); ctx.set_private_key(&key).unwrap(); ctx.set_certificate(&cert).unwrap(); @@ -451,7 +458,7 @@ run_test!(clear_ctx_options, |method, _| { #[test] fn test_write() { let (_s, stream) = Server::new(); - let mut stream = SslStream::connect(&SslContext::new(Sslv23).unwrap(), stream).unwrap(); + let mut stream = SslStream::connect(&SslContext::new(Tls).unwrap(), stream).unwrap(); stream.write_all("hello".as_bytes()).unwrap(); stream.flush().unwrap(); stream.write_all(" there".as_bytes()).unwrap(); @@ -461,7 +468,7 @@ fn test_write() { #[test] fn test_write_direct() { let (_s, stream) = Server::new(); - let mut stream = SslStream::connect(&SslContext::new(Sslv23).unwrap(), stream).unwrap(); + let mut stream = SslStream::connect(&SslContext::new(Tls).unwrap(), stream).unwrap(); stream.write_all("hello".as_bytes()).unwrap(); stream.flush().unwrap(); stream.write_all(" there".as_bytes()).unwrap(); @@ -492,7 +499,7 @@ fn test_write_dtlsv1() { #[test] fn test_read() { let (_s, tcp) = Server::new(); - let mut stream = SslStream::connect(&SslContext::new(Sslv23).unwrap(), tcp).unwrap(); + let mut stream = SslStream::connect(&SslContext::new(Tls).unwrap(), tcp).unwrap(); stream.write_all("GET /\r\n\r\n".as_bytes()).unwrap(); stream.flush().unwrap(); io::copy(&mut stream, &mut io::sink()).ok().expect("read error"); @@ -501,7 +508,7 @@ fn test_read() { #[test] fn test_read_direct() { let (_s, tcp) = Server::new(); - let mut stream = SslStream::connect(&SslContext::new(Sslv23).unwrap(), tcp).unwrap(); + let mut stream = SslStream::connect(&SslContext::new(Tls).unwrap(), tcp).unwrap(); stream.write_all("GET /\r\n\r\n".as_bytes()).unwrap(); stream.flush().unwrap(); io::copy(&mut stream, &mut io::sink()).ok().expect("read error"); @@ -510,7 +517,7 @@ fn test_read_direct() { #[test] fn test_pending() { let (_s, tcp) = Server::new(); - let mut stream = SslStream::connect(&SslContext::new(Sslv23).unwrap(), tcp).unwrap(); + let mut stream = SslStream::connect(&SslContext::new(Tls).unwrap(), tcp).unwrap(); stream.write_all("GET /\r\n\r\n".as_bytes()).unwrap(); stream.flush().unwrap(); @@ -533,7 +540,7 @@ fn test_pending() { #[test] fn test_state() { let (_s, tcp) = Server::new(); - let stream = SslStream::connect(&SslContext::new(Sslv23).unwrap(), tcp).unwrap(); + let stream = SslStream::connect(&SslContext::new(Tls).unwrap(), tcp).unwrap(); assert_eq!(stream.ssl().state_string(), "SSLOK "); assert_eq!(stream.ssl().state_string_long(), "SSL negotiation finished successfully"); @@ -542,10 +549,10 @@ fn test_state() { /// Tests that connecting with the client using ALPN, but the server not does not /// break the existing connection behavior. #[test] -#[cfg(feature = "alpn")] +#[cfg(all(feature = "alpn", not(ossl101)))] fn test_connect_with_unilateral_alpn() { let (_s, stream) = Server::new(); - let mut ctx = SslContext::new(Sslv23).unwrap(); + let mut ctx = SslContext::new(Tls).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -564,10 +571,10 @@ fn test_connect_with_unilateral_alpn() { /// Tests that connecting with the client using NPN, but the server not does not /// break the existing connection behavior. #[test] -#[cfg(feature = "npn")] +#[cfg(all(feature = "npn", not(ossl101)))] fn test_connect_with_unilateral_npn() { let (_s, stream) = Server::new(); - let mut ctx = SslContext::new(Sslv23).unwrap(); + let mut ctx = SslContext::new(Tls).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -586,10 +593,10 @@ fn test_connect_with_unilateral_npn() { /// Tests that when both the client as well as the server use ALPN and their /// lists of supported protocols have an overlap, the correct protocol is chosen. #[test] -#[cfg(feature = "alpn")] +#[cfg(all(feature = "alpn", not(ossl101)))] fn test_connect_with_alpn_successful_multiple_matching() { let (_s, stream) = Server::new_alpn(); - let mut ctx = SslContext::new(Sslv23).unwrap(); + let mut ctx = SslContext::new(Tls).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"spdy/3.1", b"http/1.1"]); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -608,10 +615,10 @@ fn test_connect_with_alpn_successful_multiple_matching() { /// Tests that when both the client as well as the server use NPN and their /// lists of supported protocols have an overlap, the correct protocol is chosen. #[test] -#[cfg(feature = "npn")] +#[cfg(all(feature = "npn", not(ossl101)))] fn test_connect_with_npn_successful_multiple_matching() { let (_s, stream) = Server::new_alpn(); - let mut ctx = SslContext::new(Sslv23).unwrap(); + let mut ctx = SslContext::new(Tls).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"spdy/3.1", b"http/1.1"]); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -631,10 +638,10 @@ fn test_connect_with_npn_successful_multiple_matching() { /// lists of supported protocols have an overlap -- with only ONE protocol /// being valid for both. #[test] -#[cfg(feature = "alpn")] +#[cfg(all(feature = "alpn", not(ossl101)))] fn test_connect_with_alpn_successful_single_match() { let (_s, stream) = Server::new_alpn(); - let mut ctx = SslContext::new(Sslv23).unwrap(); + let mut ctx = SslContext::new(Tls).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"spdy/3.1"]); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -655,10 +662,10 @@ fn test_connect_with_alpn_successful_single_match() { /// lists of supported protocols have an overlap -- with only ONE protocol /// being valid for both. #[test] -#[cfg(feature = "npn")] +#[cfg(all(feature = "npn", not(ossl101)))] fn test_connect_with_npn_successful_single_match() { let (_s, stream) = Server::new_alpn(); - let mut ctx = SslContext::new(Sslv23).unwrap(); + let mut ctx = SslContext::new(Tls).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"spdy/3.1"]); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -677,13 +684,13 @@ fn test_connect_with_npn_successful_single_match() { /// Tests that when the `SslStream` is created as a server stream, the protocols /// are correctly advertised to the client. #[test] -#[cfg(feature = "npn")] +#[cfg(all(feature = "npn", not(ossl101)))] fn test_npn_server_advertise_multiple() { - let listener = TcpListener::bind(next_addr()).unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let localhost = listener.local_addr().unwrap(); // We create a different context instance for the server... let listener_ctx = { - let mut ctx = SslContext::new(Sslv23).unwrap(); + let mut ctx = SslContext::new(Tls).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]); assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) @@ -698,7 +705,7 @@ fn test_npn_server_advertise_multiple() { let _ = SslStream::accept(&listener_ctx, stream).unwrap(); }); - let mut ctx = SslContext::new(Sslv23).unwrap(); + let mut ctx = SslContext::new(Tls).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"spdy/3.1"]); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -718,13 +725,13 @@ fn test_npn_server_advertise_multiple() { /// Tests that when the `SslStream` is created as a server stream, the protocols /// are correctly advertised to the client. #[test] -#[cfg(feature = "alpn")] +#[cfg(all(feature = "alpn", not(ossl101)))] fn test_alpn_server_advertise_multiple() { - let listener = TcpListener::bind(next_addr()).unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let localhost = listener.local_addr().unwrap(); // We create a different context instance for the server... let listener_ctx = { - let mut ctx = SslContext::new(Sslv23).unwrap(); + let mut ctx = SslContext::new(Tls).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]); assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) @@ -739,7 +746,7 @@ fn test_alpn_server_advertise_multiple() { let _ = SslStream::accept(&listener_ctx, stream).unwrap(); }); - let mut ctx = SslContext::new(Sslv23).unwrap(); + let mut ctx = SslContext::new(Tls).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"spdy/3.1"]); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -759,13 +766,13 @@ fn test_alpn_server_advertise_multiple() { /// Test that Servers supporting ALPN don't report a protocol when none of their protocols match /// the client's reported protocol. #[test] -#[cfg(feature = "alpn")] +#[cfg(all(feature = "alpn", not(ossl101)))] fn test_alpn_server_select_none() { - let listener = TcpListener::bind(next_addr()).unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let localhost = listener.local_addr().unwrap(); // We create a different context instance for the server... let listener_ctx = { - let mut ctx = SslContext::new(Sslv23).unwrap(); + let mut ctx = SslContext::new(Tls).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]); assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) @@ -780,7 +787,7 @@ fn test_alpn_server_select_none() { let _ = SslStream::accept(&listener_ctx, stream).unwrap(); }); - let mut ctx = SslContext::new(Sslv23).unwrap(); + let mut ctx = SslContext::new(Tls).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/2"]); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -875,7 +882,7 @@ fn handshake(res: Result, HandshakeError>) fn test_write_nonblocking() { let (_s, stream) = Server::new(); stream.set_nonblocking(true).unwrap(); - let cx = SslContext::new(Sslv23).unwrap(); + let cx = SslContext::new(Tls).unwrap(); let mut stream = handshake(SslStream::connect(&cx, stream)); let mut iterations = 0; @@ -913,7 +920,7 @@ fn test_write_nonblocking() { fn test_read_nonblocking() { let (_s, stream) = Server::new(); stream.set_nonblocking(true).unwrap(); - let cx = SslContext::new(Sslv23).unwrap(); + let cx = SslContext::new(Tls).unwrap(); let mut stream = handshake(SslStream::connect(&cx, stream)); let mut iterations = 0; @@ -965,7 +972,6 @@ fn test_read_nonblocking() { #[test] #[should_panic(expected = "blammo")] -#[cfg(feature = "nightly")] fn write_panic() { struct ExplodingStream(TcpStream); @@ -988,13 +994,12 @@ fn write_panic() { let (_s, stream) = Server::new(); let stream = ExplodingStream(stream); - let ctx = SslContext::new(SslMethod::Sslv23).unwrap(); + let ctx = SslContext::new(SslMethod::Tls).unwrap(); let _ = SslStream::connect(&ctx, stream); } #[test] #[should_panic(expected = "blammo")] -#[cfg(feature = "nightly")] fn read_panic() { struct ExplodingStream(TcpStream); @@ -1017,13 +1022,12 @@ fn read_panic() { let (_s, stream) = Server::new(); let stream = ExplodingStream(stream); - let ctx = SslContext::new(SslMethod::Sslv23).unwrap(); + let ctx = SslContext::new(SslMethod::Tls).unwrap(); let _ = SslStream::connect(&ctx, stream); } #[test] #[should_panic(expected = "blammo")] -#[cfg(feature = "nightly")] fn flush_panic() { struct ExplodingStream(TcpStream); @@ -1046,20 +1050,20 @@ fn flush_panic() { let (_s, stream) = Server::new(); let stream = ExplodingStream(stream); - let ctx = SslContext::new(SslMethod::Sslv23).unwrap(); - let mut stream = SslStream::connect(&ctx, stream).unwrap(); + let ctx = SslContext::new(SslMethod::Tls).unwrap(); + let mut stream = SslStream::connect(&ctx, stream).ok().unwrap(); let _ = stream.flush(); } #[test] fn refcount_ssl_context() { let mut ssl = { - let ctx = SslContext::new(SslMethod::Sslv23).unwrap(); + let ctx = SslContext::new(SslMethod::Tls).unwrap(); ssl::Ssl::new(&ctx).unwrap() }; { - let new_ctx_a = SslContext::new(SslMethod::Sslv23).unwrap(); + let new_ctx_a = SslContext::new(SslMethod::Tls).unwrap(); let _new_ctx_b = ssl.set_ssl_context(&new_ctx_a); } } @@ -1067,7 +1071,7 @@ fn refcount_ssl_context() { #[test] #[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( fn default_verify_paths() { - let mut ctx = SslContext::new(SslMethod::Sslv23).unwrap(); + let mut ctx = SslContext::new(SslMethod::Tls).unwrap(); ctx.set_default_verify_paths().unwrap(); ctx.set_verify(SSL_VERIFY_PEER); let s = TcpStream::connect("google.com:443").unwrap(); @@ -1086,6 +1090,6 @@ fn default_verify_paths() { fn add_extra_chain_cert() { let cert = include_bytes!("../../../test/cert.pem"); let cert = X509::from_pem(cert).unwrap(); - let mut ctx = SslContext::new(SslMethod::Sslv23).unwrap(); + let mut ctx = SslContext::new(SslMethod::Tls).unwrap(); ctx.add_extra_chain_cert(&cert).unwrap(); } diff --git a/openssl/src/version.rs b/openssl/src/version.rs index 0e9f61d8..245305e8 100644 --- a/openssl/src/version.rs +++ b/openssl/src/version.rs @@ -11,9 +11,26 @@ // limitations under the License. // -use ffi; use std::ffi::CStr; +#[cfg(ossl10x)] +use ffi::{ + SSLEAY_VERSION as OPENSSL_VERSION, + SSLEAY_CFLAGS as OPENSSL_CFLAGS, + SSLEAY_BUILT_ON as OPENSSL_BUILT_ON, + SSLEAY_PLATFORM as OPENSSL_PLATFORM, + SSLEAY_DIR as OPENSSL_DIR, + SSLeay as OpenSSL_version_num, + SSLeay_version as OpenSSL_version, +}; + +#[cfg(ossl110)] +use ffi::{OPENSSL_VERSION, OPENSSL_CFLAGS}; +#[cfg(ossl110)] +use ffi::{OPENSSL_BUILT_ON, OPENSSL_PLATFORM, OPENSSL_DIR}; +#[cfg(ossl110)] +use ffi::{OpenSSL_version_num, OpenSSL_version}; + /// OPENSSL_VERSION_NUMBER is a numeric release version identifier: /// /// `MNNFFPPS: major minor fix patch status` @@ -39,34 +56,34 @@ use std::ffi::CStr; /// /// The return value of this function can be compared to the macro to make sure that the correct version of the library has been loaded, especially when using DLLs on Windows systems. pub fn number() -> i64 { - unsafe { ffi::SSLeay() as i64 } + unsafe { OpenSSL_version_num() as i64 } } /// The text variant of the version number and the release date. For example, "OpenSSL 0.9.5a 1 Apr 2000". pub fn version() -> &'static str { - unsafe { CStr::from_ptr(ffi::SSLeay_version(ffi::SSLEAY_VERSION)).to_str().unwrap() } + unsafe { CStr::from_ptr(OpenSSL_version(OPENSSL_VERSION)).to_str().unwrap() } } /// The compiler flags set for the compilation process in the form "compiler: ..." if available or /// "compiler: information not available" otherwise. pub fn c_flags() -> &'static str { - unsafe { CStr::from_ptr(ffi::SSLeay_version(ffi::SSLEAY_CFLAGS)).to_str().unwrap() } + unsafe { CStr::from_ptr(OpenSSL_version(OPENSSL_CFLAGS)).to_str().unwrap() } } /// The date of the build process in the form "built on: ..." if available or "built on: date not available" otherwise. pub fn built_on() -> &'static str { - unsafe { CStr::from_ptr(ffi::SSLeay_version(ffi::SSLEAY_BUILT_ON)).to_str().unwrap() } + unsafe { CStr::from_ptr(OpenSSL_version(OPENSSL_BUILT_ON)).to_str().unwrap() } } /// The "Configure" target of the library build in the form "platform: ..." if available or "platform: information not available" otherwise. pub fn platform() -> &'static str { - unsafe { CStr::from_ptr(ffi::SSLeay_version(ffi::SSLEAY_PLATFORM)).to_str().unwrap() } + unsafe { CStr::from_ptr(OpenSSL_version(OPENSSL_PLATFORM)).to_str().unwrap() } } /// The "OPENSSLDIR" setting of the library build in the form "OPENSSLDIR: "..."" if available or "OPENSSLDIR: N/A" otherwise. pub fn dir() -> &'static str { - unsafe { CStr::from_ptr(ffi::SSLeay_version(ffi::SSLEAY_DIR)).to_str().unwrap() } + unsafe { CStr::from_ptr(OpenSSL_version(OPENSSL_DIR)).to_str().unwrap() } } /// This test ensures that we do not segfault when calling the functions of this module diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index f5369447..086342dd 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -12,7 +12,6 @@ use std::marker::PhantomData; use HashTypeInternals; use asn1::Asn1Time; -#[cfg(feature = "x509_expiry")] use asn1::Asn1TimeRef; use bio::{MemBio, MemBioSlice}; @@ -24,6 +23,19 @@ use ffi; use nid::Nid; use error::ErrorStack; +#[cfg(ossl10x)] +use ffi::{ + X509_set_notBefore, + X509_set_notAfter, + ASN1_STRING_data, +}; +#[cfg(ossl110)] +use ffi::{ + X509_set1_notBefore as X509_set_notBefore, + X509_set1_notAfter as X509_set_notAfter, + ASN1_STRING_get0_data as ASN1_STRING_data, +}; + pub mod extension; use self::extension::{ExtensionType, Extension}; @@ -36,7 +48,7 @@ pub struct SslString(&'static str); impl<'s> Drop for SslString { fn drop(&mut self) { unsafe { - ffi::CRYPTO_free(self.0.as_ptr() as *mut c_void); + CRYPTO_free!(self.0.as_ptr() as *mut c_void); } } } @@ -50,8 +62,8 @@ impl Deref for SslString { } impl SslString { - unsafe fn new(buf: *const c_char, len: c_int) -> SslString { - let slice = slice::from_raw_parts(buf as *const _, len as usize); + unsafe fn new(buf: *const u8, len: c_int) -> SslString { + let slice = slice::from_raw_parts(buf, len as usize); SslString(str::from_utf8_unchecked(slice)) } } @@ -311,11 +323,11 @@ impl X509Generator { let not_before = try!(Asn1Time::days_from_now(0)); let not_after = try!(Asn1Time::days_from_now(self.days)); - try_ssl!(ffi::X509_set_notBefore(x509.as_ptr(), not_before.as_ptr() as *const _)); + try_ssl!(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); - try_ssl!(ffi::X509_set_notAfter(x509.as_ptr(), not_after.as_ptr() as *const _)); + try_ssl!(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); @@ -350,9 +362,6 @@ impl X509Generator { } /// Obtain a certificate signing request (CSR) - /// - /// Requries the `x509_generator_request` feature. - #[cfg(feature = "x509_generator_request")] pub fn request(&self, p_key: &PKey) -> Result { let cert = match self.sign(p_key) { Ok(c) => c, @@ -363,9 +372,9 @@ impl X509Generator { let req = ffi::X509_to_X509_REQ(cert.as_ptr(), ptr::null_mut(), ptr::null()); try_ssl_null!(req); - let exts = ::c_helpers::rust_0_8_X509_get_extensions(cert.as_ptr()); + let exts = compat::X509_get0_extensions(cert.as_ptr()); if exts != ptr::null_mut() { - try_ssl!(ffi::X509_REQ_add_extensions(req, exts)); + try_ssl!(ffi::X509_REQ_add_extensions(req, exts as *mut _)); } let hash_fn = self.hash_type.evp_md(); @@ -438,22 +447,18 @@ impl<'a> X509Ref<'a> { } /// Returns certificate Not After validity period. - /// Requires the `x509_expiry` feature. - #[cfg(feature = "x509_expiry")] pub fn not_after<'b>(&'b self) -> Asn1TimeRef<'b> { unsafe { - let date = ::c_helpers::rust_0_8_X509_get_notAfter(self.0); + let date = compat::X509_get_notAfter(self.0); assert!(!date.is_null()); Asn1TimeRef::from_ptr(date) } } /// Returns certificate Not Before validity period. - /// Requires the `x509_expiry` feature. - #[cfg(feature = "x509_expiry")] pub fn not_before<'b>(&'b self) -> Asn1TimeRef<'b> { unsafe { - let date = ::c_helpers::rust_0_8_X509_get_notBefore(self.0); + let date = compat::X509_get_notBefore(self.0); assert!(!date.is_null()); Asn1TimeRef::from_ptr(date) } @@ -496,7 +501,7 @@ impl X509 { /// Reads a certificate from DER. pub fn from_der(buf: &[u8]) -> Result { unsafe { - let mut ptr = buf.as_ptr() as *mut _; + let mut ptr = buf.as_ptr(); let len = cmp::min(buf.len(), c_long::max_value() as usize) as c_long; let x509 = try_ssl_null!(ffi::d2i_X509(ptr::null_mut(), &mut ptr, len)); Ok(X509::from_ptr(x509)) @@ -524,13 +529,11 @@ impl Deref for X509 { } } -#[cfg(feature = "x509_clone")] impl Clone for X509 { - /// Requires the `x509_clone` feature. fn clone(&self) -> X509 { unsafe { - ::c_helpers::rust_0_8_X509_clone(self.as_ptr()); - X509::new(self.as_ptr()) + compat::X509_up_ref(self.as_ptr()); + X509::from_ptr(self.as_ptr()) } } } @@ -561,7 +564,7 @@ impl<'x> X509Name<'x> { return None; } - let mut str_from_asn1: *mut c_char = ptr::null_mut(); + let mut str_from_asn1: *mut u8 = ptr::null_mut(); let len = ffi::ASN1_STRING_to_UTF8(&mut str_from_asn1, asn1_str); if len < 0 { @@ -779,22 +782,43 @@ pub struct GeneralNames<'a> { } impl<'a> Drop for GeneralNames<'a> { + #[cfg(ossl10x)] fn drop(&mut self) { unsafe { // This transmute is dubious but it's what openssl itself does... - let free: unsafe extern "C" fn(*mut ffi::GENERAL_NAME) = ffi::GENERAL_NAME_free; - let free: unsafe extern "C" fn(*mut c_void) = mem::transmute(free); + let free: unsafe extern fn(*mut ffi::GENERAL_NAME) = ffi::GENERAL_NAME_free; + let free: unsafe extern fn(*mut c_void) = mem::transmute(free); ffi::sk_pop_free(&mut (*self.stack).stack, Some(free)); } } + + #[cfg(ossl110)] + fn drop(&mut self) { + unsafe { + // This transmute is dubious but it's what openssl itself does... + let free: unsafe extern fn(*mut ffi::GENERAL_NAME) = ffi::GENERAL_NAME_free; + let free: unsafe extern fn(*mut c_void) = mem::transmute(free); + ffi::OPENSSL_sk_pop_free(self.stack as *mut _, Some(free)); + } + } } impl<'a> GeneralNames<'a> { /// Returns the number of `GeneralName`s in this structure. pub fn len(&self) -> usize { + self._len() + } + + #[cfg(ossl10x)] + fn _len(&self) -> usize { unsafe { (*self.stack).stack.num as usize } } + #[cfg(ossl110)] + fn _len(&self) -> usize { + unsafe { ffi::OPENSSL_sk_num(self.stack as *const _) as usize } + } + /// Returns the specified `GeneralName`. /// /// # Panics @@ -803,14 +827,23 @@ impl<'a> GeneralNames<'a> { pub fn get(&self, idx: usize) -> GeneralName<'a> { unsafe { assert!(idx < self.len()); - GeneralName { - name: *(*self.stack).stack.data.offset(idx as isize) as *const ffi::GENERAL_NAME, + name: self._get(idx), m: PhantomData, } } } + #[cfg(ossl10x)] + unsafe fn _get(&self, idx: usize) -> *const ffi::GENERAL_NAME { + *(*self.stack).stack.data.offset(idx as isize) as *const ffi::GENERAL_NAME + } + + #[cfg(ossl110)] + unsafe fn _get(&self, idx: usize) -> *const ffi::GENERAL_NAME { + ffi::OPENSSL_sk_value(self.stack as *const _, idx as c_int) as *mut _ + } + /// Returns an iterator over the `GeneralName`s in this structure. pub fn iter(&self) -> GeneralNamesIter { GeneralNamesIter { @@ -870,7 +903,7 @@ impl<'a> GeneralName<'a> { return None; } - let ptr = ffi::ASN1_STRING_data((*self.name).d as *mut _); + let ptr = ASN1_STRING_data((*self.name).d as *mut _); let len = ffi::ASN1_STRING_length((*self.name).d as *mut _); let slice = slice::from_raw_parts(ptr as *const u8, len as usize); @@ -888,7 +921,7 @@ impl<'a> GeneralName<'a> { return None; } - let ptr = ffi::ASN1_STRING_data((*self.name).d as *mut _); + let ptr = ASN1_STRING_data((*self.name).d as *mut _); let len = ffi::ASN1_STRING_length((*self.name).d as *mut _); Some(slice::from_raw_parts(ptr as *const u8, len as usize)) @@ -904,3 +937,44 @@ fn test_negative_serial() { "All serials should be positive"); } } + +#[cfg(ossl110)] +mod compat { + pub use ffi::X509_getm_notAfter as X509_get_notAfter; + pub use ffi::X509_getm_notBefore as X509_get_notBefore; + pub use ffi::X509_up_ref; + pub use ffi::X509_get0_extensions; +} + +#[cfg(ossl10x)] +#[allow(bad_style)] +mod compat { + use libc::c_int; + use ffi; + + pub unsafe fn X509_get_notAfter(x: *mut ffi::X509) -> *mut ffi::ASN1_TIME { + (*(*(*x).cert_info).validity).notAfter + } + + pub unsafe fn X509_get_notBefore(x: *mut ffi::X509) -> *mut ffi::ASN1_TIME { + (*(*(*x).cert_info).validity).notBefore + } + + pub unsafe fn X509_up_ref(x: *mut ffi::X509) { + ffi::CRYPTO_add_lock(&mut (*x).references, + 1, + ffi::CRYPTO_LOCK_X509, + "mod.rs\0".as_ptr() as *const _, + line!() as c_int); + } + + pub unsafe fn X509_get0_extensions(cert: *const ffi::X509) + -> *const ffi::stack_st_X509_EXTENSION { + let info = (*cert).cert_info; + if info.is_null() { + 0 as *mut _ + } else { + (*info).extensions + } + } +} diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index eac08941..07d9e1d4 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -69,7 +69,6 @@ fn test_cert_gen_extension_bad_ordering() { } #[test] -#[cfg(feature = "x509_generator_request")] fn test_req_gen() { let pkey = pkey(); @@ -93,7 +92,6 @@ fn test_cert_loading() { } #[test] -#[cfg(feature = "x509_expiry")] fn test_cert_issue_validity() { let cert = include_bytes!("../../test/cert.pem"); let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); diff --git a/openssl/test/build.sh b/openssl/test/build.sh index 2c38f3a3..106a38d3 100755 --- a/openssl/test/build.sh +++ b/openssl/test/build.sh @@ -1,33 +1,48 @@ #!/bin/bash -set -e + +set -ex MAX_REDIRECTS=5 -OPENSSL=openssl-1.0.2h.tar.gz +OPENSSL=openssl-$BUILD_OPENSSL_VERSION.tar.gz OUT=/tmp/$OPENSSL -SHA1="577585f5f5d299c44dd3c993d3c0ac7a219e4949" + +me=$0 +myname=`basename $me` + +cmp --silent $me $HOME/openssl/$myname && exit 0 || echo "cache is busted" + +rm -rf $HOME/openssl if [ "$TRAVIS_OS_NAME" == "osx" ]; then exit 0 fi -if [ "$TARGET" == "arm-unknown-linux-gnueabihf" ]; then - export C_INCLUDE_PATH=/usr/arm-linux-gnueabihf/include - CROSS=arm-linux-gnueabihf- +if [ "$BUILD_OPENSSL_VERSION" == "" ]; then + exit 0 +fi + +if [ "$TARGET" == "i686-unknown-linux-gnu" ]; then + OS_COMPILER=linux-elf + OS_FLAGS=-m32 +elif [ "$TARGET" == "arm-unknown-linux-gnueabihf" ]; then OS_COMPILER=linux-armv4 + export AR=arm-linux-gnueabihf-ar + export CC=arm-linux-gnueabihf-gcc else OS_COMPILER=linux-x86_64 fi mkdir -p /tmp/openssl +cp $me /tmp/openssl/$myname cd /tmp/openssl curl -o $OUT -L --max-redirs $MAX_REDIRECTS https://openssl.org/source/$OPENSSL \ || curl -o $OUT -L --max-redirs ${MAX_REDIRECTS} http://mirrors.ibiblio.org/openssl/source/$OPENSSL -echo "$SHA1 $OUT" | sha1sum -c - - tar --strip-components=1 -xzf $OUT -./Configure --prefix=$HOME/openssl shared --cross-compile-prefix=$CROSS $OS_COMPILER -make +./Configure --prefix=$HOME/openssl $OS_COMPILER -fPIC $OS_FLAGS + +make -j$(nproc) make install +cp $myname $HOME/openssl/$myname diff --git a/openssl/test/run.sh b/openssl/test/run.sh index 2c2473b1..eed7ebac 100755 --- a/openssl/test/run.sh +++ b/openssl/test/run.sh @@ -1,32 +1,15 @@ #!/bin/bash set -e -MAIN_TARGETS=https://static.rust-lang.org/dist - -if [ "$TEST_FEATURES" == "true" ]; then - FEATURES="tlsv1_2 tlsv1_1 dtlsv1 dtlsv1_2 sslv3 aes_xts aes_ctr npn alpn rfc5114 ecdh_auto pkcs5_pbkdf2_hmac x509_clone ssl_context_clone x509_generator_request hmac hmac_clone dh_from_params x509_expiry" +if [ "$BUILD_OPENSSL_VERSION" != "" ]; then + FEATURES="aes_xts aes_ctr npn alpn rfc5114 ecdh_auto" fi -if [ "$TRAVIS_OS_NAME" != "osx" ]; then - export OPENSSL_LIB_DIR=$HOME/openssl/lib - export OPENSSL_INCLUDE_DIR=$HOME/openssl/include - export LD_LIBRARY_PATH=$HOME/openssl/lib:$LD_LIBRARY_PATH +if [ -d "$HOME/openssl/lib" ]; then + export OPENSSL_DIR=$HOME/openssl + export PATH=$HOME/openssl/bin:$PATH fi -if [ -n "$TARGET" ]; then - FLAGS="--target=$TARGET" - COMMAND="build" - - # Download the rustlib folder from the relevant portion of main distribution's - # tarballs. - dir=rust-std-$TARGET - pkg=rust-std - curl -s $MAIN_TARGETS/$pkg-$TRAVIS_RUST_VERSION-$TARGET.tar.gz | \ - tar xzf - -C $HOME/rust/lib/rustlib --strip-components=4 \ - $pkg-$TRAVIS_RUST_VERSION-$TARGET/$dir/lib/rustlib/$TARGET -else - COMMAND="test" -fi - -export PATH=$HOME/openssl/bin:$PATH -(cd openssl && RUST_BACKTRACE=1 cargo $COMMAND $FLAGS --features "$FEATURES") +cargo run --manifest-path systest/Cargo.toml --target $TARGET +exec cargo test --manifest-path openssl/Cargo.toml --target $TARGET \ + --features "$FEATURES" diff --git a/systest/Cargo.toml b/systest/Cargo.toml new file mode 100644 index 00000000..3997bf35 --- /dev/null +++ b/systest/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "systest" +version = "0.1.0" +authors = ["Alex Crichton "] +build = "build.rs" + +[dependencies] +libc = "0.2" +openssl-sys = { path = "../openssl-sys" } + +[build-dependencies] +ctest = "0.1" diff --git a/systest/build.rs b/systest/build.rs new file mode 100644 index 00000000..b2820e5b --- /dev/null +++ b/systest/build.rs @@ -0,0 +1,110 @@ +extern crate ctest; + +use std::env; + +fn main() { + let mut cfg = ctest::TestGenerator::new(); + let target = env::var("TARGET").unwrap(); + + if let Ok(out) = env::var("DEP_OPENSSL_INCLUDE") { + cfg.include(&out); + } + + // Needed to get OpenSSL to correctly undef symbols that are already on + // Windows like X509_NAME + if target.contains("windows") { + cfg.header("windows.h"); + + // weird "different 'const' qualifiers" error on Windows, maybe a cl.exe + // thing? + if target.contains("msvc") { + cfg.flag("/wd4090"); + } + } + + if env::var("DEP_OPENSSL_IS_101").is_ok() { + cfg.cfg("ossl101", None); + } + if env::var("DEP_OPENSSL_IS_102").is_ok() { + cfg.cfg("ossl102", None); + } + if env::var("DEP_OPENSSL_IS_110").is_ok() { + cfg.cfg("ossl110", None); + } + + cfg.header("openssl/comp.h") + .header("openssl/dh.h") + .header("openssl/ossl_typ.h") + .header("openssl/stack.h") + .header("openssl/x509.h") + .header("openssl/bio.h") + .header("openssl/x509v3.h") + .header("openssl/safestack.h") + .header("openssl/hmac.h") + .header("openssl/ssl.h") + .header("openssl/err.h") + .header("openssl/rand.h") + .header("openssl/pkcs12.h") + .header("openssl/bn.h"); + cfg.type_name(|s, is_struct| { + // Add some `*` on some callback parameters to get function pointer to + // typecheck in C, especially on MSVC. + if s == "PasswordCallback" { + format!("pem_password_cb*") + } else if s == "bio_info_cb" { + format!("bio_info_cb*") + } else if s == "_STACK" { + format!("struct stack_st") + } else if is_struct && s.chars().next().unwrap().is_lowercase() { + format!("struct {}", s) + } else { + format!("{}", s) + } + }); + cfg.skip_type(|s| { + // function pointers are declared without a `*` in openssl so their + // sizeof is 1 which isn't what we want. + s == "PasswordCallback" || + s == "bio_info_cb" || + s.starts_with("CRYPTO_EX_") + }); + cfg.skip_struct(|s| { + s == "ProbeResult" + }); + cfg.skip_fn(move |s| { + s == "CRYPTO_memcmp" || // uses volatile + s == "X509V3_EXT_conf_nid" || // weird lhash first param + s == "X509V3_EXT_conf" || // weird lhash first param + + // one parameter is `const` in OpenSSL 1.0.1, no need for a new + // definition or a new file here. + (s == "BIO_new_mem_buf" && env::var("DEP_OPENSSL_IS_101").is_ok()) || + + // Skip some functions with function pointers on windows, not entirely + // sure how to get them to work out... + (target.contains("windows") && { + s == "SSL_get_ex_new_index" || + s == "SSL_CTX_get_ex_new_index" || + s == "CRYPTO_get_ex_new_index" + }) + }); + cfg.skip_field_type(|s, field| { + (s == "EVP_PKEY" && field == "pkey") || // union + (s == "GENERAL_NAME" && field == "d") // union + }); + cfg.skip_signededness(|s| { + s.ends_with("_cb") || + s.starts_with("CRYPTO_") || + s == "PasswordCallback" + }); + cfg.field_name(|_s, field| { + if field == "type_" { + format!("type") + } else { + format!("{}", field) + } + }); + cfg.fn_cname(|rust, link_name| link_name.unwrap_or(rust).to_string()); + cfg.generate("../openssl-sys/src/lib.rs", "all.rs"); +} + diff --git a/systest/src/main.rs b/systest/src/main.rs new file mode 100644 index 00000000..39d31b2f --- /dev/null +++ b/systest/src/main.rs @@ -0,0 +1,9 @@ +#![allow(bad_style)] + +extern crate openssl_sys; +extern crate libc; + +use libc::*; +use openssl_sys::*; + +include!(concat!(env!("OUT_DIR"), "/all.rs")); From af3e06d3e897d0ea5a2a50f0a6b932c3c42bd450 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Wed, 12 Oct 2016 22:34:13 -0700 Subject: [PATCH 009/186] Add remaining SSL_OP constants --- openssl-sys/src/lib.rs | 15 +++++---------- openssl/src/ssl/mod.rs | 5 +++++ 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 1c1df579..9dfe8061 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -169,17 +169,12 @@ pub const SSL_OP_CIPHER_SERVER_PREFERENCE: c_ulong = 0x00400000; pub const SSL_OP_TLS_ROLLBACK_BUG: c_ulong = 0x00800000; pub const SSL_OP_NO_SSLv3: c_ulong = 0x02000000; pub const SSL_OP_NO_TLSv1: c_ulong = 0x04000000; - -// Intentionally not bound since they conflict with SSL_OP_PKCS1_CHECK_1 and -// SSL_OP_PKCS1_CHECK_2 on 0.9.8 :( -/* -pub const SSL_OP_NO_TLSv1_2: c_long = 0x08000000; -pub const SSL_OP_NO_TLSv1_1: c_long = 0x10000000; -pub const SSL_OP_NO_DTLSv1: c_long = 0x04000000; -pub const SSL_OP_NO_DTLSv1_2: c_long = 0x08000000; -pub const SSL_OP_NO_SSL_MASK: c_long = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | +pub const SSL_OP_NO_TLSv1_2: c_ulong = 0x08000000; +pub const SSL_OP_NO_TLSv1_1: c_ulong = 0x10000000; +pub const SSL_OP_NO_DTLSv1: c_ulong = 0x04000000; +pub const SSL_OP_NO_DTLSv1_2: c_ulong = 0x08000000; +pub const SSL_OP_NO_SSL_MASK: c_ulong = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2; -*/ pub const TLSEXT_NAMETYPE_host_name: c_int = 0; diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 51bfc790..1c3fe1ae 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -65,6 +65,11 @@ bitflags! { const SSL_OP_NO_SSLV2 = ffi::SSL_OP_NO_SSLv2, const SSL_OP_NO_SSLV3 = ffi::SSL_OP_NO_SSLv3, const SSL_OP_NO_TLSV1 = ffi::SSL_OP_NO_TLSv1, + const SSL_OP_NO_TLSV1_2 = ffi::SSL_OP_NO_TLSv1_2, + const SSL_OP_NO_TLSV1_1 = ffi::SSL_OP_NO_TLSv1_1, + const SSL_OP_NO_DTLSV1 = ffi::SSL_OP_NO_DTLSv1, + const SSL_OP_NO_DTLSV1_2 = ffi::SSL_OP_NO_DTLSv1_2, + const SSL_OP_NO_SSL_MASK = ffi::SSL_OP_NO_SSL_MASK, } } From 715b700aff6e46c555895618892a46fa53a5d17a Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Wed, 12 Oct 2016 22:51:47 -0700 Subject: [PATCH 010/186] Ignore a test on OpenSSL 1.1.0 --- openssl/src/ssl/tests/mod.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index e5bdc8da..01c836e7 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -767,6 +767,9 @@ fn test_alpn_server_advertise_multiple() { /// the client's reported protocol. #[test] #[cfg(all(feature = "alpn", not(ossl101)))] +// TODO: not sure why this test is failing on OpenSSL 1.1.0, may be related to +// something about SSLv3 though? +#[cfg_attr(ossl110, ignore)] fn test_alpn_server_select_none() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let localhost = listener.local_addr().unwrap(); From ce4d233d38db0e855397e7c6defd194ea8d5c686 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Wed, 12 Oct 2016 22:53:03 -0700 Subject: [PATCH 011/186] Tweak some comments in Cargo.toml --- openssl/Cargo.toml | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/openssl/Cargo.toml b/openssl/Cargo.toml index d9691403..ada3fe36 100644 --- a/openssl/Cargo.toml +++ b/openssl/Cargo.toml @@ -12,19 +12,10 @@ build = "build.rs" exclude = ["test/*"] [features] -aes_xts = [] -aes_ctr = [] - # Added in OpenSSL 1.0.2 rfc5114 = [] - -# TODO: what to do about these features? -# tlsv1_2 = [] -# tlsv1_1 = [] -# dtlsv1 = [] -# dtlsv1_2 = [] -# sslv2 = [] -# sslv3 = [] +aes_xts = [] +aes_ctr = [] npn = [] alpn = [] From b610e01793f31836bb5e56b655a3bbae498649d6 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 13 Oct 2016 19:06:53 -0700 Subject: [PATCH 012/186] Flag off dtls and mask ssl_ops Also un-feature gate npn as it ships with 1.0.1 --- openssl-sys/src/lib.rs | 4 ++++ openssl/Cargo.toml | 4 ++-- openssl/src/ssl/mod.rs | 16 +++------------- openssl/test/run.sh | 2 +- 4 files changed, 10 insertions(+), 16 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 9dfe8061..e3c5bd95 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -171,8 +171,12 @@ pub const SSL_OP_NO_SSLv3: c_ulong = 0x02000000; pub const SSL_OP_NO_TLSv1: c_ulong = 0x04000000; pub const SSL_OP_NO_TLSv1_2: c_ulong = 0x08000000; pub const SSL_OP_NO_TLSv1_1: c_ulong = 0x10000000; + +#[cfg(not(ossl101))] pub const SSL_OP_NO_DTLSv1: c_ulong = 0x04000000; +#[cfg(not(ossl101))] pub const SSL_OP_NO_DTLSv1_2: c_ulong = 0x08000000; +#[cfg(not(ossl101))] pub const SSL_OP_NO_SSL_MASK: c_ulong = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2; diff --git a/openssl/Cargo.toml b/openssl/Cargo.toml index ada3fe36..868aef60 100644 --- a/openssl/Cargo.toml +++ b/openssl/Cargo.toml @@ -16,9 +16,9 @@ exclude = ["test/*"] rfc5114 = [] aes_xts = [] aes_ctr = [] - -npn = [] alpn = [] +openssl-102 = [] + ecdh_auto = [] [dependencies] diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 1c3fe1ae..fc1c131c 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -14,9 +14,7 @@ use std::path::Path; use std::ptr; use std::str; use std::sync::{Mutex, Arc}; -#[cfg(any(feature = "npn", feature = "alpn"))] use libc::{c_uchar, c_uint}; -#[cfg(any(feature = "npn", feature = "alpn"))] use std::slice; use std::marker::PhantomData; use ffi; @@ -67,8 +65,11 @@ bitflags! { const SSL_OP_NO_TLSV1 = ffi::SSL_OP_NO_TLSv1, const SSL_OP_NO_TLSV1_2 = ffi::SSL_OP_NO_TLSv1_2, const SSL_OP_NO_TLSV1_1 = ffi::SSL_OP_NO_TLSv1_1, + #[cfg(feature = "openssl-102")] const SSL_OP_NO_DTLSV1 = ffi::SSL_OP_NO_DTLSv1, + #[cfg(feature = "openssl-102")] const SSL_OP_NO_DTLSV1_2 = ffi::SSL_OP_NO_DTLSv1_2, + #[cfg(feature = "openssl-102")] const SSL_OP_NO_SSL_MASK = ffi::SSL_OP_NO_SSL_MASK, } } @@ -113,7 +114,6 @@ fn get_ssl_verify_data_idx() -> c_int { *SSL_INDEXES.lock().unwrap().entry(TypeId::of::()).or_insert_with(|| get_new_ssl_idx::()) } -#[cfg(all(feature = "npn", not(ossl101)))] lazy_static! { static ref NPN_PROTOS_IDX: c_int = get_new_idx::>(); } @@ -218,7 +218,6 @@ extern fn raw_sni(ssl: *mut ffi::SSL, al: *mut c_int, _arg: *mut c_void) -> c } } -#[cfg(all(any(feature = "npn", feature = "alpn"), not(ossl101)))] unsafe fn select_proto_using(ssl: *mut ffi::SSL, out: *mut *mut c_uchar, outlen: *mut c_uchar, @@ -251,7 +250,6 @@ unsafe fn select_proto_using(ssl: *mut ffi::SSL, /// supported by the server. It achieves this by delegating to the `SSL_select_next_proto` /// function. The list of protocols supported by the client is found in the extra data of the /// OpenSSL context. -#[cfg(all(feature = "npn", not(ossl101)))] extern fn raw_next_proto_select_cb(ssl: *mut ffi::SSL, out: *mut *mut c_uchar, outlen: *mut c_uchar, @@ -280,7 +278,6 @@ extern fn raw_alpn_select_cb(ssl: *mut ffi::SSL, /// that it supports. /// The list of supported protocols is found in the extra data of the OpenSSL /// context. -#[cfg(all(feature = "npn", not(ossl101)))] extern fn raw_next_protos_advertise_cb(ssl: *mut ffi::SSL, out: *mut *const c_uchar, outlen: *mut c_uint, @@ -307,7 +304,6 @@ extern fn raw_next_protos_advertise_cb(ssl: *mut ffi::SSL, /// Convert a set of byte slices into a series of byte strings encoded for SSL. Encoding is a byte /// containing the length followed by the string. -#[cfg(all(any(feature = "alpn", feature = "npn"), not(ossl101)))] fn ssl_encode_byte_strings(strings: &[&[u8]]) -> Vec { let mut enc = Vec::new(); for string in strings { @@ -555,9 +551,6 @@ impl<'a> SslContextRef<'a> { /// Set the protocols to be used during Next Protocol Negotiation (the protocols /// supported by the application). - /// - /// This method needs the `npn` feature. - #[cfg(all(feature = "npn", not(ossl101)))] pub fn set_npn_protocols(&mut self, protocols: &[&[u8]]) { // Firstly, convert the list of protocols to a byte-array that can be passed to OpenSSL // APIs -- a list of length-prefixed strings. @@ -907,9 +900,6 @@ impl<'a> SslRef<'a> { /// /// The protocol's name is returned is an opaque sequence of bytes. It is up to the client /// to interpret it. - /// - /// This method needs the `npn` feature. - #[cfg(feature = "npn")] pub fn selected_npn_protocol(&self) -> Option<&[u8]> { unsafe { let mut data: *const c_uchar = ptr::null(); diff --git a/openssl/test/run.sh b/openssl/test/run.sh index eed7ebac..cecf3c52 100755 --- a/openssl/test/run.sh +++ b/openssl/test/run.sh @@ -2,7 +2,7 @@ set -e if [ "$BUILD_OPENSSL_VERSION" != "" ]; then - FEATURES="aes_xts aes_ctr npn alpn rfc5114 ecdh_auto" + FEATURES="aes_xts aes_ctr alpn rfc5114 ecdh_auto openssl-102" fi if [ -d "$HOME/openssl/lib" ]; then From 1883590c61e912a627e3c02542d9a2d0b4019d24 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 13 Oct 2016 19:21:12 -0700 Subject: [PATCH 013/186] Correct feature selection in tests --- openssl/Cargo.toml | 3 ++- openssl/test/run.sh | 13 ++++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/openssl/Cargo.toml b/openssl/Cargo.toml index 868aef60..2ed0df12 100644 --- a/openssl/Cargo.toml +++ b/openssl/Cargo.toml @@ -17,9 +17,10 @@ rfc5114 = [] aes_xts = [] aes_ctr = [] alpn = [] +ecdh_auto = [] openssl-102 = [] -ecdh_auto = [] +openssl-110 = ["openssl-102"] [dependencies] bitflags = "0.7" diff --git a/openssl/test/run.sh b/openssl/test/run.sh index cecf3c52..cc4756bf 100755 --- a/openssl/test/run.sh +++ b/openssl/test/run.sh @@ -1,9 +1,16 @@ #!/bin/bash set -e -if [ "$BUILD_OPENSSL_VERSION" != "" ]; then - FEATURES="aes_xts aes_ctr alpn rfc5114 ecdh_auto openssl-102" -fi +case "$BUILD_OPENSSL_VERSION" in + 1.0.2*) + FEATURES="openssl-102" + ;; + 1.1.0*) + FEATURES="openssl-110" + ;; +esac + +echo Using features: $FEATURES if [ -d "$HOME/openssl/lib" ]; then export OPENSSL_DIR=$HOME/openssl From edfc50f37db8d230eb17480f124b9fd70166a940 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 13 Oct 2016 19:46:13 -0700 Subject: [PATCH 014/186] Clean up features --- openssl/Cargo.toml | 7 ------- openssl/src/crypto/symm.rs | 33 --------------------------------- openssl/src/dh/mod.rs | 8 ++++---- openssl/src/ssl/mod.rs | 22 ++++++++++++---------- openssl/src/ssl/tests/mod.rs | 15 +++++---------- 5 files changed, 21 insertions(+), 64 deletions(-) diff --git a/openssl/Cargo.toml b/openssl/Cargo.toml index 2ed0df12..3845c51d 100644 --- a/openssl/Cargo.toml +++ b/openssl/Cargo.toml @@ -12,14 +12,7 @@ build = "build.rs" exclude = ["test/*"] [features] -# Added in OpenSSL 1.0.2 -rfc5114 = [] -aes_xts = [] -aes_ctr = [] -alpn = [] -ecdh_auto = [] openssl-102 = [] - openssl-110 = ["openssl-102"] [dependencies] diff --git a/openssl/src/crypto/symm.rs b/openssl/src/crypto/symm.rs index c4021338..37754387 100644 --- a/openssl/src/crypto/symm.rs +++ b/openssl/src/crypto/symm.rs @@ -16,31 +16,20 @@ pub enum Mode { pub enum Type { AES_128_ECB, AES_128_CBC, - /// Requires the `aes_xts` feature - #[cfg(feature = "aes_xts")] AES_128_XTS, - #[cfg(feature = "aes_ctr")] AES_128_CTR, - // AES_128_GCM, AES_128_CFB1, AES_128_CFB128, AES_128_CFB8, - AES_256_ECB, AES_256_CBC, - /// Requires the `aes_xts` feature - #[cfg(feature = "aes_xts")] AES_256_XTS, - #[cfg(feature = "aes_ctr")] AES_256_CTR, - // AES_256_GCM, AES_256_CFB1, AES_256_CFB128, AES_256_CFB8, - DES_CBC, DES_ECB, - RC4_128, } @@ -50,29 +39,20 @@ impl Type { match *self { Type::AES_128_ECB => ffi::EVP_aes_128_ecb(), Type::AES_128_CBC => ffi::EVP_aes_128_cbc(), - #[cfg(feature = "aes_xts")] Type::AES_128_XTS => ffi::EVP_aes_128_xts(), - #[cfg(feature = "aes_ctr")] Type::AES_128_CTR => ffi::EVP_aes_128_ctr(), - // AES_128_GCM => (EVP_aes_128_gcm(), 16, 16), Type::AES_128_CFB1 => ffi::EVP_aes_128_cfb1(), Type::AES_128_CFB128 => ffi::EVP_aes_128_cfb128(), Type::AES_128_CFB8 => ffi::EVP_aes_128_cfb8(), - Type::AES_256_ECB => ffi::EVP_aes_256_ecb(), Type::AES_256_CBC => ffi::EVP_aes_256_cbc(), - #[cfg(feature = "aes_xts")] Type::AES_256_XTS => ffi::EVP_aes_256_xts(), - #[cfg(feature = "aes_ctr")] Type::AES_256_CTR => ffi::EVP_aes_256_ctr(), - // AES_256_GCM => (EVP_aes_256_gcm(), 32, 16), Type::AES_256_CFB1 => ffi::EVP_aes_256_cfb1(), Type::AES_256_CFB128 => ffi::EVP_aes_256_cfb128(), Type::AES_256_CFB8 => ffi::EVP_aes_256_cfb8(), - Type::DES_CBC => ffi::EVP_des_cbc(), Type::DES_ECB => ffi::EVP_des_ecb(), - Type::RC4_128 => ffi::EVP_rc4(), } } @@ -396,7 +376,6 @@ mod tests { } #[test] - #[cfg(feature = "aes_xts")] fn test_aes256_xts() { // Test case 174 from // http://csrc.nist.gov/groups/STM/cavp/documents/aes/XTSTestVectors.zip @@ -412,7 +391,6 @@ mod tests { } #[test] - #[cfg(feature = "aes_ctr")] fn test_aes128_ctr() { let pt = "6BC1BEE22E409F96E93D7E117393172AAE2D8A571E03AC9C9EB76FAC45AF8E5130C81C46A35CE411\ @@ -425,17 +403,6 @@ mod tests { cipher_test(super::Type::AES_128_CTR, pt, ct, key, iv); } - // #[test] - // fn test_aes128_gcm() { - // Test case 3 in GCM spec - // let pt = ~"d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255"; - // let ct = ~"42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091473f59854d5c2af327cd64a62cf35abd2ba6fab4"; - // let key = ~"feffe9928665731c6d6a8f9467308308"; - // let iv = ~"cafebabefacedbaddecaf888"; - // - // cipher_test(super::AES_128_GCM, pt, ct, key, iv); - // } - #[test] fn test_aes128_cfb1() { // Lifted from http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf diff --git a/openssl/src/dh/mod.rs b/openssl/src/dh/mod.rs index 4ee2d890..b716ffe0 100644 --- a/openssl/src/dh/mod.rs +++ b/openssl/src/dh/mod.rs @@ -30,19 +30,19 @@ impl DH { Ok(DH(dh)) } - #[cfg(all(feature = "rfc5114", not(ossl101)))] + #[cfg(feature = "openssl-102")] pub fn get_1024_160() -> Result { let dh = try_ssl_null!(unsafe { ffi::DH_get_1024_160() }); Ok(DH(dh)) } - #[cfg(all(feature = "rfc5114", not(ossl101)))] + #[cfg(feature = "openssl-102")] pub fn get_2048_224() -> Result { let dh = try_ssl_null!(unsafe { ffi::DH_get_2048_224() }); Ok(DH(dh)) } - #[cfg(all(feature = "rfc5114", not(ossl101)))] + #[cfg(feature = "openssl-102")] pub fn get_2048_256() -> Result { let dh = try_ssl_null!(unsafe { ffi::DH_get_2048_256() }); Ok(DH(dh)) @@ -92,7 +92,7 @@ mod tests { use ssl::SslMethod::Tls; #[test] - #[cfg(all(feature = "rfc5114", not(ossl101)))] + #[cfg(feature = "openssl-102")] fn test_dh_rfc5114() { let mut ctx = SslContext::new(Tls).unwrap(); let dh1 = DH::get_1024_160().unwrap(); diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index fc1c131c..74c924cc 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -117,7 +117,7 @@ fn get_ssl_verify_data_idx() -> c_int { lazy_static! { static ref NPN_PROTOS_IDX: c_int = get_new_idx::>(); } -#[cfg(all(feature = "alpn", not(ossl101)))] +#[cfg(feature = "openssl-102")] lazy_static! { static ref ALPN_PROTOS_IDX: c_int = get_new_idx::>(); } @@ -260,7 +260,7 @@ extern fn raw_next_proto_select_cb(ssl: *mut ffi::SSL, unsafe { select_proto_using(ssl, out, outlen, inbuf, inlen, *NPN_PROTOS_IDX) } } -#[cfg(all(feature = "alpn", not(ossl101)))] +#[cfg(feature = "openssl-102")] extern fn raw_alpn_select_cb(ssl: *mut ffi::SSL, out: *mut *const c_uchar, outlen: *mut c_uchar, @@ -512,14 +512,16 @@ impl<'a> SslContextRef<'a> { /// compatible clients, and automatically select an appropriate elliptic /// curve. /// - /// This method requires OpenSSL >= 1.0.2 or LibreSSL and the `ecdh_auto` - /// feature. - #[cfg(all(feature = "ecdh_auto", not(ossl101)))] + /// This feature is always enabled on OpenSSL 1.1.0, and calling this + /// method does nothing. + /// + /// This method requires the `openssl-102` feature. + #[cfg(feature = "openssl-102")] pub fn set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> { self._set_ecdh_auto(onoff) } - #[cfg(all(feature = "ecdh_auto", ossl102))] + #[cfg(all(feature = "openssl-102", ossl102))] fn _set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> { wrap_ssl_result(unsafe { ffi::SSL_CTX_ctrl(self.as_ptr(), @@ -529,7 +531,7 @@ impl<'a> SslContextRef<'a> { }) } - #[cfg(all(feature = "ecdh_auto", ossl110))] + #[cfg(all(feature = "openssl-102", ossl110))] fn _set_ecdh_auto(&mut self, _onoff: bool) -> Result<(), ErrorStack> { Ok(()) } @@ -581,8 +583,8 @@ impl<'a> SslContextRef<'a> { /// /// Note that ordering of the protocols controls the priority with which they are chosen. /// - /// This method needs the `alpn` feature. - #[cfg(all(feature = "alpn", not(ossl101)))] + /// This method needs the `openssl-102` feature. + #[cfg(feature = "openssl-102")] pub fn set_alpn_protocols(&mut self, protocols: &[&[u8]]) { let protocols: Box> = Box::new(ssl_encode_byte_strings(protocols)); unsafe { @@ -922,7 +924,7 @@ impl<'a> SslRef<'a> { /// to interpret it. /// /// This method needs the `alpn` feature. - #[cfg(all(feature = "alpn", not(ossl101)))] + #[cfg(feature = "openssl-102")] pub fn selected_alpn_protocol(&self) -> Option<&[u8]> { unsafe { let mut data: *const c_uchar = ptr::null(); diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 01c836e7..58520930 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -104,7 +104,6 @@ impl Server { Server::new_tcp(&["-www"]) } - #[cfg(all(any(feature = "alpn", feature = "npn"), not(ossl101)))] fn new_alpn() -> (Server, TcpStream) { Server::new_tcp(&["-www", "-nextprotoneg", @@ -549,7 +548,7 @@ fn test_state() { /// Tests that connecting with the client using ALPN, but the server not does not /// break the existing connection behavior. #[test] -#[cfg(all(feature = "alpn", not(ossl101)))] +#[cfg(feature = "openssl-102")] fn test_connect_with_unilateral_alpn() { let (_s, stream) = Server::new(); let mut ctx = SslContext::new(Tls).unwrap(); @@ -571,7 +570,6 @@ fn test_connect_with_unilateral_alpn() { /// Tests that connecting with the client using NPN, but the server not does not /// break the existing connection behavior. #[test] -#[cfg(all(feature = "npn", not(ossl101)))] fn test_connect_with_unilateral_npn() { let (_s, stream) = Server::new(); let mut ctx = SslContext::new(Tls).unwrap(); @@ -593,7 +591,7 @@ fn test_connect_with_unilateral_npn() { /// Tests that when both the client as well as the server use ALPN and their /// lists of supported protocols have an overlap, the correct protocol is chosen. #[test] -#[cfg(all(feature = "alpn", not(ossl101)))] +#[cfg(feature = "openssl-102")] fn test_connect_with_alpn_successful_multiple_matching() { let (_s, stream) = Server::new_alpn(); let mut ctx = SslContext::new(Tls).unwrap(); @@ -615,7 +613,6 @@ fn test_connect_with_alpn_successful_multiple_matching() { /// Tests that when both the client as well as the server use NPN and their /// lists of supported protocols have an overlap, the correct protocol is chosen. #[test] -#[cfg(all(feature = "npn", not(ossl101)))] fn test_connect_with_npn_successful_multiple_matching() { let (_s, stream) = Server::new_alpn(); let mut ctx = SslContext::new(Tls).unwrap(); @@ -638,7 +635,7 @@ fn test_connect_with_npn_successful_multiple_matching() { /// lists of supported protocols have an overlap -- with only ONE protocol /// being valid for both. #[test] -#[cfg(all(feature = "alpn", not(ossl101)))] +#[cfg(feature = "openssl-102")] fn test_connect_with_alpn_successful_single_match() { let (_s, stream) = Server::new_alpn(); let mut ctx = SslContext::new(Tls).unwrap(); @@ -662,7 +659,6 @@ fn test_connect_with_alpn_successful_single_match() { /// lists of supported protocols have an overlap -- with only ONE protocol /// being valid for both. #[test] -#[cfg(all(feature = "npn", not(ossl101)))] fn test_connect_with_npn_successful_single_match() { let (_s, stream) = Server::new_alpn(); let mut ctx = SslContext::new(Tls).unwrap(); @@ -684,7 +680,6 @@ fn test_connect_with_npn_successful_single_match() { /// Tests that when the `SslStream` is created as a server stream, the protocols /// are correctly advertised to the client. #[test] -#[cfg(all(feature = "npn", not(ossl101)))] fn test_npn_server_advertise_multiple() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let localhost = listener.local_addr().unwrap(); @@ -725,7 +720,7 @@ fn test_npn_server_advertise_multiple() { /// Tests that when the `SslStream` is created as a server stream, the protocols /// are correctly advertised to the client. #[test] -#[cfg(all(feature = "alpn", not(ossl101)))] +#[cfg(feature = "openssl-102")] fn test_alpn_server_advertise_multiple() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let localhost = listener.local_addr().unwrap(); @@ -766,7 +761,7 @@ fn test_alpn_server_advertise_multiple() { /// Test that Servers supporting ALPN don't report a protocol when none of their protocols match /// the client's reported protocol. #[test] -#[cfg(all(feature = "alpn", not(ossl101)))] +#[cfg(feature = "openssl-102")] // TODO: not sure why this test is failing on OpenSSL 1.1.0, may be related to // something about SSLv3 though? #[cfg_attr(ossl110, ignore)] From 143556078b70c3794c95da740a21d7d7917bea68 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 13 Oct 2016 19:48:30 -0700 Subject: [PATCH 015/186] Reenable dtls tests --- openssl/src/ssl/tests/mod.rs | 32 ++++++-------------------------- 1 file changed, 6 insertions(+), 26 deletions(-) diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 58520930..e8f5da54 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -27,13 +27,10 @@ use x509::X509FileType; use x509::X509; use crypto::pkey::PKey; -#[cfg(feature="dtlsv1")] use std::net::UdpSocket; -#[cfg(feature="dtlsv1")] -use ssl::SslMethod::Dtlsv1; +use ssl::SslMethod::Dtls; #[cfg(feature="sslv2")] use ssl::SslMethod::Sslv2; -#[cfg(feature="dtlsv1")] use net2::UdpSocketExt; mod select; @@ -112,7 +109,6 @@ impl Server { "http/1.1,spdy/3.1"]) } - #[cfg(feature = "dtlsv1")] fn new_dtlsv1(input: I) -> (Server, UdpConnected) where I: IntoIterator, I::IntoIter: Send + 'static @@ -143,18 +139,15 @@ impl Drop for Server { } } -#[cfg(feature = "dtlsv1")] #[derive(Debug)] struct UdpConnected(UdpSocket); -#[cfg(feature = "dtlsv1")] impl Read for UdpConnected { fn read(&mut self, buf: &mut [u8]) -> io::Result { self.0.recv_from(buf).map(|(s, _)| s) } } -#[cfg(feature = "dtlsv1")] impl Write for UdpConnected { #[cfg(unix)] fn write(&mut self, buf: &[u8]) -> io::Result { @@ -220,10 +213,9 @@ macro_rules! run_test( } #[test] - #[cfg(feature="dtlsv1")] fn dtlsv1() { let (_s, stream) = Server::new_dtlsv1(Some("hello")); - $blk(SslMethod::Dtlsv1, stream); + $blk(SslMethod::Dtls, stream); } } ); @@ -484,11 +476,10 @@ run_test!(get_peer_certificate, |method, stream| { }); #[test] -#[cfg(feature = "dtlsv1")] fn test_write_dtlsv1() { let (_s, stream) = Server::new_dtlsv1(iter::repeat("y\n")); - let mut stream = SslStream::connect(&SslContext::new(Dtlsv1).unwrap(), stream).unwrap(); + let mut stream = SslStream::connect(&SslContext::new(Dtls).unwrap(), stream).unwrap(); stream.write_all(b"hello").unwrap(); stream.flush().unwrap(); stream.write_all(b" there").unwrap(); @@ -804,7 +795,6 @@ fn test_alpn_server_select_none() { } -#[cfg(feature="dtlsv1")] #[cfg(test)] mod dtlsv1 { use serialize::hex::FromHex; @@ -813,12 +803,12 @@ mod dtlsv1 { use crypto::hash::Type::SHA256; use ssl::SslMethod; - use ssl::SslMethod::Dtlsv1; + use ssl::SslMethod::Dtls; use ssl::{SslContext, SslStream}; use ssl::SSL_VERIFY_PEER; use x509::X509StoreContext; - const PROTOCOL: SslMethod = Dtlsv1; + const PROTOCOL: SslMethod = Dtls; #[test] fn test_new_ctx() { @@ -827,24 +817,14 @@ mod dtlsv1 { } #[test] -#[cfg(feature = "dtlsv1")] fn test_read_dtlsv1() { let (_s, stream) = Server::new_dtlsv1(Some("hello")); - let mut stream = SslStream::connect(&SslContext::new(Dtlsv1).unwrap(), stream).unwrap(); + let mut stream = SslStream::connect(&SslContext::new(Dtls).unwrap(), stream).unwrap(); let mut buf = [0u8; 100]; assert!(stream.read(&mut buf).is_ok()); } -#[test] -#[cfg(feature = "sslv2")] -fn test_sslv2_connect_failure() { - let (_s, tcp) = Server::new_tcp(&["-no_ssl2", "-www"]); - SslStream::connect(&SslContext::new(Sslv2).unwrap(), tcp) - .err() - .unwrap(); -} - fn wait_io(stream: &TcpStream, read: bool, timeout_ms: u32) -> bool { unsafe { let mut set: select::fd_set = mem::zeroed(); From 140ef1b98845594fea6b8d5a5409453320b0def9 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 13 Oct 2016 20:01:31 -0700 Subject: [PATCH 016/186] Fix tests on windows --- openssl/src/ssl/tests/mod.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index e8f5da54..2cd4e05e 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -169,12 +169,13 @@ impl Write for UdpConnected { #[cfg(windows)] fn write(&mut self, buf: &[u8]) -> io::Result { use std::os::windows::prelude::*; - use libc; + use ws2_32; + let n = unsafe { - libc::send(self.0.as_raw_socket(), - buf.as_ptr() as *const _, - buf.len() as libc::c_int, - 0) + ws2_32::send(self.0.as_raw_socket(), + buf.as_ptr() as *const _, + buf.len() as libc::c_int, + 0) }; if n < 0 { Err(io::Error::last_os_error()) From 5b29fc9d6954e32cc20482e5e3d1d65f8d7cf252 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 13 Oct 2016 20:03:02 -0700 Subject: [PATCH 017/186] Disable npn tests on < 1.0.2 s_client doesn't seem to support the required flag before then. --- openssl/src/ssl/tests/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 2cd4e05e..f5078648 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -605,6 +605,7 @@ fn test_connect_with_alpn_successful_multiple_matching() { /// Tests that when both the client as well as the server use NPN and their /// lists of supported protocols have an overlap, the correct protocol is chosen. #[test] +#[cfg(feature = "openssl-102")] fn test_connect_with_npn_successful_multiple_matching() { let (_s, stream) = Server::new_alpn(); let mut ctx = SslContext::new(Tls).unwrap(); @@ -651,6 +652,7 @@ fn test_connect_with_alpn_successful_single_match() { /// lists of supported protocols have an overlap -- with only ONE protocol /// being valid for both. #[test] +#[cfg(feature = "openssl-102")] fn test_connect_with_npn_successful_single_match() { let (_s, stream) = Server::new_alpn(); let mut ctx = SslContext::new(Tls).unwrap(); From a09f46266d7f2f42a019a13e31ffaa7067577130 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 13 Oct 2016 20:06:01 -0700 Subject: [PATCH 018/186] Fix windows for real --- openssl/src/ssl/tests/mod.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index f5078648..0140e283 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -168,8 +168,9 @@ impl Write for UdpConnected { #[cfg(windows)] fn write(&mut self, buf: &[u8]) -> io::Result { + extern crate ws2_32; use std::os::windows::prelude::*; - use ws2_32; + use libc; let n = unsafe { ws2_32::send(self.0.as_raw_socket(), From 3d535f661f8ae2b402abf212f3d89404eedab498 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 13 Oct 2016 20:15:26 -0700 Subject: [PATCH 019/186] Use stdlib logic for udp --- openssl/src/lib.rs | 3 --- openssl/src/ssl/tests/mod.rs | 40 ++---------------------------------- 2 files changed, 2 insertions(+), 41 deletions(-) diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index 66c767dc..aa34753c 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -10,9 +10,6 @@ extern crate openssl_sys as ffi; #[cfg(test)] extern crate rustc_serialize as serialize; -#[cfg(test)] -extern crate net2; - #[cfg(test)] extern crate tempdir; diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 0140e283..2e362b5e 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -12,7 +12,6 @@ use std::process::{Command, Child, Stdio, ChildStdin}; use std::thread; use std::time::Duration; -use net2::TcpStreamExt; use tempdir::TempDir; use crypto::hash::Type::SHA256; @@ -29,9 +28,6 @@ use crypto::pkey::PKey; use std::net::UdpSocket; use ssl::SslMethod::Dtls; -#[cfg(feature="sslv2")] -use ssl::SslMethod::Sslv2; -use net2::UdpSocketExt; mod select; @@ -144,45 +140,13 @@ struct UdpConnected(UdpSocket); impl Read for UdpConnected { fn read(&mut self, buf: &mut [u8]) -> io::Result { - self.0.recv_from(buf).map(|(s, _)| s) + self.0.recv(buf) } } impl Write for UdpConnected { - #[cfg(unix)] fn write(&mut self, buf: &[u8]) -> io::Result { - use std::os::unix::prelude::*; - use libc; - let n = unsafe { - libc::send(self.0.as_raw_fd(), - buf.as_ptr() as *const _, - buf.len() as libc::size_t, - 0) - }; - if n < 0 { - Err(io::Error::last_os_error()) - } else { - Ok(n as usize) - } - } - - #[cfg(windows)] - fn write(&mut self, buf: &[u8]) -> io::Result { - extern crate ws2_32; - use std::os::windows::prelude::*; - use libc; - - let n = unsafe { - ws2_32::send(self.0.as_raw_socket(), - buf.as_ptr() as *const _, - buf.len() as libc::c_int, - 0) - }; - if n < 0 { - Err(io::Error::last_os_error()) - } else { - Ok(n as usize) - } + self.0.send(buf) } fn flush(&mut self) -> io::Result<()> { From f44cff29e658987b980a6927958d9bed334232ad Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 13 Oct 2016 22:34:39 -0700 Subject: [PATCH 020/186] Cleanup --- openssl/src/ssl/mod.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 74c924cc..0bd3272b 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -75,10 +75,8 @@ bitflags! { } /// Determines the SSL method supported -#[allow(non_camel_case_types)] #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] pub enum SslMethod { - // TODO: support more methods /// Support the TLS protocol Tls, /// Support DTLS protocol From 0908fddc7460529f4536b22516da20d3b89c993a Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Fri, 14 Oct 2016 11:15:22 -0700 Subject: [PATCH 021/186] Ignore DTLS tests on Windows/ARM for now cc #467 --- openssl/src/ssl/tests/mod.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 2e362b5e..f86895e5 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -179,6 +179,7 @@ macro_rules! run_test( } #[test] + #[cfg_attr(any(windows, target_arch = "arm"), ignore)] // FIXME(#467) fn dtlsv1() { let (_s, stream) = Server::new_dtlsv1(Some("hello")); $blk(SslMethod::Dtls, stream); @@ -442,6 +443,7 @@ run_test!(get_peer_certificate, |method, stream| { }); #[test] +#[cfg_attr(any(windows, target_arch = "arm"), ignore)] // FIXME(#467) fn test_write_dtlsv1() { let (_s, stream) = Server::new_dtlsv1(iter::repeat("y\n")); @@ -785,6 +787,7 @@ mod dtlsv1 { } #[test] +#[cfg_attr(any(windows, target_arch = "arm"), ignore)] // FIXME(#467) fn test_read_dtlsv1() { let (_s, stream) = Server::new_dtlsv1(Some("hello")); @@ -862,7 +865,7 @@ fn test_write_nonblocking() { } #[test] -#[cfg_attr(windows, ignore)] // FIXME flickers on appveyor +#[cfg_attr(any(windows, target_arch = "arm"), ignore)] // FIXME(#467) fn test_read_nonblocking() { let (_s, stream) = Server::new(); stream.set_nonblocking(true).unwrap(); From ae282a78e2c16dda2a7594b86a77334d6afdd40e Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 14 Oct 2016 16:15:50 -0700 Subject: [PATCH 022/186] Remove link_name usage --- openssl-sys/src/lib.rs | 4 ---- openssl-sys/src/ossl10x.rs | 2 ++ openssl-sys/src/ossl110.rs | 2 ++ openssl/src/crypto/hash.rs | 11 ++++++++--- 4 files changed, 12 insertions(+), 7 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index e3c5bd95..de201332 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -466,11 +466,7 @@ extern { pub fn EVP_DigestFinal(ctx: *mut EVP_MD_CTX, res: *mut u8, n: *mut u32) -> c_int; pub fn EVP_DigestFinal_ex(ctx: *mut EVP_MD_CTX, res: *mut u8, n: *mut u32) -> c_int; - #[cfg_attr(any(ossl101, ossl102), link_name = "EVP_MD_CTX_create")] - pub fn EVP_MD_CTX_new() -> *mut EVP_MD_CTX; pub fn EVP_MD_CTX_copy_ex(dst: *mut EVP_MD_CTX, src: *const EVP_MD_CTX) -> c_int; - #[cfg_attr(any(ossl101, ossl102), link_name = "EVP_MD_CTX_destroy")] - pub fn EVP_MD_CTX_free(ctx: *mut EVP_MD_CTX); pub fn EVP_PKEY_new() -> *mut EVP_PKEY; pub fn EVP_PKEY_free(k: *mut EVP_PKEY); diff --git a/openssl-sys/src/ossl10x.rs b/openssl-sys/src/ossl10x.rs index 8420846a..70514cc8 100644 --- a/openssl-sys/src/ossl10x.rs +++ b/openssl-sys/src/ossl10x.rs @@ -559,6 +559,8 @@ extern { type_: c_int, file: *const c_char, line: c_int) -> c_int; + pub fn EVP_MD_CTX_create() -> *mut EVP_MD_CTX; + pub fn EVP_MD_CTX_destroy(ctx: *mut EVP_MD_CTX); pub fn sk_free(st: *mut _STACK); pub fn sk_pop_free(st: *mut _STACK, free: Option); diff --git a/openssl-sys/src/ossl110.rs b/openssl-sys/src/ossl110.rs index 62a66cd5..5fee4045 100644 --- a/openssl-sys/src/ossl110.rs +++ b/openssl-sys/src/ossl110.rs @@ -137,6 +137,8 @@ extern { pub fn X509_up_ref(x: *mut X509) -> c_int; pub fn SSL_CTX_up_ref(x: *mut SSL_CTX) -> c_int; pub fn X509_get0_extensions(req: *const ::X509) -> *const stack_st_X509_EXTENSION; + pub fn EVP_MD_CTX_new() -> *mut EVP_MD_CTX; + pub fn EVP_MD_CTX_free(ctx: *mut EVP_MD_CTX); pub fn OpenSSL_version_num() -> c_ulong; pub fn OpenSSL_version(key: c_int) -> *const c_char; diff --git a/openssl/src/crypto/hash.rs b/openssl/src/crypto/hash.rs index d87c43c5..e3bf4997 100644 --- a/openssl/src/crypto/hash.rs +++ b/openssl/src/crypto/hash.rs @@ -3,6 +3,11 @@ use std::io; use std::ptr; use ffi; +#[cfg(ossl110)] +use ffi::{EVP_MD_CTX_new, EVP_MD_CTX_free}; +#[cfg(any(ossl101, ossl102))] +use ffi::{EVP_MD_CTX_create as EVP_MD_CTX_new, EVP_MD_CTX_destroy as EVP_MD_CTX_free}; + use HashTypeInternals; use error::ErrorStack; use nid::Nid; @@ -100,7 +105,7 @@ impl Hasher { pub fn new(ty: Type) -> Result { ffi::init(); - let ctx = unsafe { try_ssl_null!(ffi::EVP_MD_CTX_new()) }; + let ctx = unsafe { try_ssl_null!(EVP_MD_CTX_new()) }; let md = ty.evp_md(); let mut h = Hasher { @@ -172,7 +177,7 @@ impl Write for Hasher { impl Clone for Hasher { fn clone(&self) -> Hasher { let ctx = unsafe { - let ctx = ffi::EVP_MD_CTX_new(); + let ctx = EVP_MD_CTX_new(); assert!(!ctx.is_null()); let r = ffi::EVP_MD_CTX_copy_ex(ctx, self.ctx); assert_eq!(r, 1); @@ -193,7 +198,7 @@ impl Drop for Hasher { if self.state != Finalized { drop(self.finish()); } - ffi::EVP_MD_CTX_free(self.ctx); + EVP_MD_CTX_free(self.ctx); } } } From af51b263b17faaa3e7cb0ecc5c305b858faea64c Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 14 Oct 2016 17:39:31 -0700 Subject: [PATCH 023/186] Support hostname verification Closes #206 --- openssl-sys/src/ossl110.rs | 49 +++++++++++++++++++++++------------- openssl/src/ssl/mod.rs | 12 +++++++++ openssl/src/ssl/tests/mod.rs | 44 ++++++++++++++++++++++++++++++++ openssl/src/x509/mod.rs | 3 +++ openssl/src/x509/verify.rs | 41 ++++++++++++++++++++++++++++++ 5 files changed, 132 insertions(+), 17 deletions(-) create mode 100644 openssl/src/x509/verify.rs diff --git a/openssl-sys/src/ossl110.rs b/openssl-sys/src/ossl110.rs index 5fee4045..20cd0940 100644 --- a/openssl-sys/src/ossl110.rs +++ b/openssl-sys/src/ossl110.rs @@ -1,25 +1,28 @@ -use libc::{c_int, c_void, c_char, c_uchar, c_ulong, c_long}; +use libc::{c_int, c_void, c_char, c_uchar, c_ulong, c_long, c_uint, size_t}; +pub enum BIGNUM {} +pub enum BIO {} +pub enum BIO_METHOD {} +pub enum CRYPTO_EX_DATA {} +pub enum DH {} +pub enum DSA {} +pub enum EVP_CIPHER {} +pub enum EVP_MD_CTX {} +pub enum EVP_PKEY {} +pub enum HMAC_CTX {} +pub enum OPENSSL_STACK {} +pub enum RSA {} +pub enum SSL_CTX {} +pub enum _STACK {} +pub enum stack_st_ASN1_OBJECT {} +pub enum stack_st_GENERAL_NAME {} +pub enum stack_st_OPENSSL_STRING {} +pub enum stack_st_void {} pub enum stack_st_X509 {} pub enum stack_st_X509_ATTRIBUTE {} pub enum stack_st_X509_EXTENSION {} -pub enum stack_st_GENERAL_NAME {} -pub enum stack_st_void {} -pub enum _STACK {} -pub enum BIO_METHOD {} -pub enum RSA {} -pub enum DSA {} -pub enum EVP_PKEY {} -pub enum BIO {} -pub enum CRYPTO_EX_DATA {} -pub enum EVP_MD_CTX {} -pub enum EVP_CIPHER {} -pub enum HMAC_CTX {} -pub enum BIGNUM {} -pub enum OPENSSL_STACK {} -pub enum DH {} pub enum X509 {} -pub enum SSL_CTX {} +pub enum X509_VERIFY_PARAM {} pub const SSL_OP_MICROSOFT_SESS_ID_BUG: c_ulong = 0x00000000; pub const SSL_OP_NETSCAPE_CHALLENGE_BUG: c_ulong = 0x00000000; @@ -41,6 +44,13 @@ pub const OPENSSL_DIR: c_int = 4; pub const CRYPTO_EX_INDEX_SSL: c_int = 0; pub const CRYPTO_EX_INDEX_SSL_CTX: c_int = 1; +pub const X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT: c_uint = 0x1; +pub const X509_CHECK_FLAG_NO_WILDCARDS: c_uint = 0x2; +pub const X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS: c_uint = 0x4; +pub const X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS: c_uint = 0x8; +pub const X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS: c_uint = 0x10; +pub const X509_CHECK_FLAG_NEVER_CHECK_SUBJECT: c_uint = 0x20; + pub fn init() {} extern { @@ -96,8 +106,13 @@ extern { pub fn SSL_CTX_get_options(ctx: *const ::SSL_CTX) -> c_ulong; pub fn SSL_CTX_set_options(ctx: *mut ::SSL_CTX, op: c_ulong) -> c_ulong; pub fn SSL_CTX_clear_options(ctx: *mut ::SSL_CTX, op: c_ulong) -> c_ulong; + pub fn SSL_get0_param(ssl: *mut ::SSL) -> *mut X509_VERIFY_PARAM; pub fn X509_getm_notAfter(x: *const ::X509) -> *mut ::ASN1_TIME; pub fn X509_getm_notBefore(x: *const ::X509) -> *mut ::ASN1_TIME; + pub fn X509_VERIFY_PARAM_set_hostflags(param: *mut X509_VERIFY_PARAM, flags: c_uint); + pub fn X509_VERIFY_PARAM_set1_host(param: *mut X509_VERIFY_PARAM, + name: *const c_char, + namelen: size_t) -> c_int; pub fn DH_set0_pqg(dh: *mut ::DH, p: *mut ::BIGNUM, q: *mut ::BIGNUM, diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 0bd3272b..a3c35f3a 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -22,6 +22,8 @@ use ffi; use init; use dh::DH; use x509::{X509StoreContext, X509FileType, X509, X509Ref}; +#[cfg(feature = "openssl-110")] +use x509::verify::X509VerifyParamRef; use crypto::pkey::PKey; use error::ErrorStack; @@ -988,6 +990,16 @@ impl<'a> SslRef<'a> { SslContextRef::from_ptr(ssl_ctx) } } + + /// Returns the X509 verification configuration. + /// + /// Requires the `openssl-110` feature. + #[cfg(feature = "openssl-110")] + pub fn param(&mut self) -> X509VerifyParamRef<'a> { + unsafe { + X509VerifyParamRef::from_ptr(ffi::SSL_get0_param(self.as_ptr())) + } + } } pub struct Ssl(SslRef<'static>); diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index f86895e5..6dba713f 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -21,9 +21,13 @@ use ssl::SslMethod::Tls; use ssl::{SslMethod, HandshakeError}; use ssl::error::Error; use ssl::{SslContext, SslStream}; +#[cfg(feature = "openssl-110")] +use ssl::IntoSsl; use x509::X509StoreContext; use x509::X509FileType; use x509::X509; +#[cfg(feature = "openssl-110")] +use x509::verify::X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS; use crypto::pkey::PKey; use std::net::UdpSocket; @@ -1042,3 +1046,43 @@ fn add_extra_chain_cert() { let mut ctx = SslContext::new(SslMethod::Tls).unwrap(); ctx.add_extra_chain_cert(&cert).unwrap(); } + +#[test] +#[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( +#[cfg(feature = "openssl-110")] +fn valid_hostname() { + let mut ctx = SslContext::new(SslMethod::Tls).unwrap(); + ctx.set_default_verify_paths().unwrap(); + ctx.set_verify(SSL_VERIFY_PEER); + + let mut ssl = ctx.into_ssl().unwrap(); + ssl.param().set_hostflags(X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); + ssl.param().set_host("google.com").unwrap(); + + let s = TcpStream::connect("google.com:443").unwrap(); + let mut socket = SslStream::connect(ssl, s).unwrap(); + + socket.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); + let mut result = vec![]; + socket.read_to_end(&mut result).unwrap(); + + println!("{}", String::from_utf8_lossy(&result)); + assert!(result.starts_with(b"HTTP/1.0")); + assert!(result.ends_with(b"\r\n") || result.ends_with(b"")); +} + +#[test] +#[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( +#[cfg(feature = "openssl-110")] +fn invalid_hostname() { + let mut ctx = SslContext::new(SslMethod::Tls).unwrap(); + ctx.set_default_verify_paths().unwrap(); + ctx.set_verify(SSL_VERIFY_PEER); + + let mut ssl = ctx.into_ssl().unwrap(); + ssl.param().set_hostflags(X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); + ssl.param().set_host("foobar.com").unwrap(); + + let s = TcpStream::connect("google.com:443").unwrap(); + assert!(SslStream::connect(ssl, s).is_err()); +} diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 086342dd..5b65e866 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -38,6 +38,9 @@ use ffi::{ pub mod extension; +#[cfg(feature = "openssl-110")] +pub mod verify; + use self::extension::{ExtensionType, Extension}; #[cfg(test)] diff --git a/openssl/src/x509/verify.rs b/openssl/src/x509/verify.rs new file mode 100644 index 00000000..683836e8 --- /dev/null +++ b/openssl/src/x509/verify.rs @@ -0,0 +1,41 @@ +use std::marker::PhantomData; +use libc::c_uint; +use ffi; + +use error::ErrorStack; + +bitflags! { + pub flags X509CheckFlags: c_uint { + const X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT = ffi::X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT, + const X509_CHECK_FLAG_NO_WILDCARDS = ffi::X509_CHECK_FLAG_NO_WILDCARDS, + const X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS = ffi::X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS, + const X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS = ffi::X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS, + const X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS + = ffi::X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS, + const X509_CHECK_FLAG_NEVER_CHECK_SUBJECT = ffi::X509_CHECK_FLAG_NEVER_CHECK_SUBJECT, + } +} + +pub struct X509VerifyParamRef<'a>(*mut ffi::X509_VERIFY_PARAM, PhantomData<&'a mut ()>); + +impl<'a> X509VerifyParamRef<'a> { + pub unsafe fn from_ptr(ptr: *mut ffi::X509_VERIFY_PARAM) -> X509VerifyParamRef<'a> { + X509VerifyParamRef(ptr, PhantomData) + } + + pub fn set_hostflags(&mut self, hostflags: X509CheckFlags) { + unsafe { + ffi::X509_VERIFY_PARAM_set_hostflags(self.0, hostflags.bits); + } + } + + pub fn set_host(&mut self, host: &str) -> Result<(), ErrorStack> { + unsafe { + try_ssl!(ffi::X509_VERIFY_PARAM_set1_host(self.0, + host.as_ptr() as *const _, + host.len())) + } + + Ok(()) + } +} From d976b8f59558f57561bd37b037955b47a328902f Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 14 Oct 2016 18:04:31 -0700 Subject: [PATCH 024/186] Enable hostname verification on 1.0.2 --- openssl-sys/src/lib.rs | 24 +++++++++++++++++++++--- openssl-sys/src/ossl10x.rs | 24 +++++++++++++++++++++++- openssl-sys/src/ossl110.rs | 12 +----------- openssl/src/ssl/mod.rs | 6 +++--- openssl/src/ssl/tests/mod.rs | 8 ++++---- openssl/src/x509/mod.rs | 2 +- openssl/src/x509/verify.rs | 1 + 7 files changed, 54 insertions(+), 23 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index de201332..300ed056 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -252,6 +252,17 @@ pub const X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE: c_int = 45; pub const X509_V_ERR_UNSUPPORTED_NAME_SYNTAX: c_int = 53; pub const X509_V_OK: c_int = 0; +#[cfg(not(ossl101))] +pub const X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT: c_uint = 0x1; +#[cfg(not(ossl101))] +pub const X509_CHECK_FLAG_NO_WILDCARDS: c_uint = 0x2; +#[cfg(not(ossl101))] +pub const X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS: c_uint = 0x4; +#[cfg(not(ossl101))] +pub const X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS: c_uint = 0x8; +#[cfg(not(ossl101))] +pub const X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS: c_uint = 0x10; + pub const GEN_OTHERNAME: c_int = 0; pub const GEN_EMAIL: c_int = 1; pub const GEN_DNS: c_int = 2; @@ -587,13 +598,13 @@ extern { verify_callback: Option c_int>); pub fn SSL_set_ex_data(ssl: *mut SSL, idx: c_int, data: *mut c_void) -> c_int; pub fn SSL_get_ex_data(ssl: *const SSL, idx: c_int) -> *mut c_void; - pub fn SSL_get_servername(ssl: *const SSL, name_type: c_int) -> *const c_char; + pub fn SSL_get_current_cipher(ssl: *const SSL) -> *const SSL_CIPHER; + #[cfg(not(ossl101))] + pub fn SSL_get0_param(ssl: *mut ::SSL) -> *mut X509_VERIFY_PARAM; pub fn SSL_COMP_get_name(comp: *const COMP_METHOD) -> *const c_char; - pub fn SSL_get_current_cipher(ssl: *const SSL) -> *const SSL_CIPHER; - pub fn SSL_CIPHER_get_name(cipher: *const SSL_CIPHER) -> *const c_char; pub fn SSL_CIPHER_get_bits(cipher: *const SSL_CIPHER, alg_bits: *mut c_int) -> c_int; pub fn SSL_CIPHER_description(cipher: *const SSL_CIPHER, buf: *mut c_char, size: c_int) -> *mut c_char; @@ -693,6 +704,13 @@ extern { 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; + #[cfg(not(ossl101))] + pub fn X509_VERIFY_PARAM_set_hostflags(param: *mut X509_VERIFY_PARAM, flags: c_uint); + #[cfg(not(ossl101))] + pub fn X509_VERIFY_PARAM_set1_host(param: *mut X509_VERIFY_PARAM, + name: *const c_char, + namelen: size_t) -> c_int; + pub fn d2i_X509(a: *mut *mut X509, pp: *mut *const c_uchar, length: c_long) -> *mut X509; pub fn i2d_X509_bio(b: *mut BIO, x: *mut X509) -> c_int; pub fn i2d_X509_REQ_bio(b: *mut BIO, x: *mut X509_REQ) -> c_int; diff --git a/openssl-sys/src/ossl10x.rs b/openssl-sys/src/ossl10x.rs index 70514cc8..86451a0c 100644 --- a/openssl-sys/src/ossl10x.rs +++ b/openssl-sys/src/ossl10x.rs @@ -2,7 +2,12 @@ use std::sync::{Mutex, MutexGuard}; use std::sync::{Once, ONCE_INIT}; use std::mem; -use libc::{c_int, c_char, c_void, c_long, c_uchar, size_t, c_uint, c_ulong}; +use libc::{c_int, c_char, c_void, c_long, c_uchar, size_t, c_uint, c_ulong, time_t}; + +#[repr(C)] +pub struct stack_st_ASN1_OBJECT { + pub stack: _STACK, +} #[repr(C)] pub struct stack_st_X509 { @@ -425,6 +430,23 @@ pub struct SRP_CTX { srp_Mask: c_ulong, } +#[repr(C)] +#[cfg(not(ossl101))] +pub struct X509_VERIFY_PARAM { + pub name: *mut c_char, + pub check_time: time_t, + pub inh_flags: c_ulong, + pub flags: c_ulong, + pub purpose: c_int, + pub trust: c_int, + pub depth: c_int, + pub policies: *mut stack_st_ASN1_OBJECT, + pub id: *mut X509_VERIFY_PARAM_ID, +} + +#[cfg(not(ossl101))] +pub enum X509_VERIFY_PARAM_ID {} + pub const SSL_CTRL_OPTIONS: c_int = 32; pub const SSL_CTRL_CLEAR_OPTIONS: c_int = 77; #[cfg(ossl102)] diff --git a/openssl-sys/src/ossl110.rs b/openssl-sys/src/ossl110.rs index 20cd0940..1a7c9e00 100644 --- a/openssl-sys/src/ossl110.rs +++ b/openssl-sys/src/ossl110.rs @@ -1,4 +1,4 @@ -use libc::{c_int, c_void, c_char, c_uchar, c_ulong, c_long, c_uint, size_t}; +use libc::{c_int, c_void, c_char, c_uchar, c_ulong, c_long, c_uint}; pub enum BIGNUM {} pub enum BIO {} @@ -44,11 +44,6 @@ pub const OPENSSL_DIR: c_int = 4; pub const CRYPTO_EX_INDEX_SSL: c_int = 0; pub const CRYPTO_EX_INDEX_SSL_CTX: c_int = 1; -pub const X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT: c_uint = 0x1; -pub const X509_CHECK_FLAG_NO_WILDCARDS: c_uint = 0x2; -pub const X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS: c_uint = 0x4; -pub const X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS: c_uint = 0x8; -pub const X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS: c_uint = 0x10; pub const X509_CHECK_FLAG_NEVER_CHECK_SUBJECT: c_uint = 0x20; pub fn init() {} @@ -106,13 +101,8 @@ extern { pub fn SSL_CTX_get_options(ctx: *const ::SSL_CTX) -> c_ulong; pub fn SSL_CTX_set_options(ctx: *mut ::SSL_CTX, op: c_ulong) -> c_ulong; pub fn SSL_CTX_clear_options(ctx: *mut ::SSL_CTX, op: c_ulong) -> c_ulong; - pub fn SSL_get0_param(ssl: *mut ::SSL) -> *mut X509_VERIFY_PARAM; pub fn X509_getm_notAfter(x: *const ::X509) -> *mut ::ASN1_TIME; pub fn X509_getm_notBefore(x: *const ::X509) -> *mut ::ASN1_TIME; - pub fn X509_VERIFY_PARAM_set_hostflags(param: *mut X509_VERIFY_PARAM, flags: c_uint); - pub fn X509_VERIFY_PARAM_set1_host(param: *mut X509_VERIFY_PARAM, - name: *const c_char, - namelen: size_t) -> c_int; pub fn DH_set0_pqg(dh: *mut ::DH, p: *mut ::BIGNUM, q: *mut ::BIGNUM, diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index a3c35f3a..b042d81e 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -22,7 +22,7 @@ use ffi; use init; use dh::DH; use x509::{X509StoreContext, X509FileType, X509, X509Ref}; -#[cfg(feature = "openssl-110")] +#[cfg(feature = "openssl-102")] use x509::verify::X509VerifyParamRef; use crypto::pkey::PKey; use error::ErrorStack; @@ -993,8 +993,8 @@ impl<'a> SslRef<'a> { /// Returns the X509 verification configuration. /// - /// Requires the `openssl-110` feature. - #[cfg(feature = "openssl-110")] + /// Requires the `openssl-102` feature. + #[cfg(feature = "openssl-102")] pub fn param(&mut self) -> X509VerifyParamRef<'a> { unsafe { X509VerifyParamRef::from_ptr(ffi::SSL_get0_param(self.as_ptr())) diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 6dba713f..b3500105 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -21,12 +21,12 @@ use ssl::SslMethod::Tls; use ssl::{SslMethod, HandshakeError}; use ssl::error::Error; use ssl::{SslContext, SslStream}; -#[cfg(feature = "openssl-110")] +#[cfg(feature = "openssl-102")] use ssl::IntoSsl; use x509::X509StoreContext; use x509::X509FileType; use x509::X509; -#[cfg(feature = "openssl-110")] +#[cfg(feature = "openssl-102")] use x509::verify::X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS; use crypto::pkey::PKey; @@ -1049,7 +1049,7 @@ fn add_extra_chain_cert() { #[test] #[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( -#[cfg(feature = "openssl-110")] +#[cfg(feature = "openssl-102")] fn valid_hostname() { let mut ctx = SslContext::new(SslMethod::Tls).unwrap(); ctx.set_default_verify_paths().unwrap(); @@ -1073,7 +1073,7 @@ fn valid_hostname() { #[test] #[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( -#[cfg(feature = "openssl-110")] +#[cfg(feature = "openssl-102")] fn invalid_hostname() { let mut ctx = SslContext::new(SslMethod::Tls).unwrap(); ctx.set_default_verify_paths().unwrap(); diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 5b65e866..9fed94e2 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -38,7 +38,7 @@ use ffi::{ pub mod extension; -#[cfg(feature = "openssl-110")] +#[cfg(feature = "openssl-102")] pub mod verify; use self::extension::{ExtensionType, Extension}; diff --git a/openssl/src/x509/verify.rs b/openssl/src/x509/verify.rs index 683836e8..0fc1df3a 100644 --- a/openssl/src/x509/verify.rs +++ b/openssl/src/x509/verify.rs @@ -12,6 +12,7 @@ bitflags! { const X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS = ffi::X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS, const X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS = ffi::X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS, + #[cfg(feature = "openssl-110")] const X509_CHECK_FLAG_NEVER_CHECK_SUBJECT = ffi::X509_CHECK_FLAG_NEVER_CHECK_SUBJECT, } } From d7a433bdef4bd232c00cddff1a18569b23903ba4 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 14 Oct 2016 19:16:08 -0700 Subject: [PATCH 025/186] Respect osslconf in systest Also cfg off SSLv3_method, since it's disabled in the OpenSSL that ships with Arch Linux. More such flags can be added on demand - it doesn't seem worth auditing everything for them. --- openssl-sys/build.rs | 3 +++ openssl-sys/src/ossl10x.rs | 1 + systest/build.rs | 5 +++++ 3 files changed, 9 insertions(+) diff --git a/openssl-sys/build.rs b/openssl-sys/build.rs index 9f5b3877..b6540368 100644 --- a/openssl-sys/build.rs +++ b/openssl-sys/build.rs @@ -283,6 +283,7 @@ The build is now aborting due to this version mismatch. // Look for `#define OPENSSL_FOO`, print out everything as our own // #[cfg] flag. + let mut vars = vec![]; for line in conf_header.lines() { let i = match line.find("define ") { Some(i) => i, @@ -291,8 +292,10 @@ The build is now aborting due to this version mismatch. let var = line[i + "define ".len()..].trim(); if var.starts_with("OPENSSL") && !var.contains(" ") { println!("cargo:rustc-cfg=osslconf=\"{}\"", var); + vars.push(var); } } + println!("cargo:osslconf={}", vars.join(",")); } return version_text.to_string() diff --git a/openssl-sys/src/ossl10x.rs b/openssl-sys/src/ossl10x.rs index 86451a0c..16d669b0 100644 --- a/openssl-sys/src/ossl10x.rs +++ b/openssl-sys/src/ossl10x.rs @@ -549,6 +549,7 @@ extern { pub fn OPENSSL_add_all_algorithms_noconf(); pub fn HMAC_CTX_init(ctx: *mut ::HMAC_CTX); pub fn HMAC_CTX_cleanup(ctx: *mut ::HMAC_CTX); + #[cfg(not(osslconf = "OPENSSL_NO_SSL3_METHOD"))] pub fn SSLv3_method() -> *const ::SSL_METHOD; pub fn TLSv1_method() -> *const ::SSL_METHOD; pub fn SSLv23_method() -> *const ::SSL_METHOD; diff --git a/systest/build.rs b/systest/build.rs index b2820e5b..94c5534e 100644 --- a/systest/build.rs +++ b/systest/build.rs @@ -31,6 +31,11 @@ fn main() { if env::var("DEP_OPENSSL_IS_110").is_ok() { cfg.cfg("ossl110", None); } + if let Ok(vars) = env::var("DEP_OPENSSL_OSSLCONF") { + for var in vars.split(",") { + cfg.cfg("osslconf", Some(var)); + } + } cfg.header("openssl/comp.h") .header("openssl/dh.h") From f520aa2860dcb8f995a8fa5bd602916f96de1d8a Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 14 Oct 2016 20:50:45 -0700 Subject: [PATCH 026/186] Handle OPENSSL_NO_COMP Closes #459 --- openssl-sys/src/lib.rs | 2 ++ openssl/build.rs | 5 +++++ openssl/src/ssl/mod.rs | 10 ++++++++++ 3 files changed, 17 insertions(+) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 300ed056..482317ff 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -587,6 +587,7 @@ extern { pub fn SSL_get_ex_data_X509_STORE_CTX_idx() -> c_int; pub fn SSL_get_SSL_CTX(ssl: *const SSL) -> *mut SSL_CTX; pub fn SSL_set_SSL_CTX(ssl: *mut SSL, ctx: *mut SSL_CTX) -> *mut SSL_CTX; + #[cfg(not(osslconf = "OPENSSL_NO_COMP"))] pub fn SSL_get_current_compression(ssl: *mut SSL) -> *const COMP_METHOD; pub fn SSL_get_peer_certificate(ssl: *const SSL) -> *mut X509; pub fn SSL_get_ssl_method(ssl: *mut SSL) -> *const SSL_METHOD; @@ -603,6 +604,7 @@ extern { #[cfg(not(ossl101))] pub fn SSL_get0_param(ssl: *mut ::SSL) -> *mut X509_VERIFY_PARAM; + #[cfg(not(osslconf = "OPENSSL_NO_COMP"))] pub fn SSL_COMP_get_name(comp: *const COMP_METHOD) -> *const c_char; pub fn SSL_CIPHER_get_name(cipher: *const SSL_CIPHER) -> *const c_char; diff --git a/openssl/build.rs b/openssl/build.rs index 15d4b4db..dd832150 100644 --- a/openssl/build.rs +++ b/openssl/build.rs @@ -12,4 +12,9 @@ fn main() { if env::var("DEP_OPENSSL_IS_110").is_ok() { println!("cargo:rustc-cfg=ossl110"); } + if let Ok(vars) = env::var("DEP_OPENSSL_OSSLCONF") { + for var in vars.split(",") { + println!("cargo:rustc-cfg=osslconf=\"{}\"", var); + } + } } diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index b042d81e..076ac400 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -952,6 +952,11 @@ impl<'a> SslRef<'a> { /// The result will be either None, indicating no compression is in use, or /// a string with the compression name. pub fn compression(&self) -> Option { + self._compression() + } + + #[cfg(not(osslconf = "OPENSSL_NO_COMP"))] + fn _compression(&self) -> Option { let ptr = unsafe { ffi::SSL_get_current_compression(self.as_ptr()) }; if ptr == ptr::null() { return None; @@ -965,6 +970,11 @@ impl<'a> SslRef<'a> { Some(s) } + #[cfg(osslconf = "OPENSSL_NO_COMP")] + fn _compression(&self) -> Option { + None + } + /// Returns the server's name for the current connection pub fn servername(&self) -> Option { let name = unsafe { ffi::SSL_get_servername(self.as_ptr(), ffi::TLSEXT_NAMETYPE_host_name) }; From 7ac05996388af40e78696c5ed2d9e0426eea1881 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 14 Oct 2016 21:54:53 -0700 Subject: [PATCH 027/186] Fix test_alpn_server_select_none In OpenSSL 1.1, a failure to negotiate a protocol is a fatal error, so fork that test. This also popped up an issue where we assumed all errors had library, function, and reason strings which is not necessarily the case. While we're in here, adjust the Display impl to match what OpenSSL prints out. Closes #465 --- openssl-sys/src/lib.rs | 12 +++++ openssl/src/error.rs | 96 ++++++++++++++++++++---------------- openssl/src/ssl/tests/mod.rs | 46 ++++++++++++----- 3 files changed, 100 insertions(+), 54 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 300ed056..026d6e6b 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -318,6 +318,18 @@ pub unsafe fn SSL_set_tlsext_host_name(s: *mut SSL, name: *mut c_char) -> c_long name as *mut c_void) } +pub fn ERR_GET_LIB(l: c_ulong) -> c_int { + ((l >> 24) & 0x0FF) as c_int +} + +pub fn ERR_GET_FUNC(l: c_ulong) -> c_int { + ((l >> 12) & 0xFFF) as c_int +} + +pub fn ERR_GET_REASON(l: c_ulong) -> c_int { + (l & 0xFFF) as c_int +} + extern { pub fn ASN1_INTEGER_set(dest: *mut ASN1_INTEGER, value: c_long) -> c_int; pub fn ASN1_STRING_type_new(ty: c_int) -> *mut ASN1_STRING; diff --git a/openssl/src/error.rs b/openssl/src/error.rs index f54d7bda..4dd219af 100644 --- a/openssl/src/error.rs +++ b/openssl/src/error.rs @@ -76,39 +76,79 @@ impl Error { } /// Returns the raw OpenSSL error code for this error. - pub fn error_code(&self) -> c_ulong { + pub fn code(&self) -> c_ulong { self.0 } - /// Returns the name of the library reporting the error. - pub fn library(&self) -> &'static str { - get_lib(self.0) + /// Returns the name of the library reporting the error, if available. + pub fn library(&self) -> Option<&'static str> { + unsafe { + let cstr = ffi::ERR_lib_error_string(self.0); + if cstr.is_null() { + return None; + } + let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); + Some(str::from_utf8(bytes).unwrap()) + } } /// Returns the name of the function reporting the error. - pub fn function(&self) -> &'static str { - get_func(self.0) + pub fn function(&self) -> Option<&'static str> { + unsafe { + let cstr = ffi::ERR_func_error_string(self.0); + if cstr.is_null() { + return None; + } + let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); + Some(str::from_utf8(bytes).unwrap()) + } } /// Returns the reason for the error. - pub fn reason(&self) -> &'static str { - get_reason(self.0) + pub fn reason(&self) -> Option<&'static str> { + unsafe { + let cstr = ffi::ERR_reason_error_string(self.0); + if cstr.is_null() { + return None; + } + let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); + Some(str::from_utf8(bytes).unwrap()) + } } } impl fmt::Debug for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("Error") - .field("library", &self.library()) - .field("function", &self.function()) - .field("reason", &self.reason()) - .finish() + let mut builder = fmt.debug_struct("Error"); + builder.field("code", &self.code()); + if let Some(library) = self.library() { + builder.field("library", &library); + } + if let Some(function) = self.function() { + builder.field("function", &function); + } + if let Some(reason) = self.reason() { + builder.field("reason", &reason); + } + builder.finish() } } impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.write_str(&self.reason()) + try!(write!(fmt, "error:{:08X}", self.0)); + match self.library() { + Some(l) => try!(write!(fmt, ":{}", l)), + None => try!(write!(fmt, ":lib({})", ffi::ERR_GET_LIB(self.0))), + } + match self.function() { + Some(f) => try!(write!(fmt, ":{}", f)), + None => try!(write!(fmt, ":func({})", ffi::ERR_GET_FUNC(self.0))), + } + match self.reason() { + Some(r) => write!(fmt, ":{}", r), + None => write!(fmt, ":reason({})", ffi::ERR_GET_FUNC(self.0)), + } } } @@ -117,31 +157,3 @@ impl error::Error for Error { "An OpenSSL error" } } - -fn get_lib(err: c_ulong) -> &'static str { - unsafe { - let cstr = ffi::ERR_lib_error_string(err); - assert!(!cstr.is_null(), "bad lib: {}", err); - let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); - str::from_utf8(bytes).unwrap() - } -} - -fn get_func(err: c_ulong) -> &'static str { - unsafe { - let cstr = ffi::ERR_func_error_string(err); - assert!(!cstr.is_null(), "bad func: {}", err); - let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); - str::from_utf8(bytes).unwrap() - } -} - -fn get_reason(err: c_ulong) -> &'static str { - unsafe { - let cstr = ffi::ERR_reason_error_string(err); - assert!(!cstr.is_null(), "bad reason: {}", err); - let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); - str::from_utf8(bytes).unwrap() - } -} - diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index b3500105..ce1ba8ca 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -726,10 +726,7 @@ fn test_alpn_server_advertise_multiple() { /// Test that Servers supporting ALPN don't report a protocol when none of their protocols match /// the client's reported protocol. #[test] -#[cfg(feature = "openssl-102")] -// TODO: not sure why this test is failing on OpenSSL 1.1.0, may be related to -// something about SSLv3 though? -#[cfg_attr(ossl110, ignore)] +#[cfg(all(feature = "openssl-102", ossl102))] fn test_alpn_server_select_none() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let localhost = listener.local_addr().unwrap(); @@ -753,21 +750,46 @@ fn test_alpn_server_select_none() { let mut ctx = SslContext::new(Tls).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/2"]); - match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { - Ok(_) => {} - Err(err) => panic!("Unexpected error {:?}", err), - } + ctx.set_CA_file(&Path::new("test/root-ca.pem")).unwrap(); // Now connect to the socket and make sure the protocol negotiation works... let stream = TcpStream::connect(localhost).unwrap(); - let stream = match SslStream::connect(&ctx, stream) { - Ok(stream) => stream, - Err(err) => panic!("Expected success, got {:?}", err), - }; + let stream = SslStream::connect(&ctx, stream).unwrap(); // Since the protocols from the server and client don't overlap at all, no protocol is selected assert_eq!(None, stream.ssl().selected_alpn_protocol()); } +// In 1.1.0, ALPN negotiation failure is a fatal error +#[test] +#[cfg(all(feature = "openssl-102", ossl110))] +fn test_alpn_server_select_none() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let localhost = listener.local_addr().unwrap(); + // We create a different context instance for the server... + let listener_ctx = { + let mut ctx = SslContext::new(Tls).unwrap(); + ctx.set_verify(SSL_VERIFY_PEER); + ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]); + assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) + .is_ok()); + ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM) + .unwrap(); + ctx + }; + // Have the listener wait on the connection in a different thread. + thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + assert!(SslStream::accept(&listener_ctx, stream).is_err()); + }); + + let mut ctx = SslContext::new(Tls).unwrap(); + ctx.set_verify(SSL_VERIFY_PEER); + ctx.set_alpn_protocols(&[b"http/2"]); + ctx.set_CA_file(&Path::new("test/root-ca.pem")).unwrap(); + // Now connect to the socket and make sure the protocol negotiation works... + let stream = TcpStream::connect(localhost).unwrap(); + assert!(SslStream::connect(&ctx, stream).is_err()); +} #[cfg(test)] mod dtlsv1 { From 984b9a0cc7257befe031c922fffe19ef65f2f2e7 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 14 Oct 2016 22:28:24 -0700 Subject: [PATCH 028/186] Don't run test on ARM They're very segfaulty, but it's almost certainly due to the QEMU layer. We really just want to make sure things compile. --- openssl/test/run.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/openssl/test/run.sh b/openssl/test/run.sh index cc4756bf..cd422db7 100755 --- a/openssl/test/run.sh +++ b/openssl/test/run.sh @@ -17,6 +17,10 @@ if [ -d "$HOME/openssl/lib" ]; then export PATH=$HOME/openssl/bin:$PATH fi +if [ "$TARGET" == "arm-unknown-linux-gnueabihf" ]; then + FLAGS="--no-run" +fi + cargo run --manifest-path systest/Cargo.toml --target $TARGET exec cargo test --manifest-path openssl/Cargo.toml --target $TARGET \ - --features "$FEATURES" + --features "$FEATURES" $FLAGS From ba997c590e38104373e7430cf80dc1f56d6749a6 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 14 Oct 2016 22:55:14 -0700 Subject: [PATCH 029/186] Prefer 1.1 when looking for Homebrew installs --- openssl-sys/build.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openssl-sys/build.rs b/openssl-sys/build.rs index b6540368..5a009204 100644 --- a/openssl-sys/build.rs +++ b/openssl-sys/build.rs @@ -52,11 +52,11 @@ fn find_openssl_dir(target: &str) -> OsString { let host = env::var("HOST").unwrap(); if host.contains("apple-darwin") && target.contains("apple-darwin") { - let homebrew = Path::new("/usr/local/opt/openssl"); + let homebrew = Path::new("/usr/local/opt/openssl@1.1"); if homebrew.exists() { return homebrew.to_path_buf().into() } - let homebrew = Path::new("/usr/local/opt/openssl@1.1"); + let homebrew = Path::new("/usr/local/opt/openssl"); if homebrew.exists() { return homebrew.to_path_buf().into() } From e1d1006fad87c885c256ead37f1de0c3fc8549ef Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 14 Oct 2016 23:03:44 -0700 Subject: [PATCH 030/186] Check feature compatibility in build script --- openssl/build.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/openssl/build.rs b/openssl/build.rs index 15d4b4db..b67438e5 100644 --- a/openssl/build.rs +++ b/openssl/build.rs @@ -1,15 +1,21 @@ use std::env; fn main() { - if env::var("DEP_OPENSSL_IS_101").is_ok() { - println!("cargo:rustc-cfg=ossl101"); - println!("cargo:rustc-cfg=ossl10x"); + if env::var("DEP_OPENSSL_IS_110").is_ok() { + println!("cargo:rustc-cfg=ossl110"); + return; + } else if cfg!(feature = "openssl-110") { + panic!("the openssl-110 feature is enabled but OpenSSL 1.1.0+ is not being linked against"); } if env::var("DEP_OPENSSL_IS_102").is_ok() { println!("cargo:rustc-cfg=ossl102"); println!("cargo:rustc-cfg=ossl10x"); + return; + } else if cfg!(feature = "openssl-102") { + panic!("the openssl-102 feature is enabled but OpenSSL 1.0.2+") } - if env::var("DEP_OPENSSL_IS_110").is_ok() { - println!("cargo:rustc-cfg=ossl110"); + if env::var("DEP_OPENSSL_IS_101").is_ok() { + println!("cargo:rustc-cfg=ossl101"); + println!("cargo:rustc-cfg=ossl10x"); } } From b564cb5db776cddde68e704e4fcf23405f913a02 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 15 Oct 2016 09:41:13 -0700 Subject: [PATCH 031/186] Add digest signature methods --- openssl-sys/src/lib.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 3faa1e57..55f783b1 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -489,6 +489,23 @@ extern { pub fn EVP_DigestFinal(ctx: *mut EVP_MD_CTX, res: *mut u8, n: *mut u32) -> c_int; pub fn EVP_DigestFinal_ex(ctx: *mut EVP_MD_CTX, res: *mut u8, n: *mut u32) -> c_int; + pub fn EVP_DigestSignInit(ctx: *mut EVP_MD_CTX, + pctx: *mut *mut EVP_PKEY_CTX, + type_: *const EVP_MD, + e: *mut ENGINE, + pkey: *mut EVP_PKEY) -> c_int; + pub fn EVP_DigestSignFinal(ctx: *mut EVP_MD_CTX, + sig: *mut c_uchar, + siglen: *mut size_t) -> c_int; + pub fn EVP_DigestVerifyInit(ctx: *mut EVP_MD_CTX, + pctx: *mut *mut EVP_PKEY_CTX, + type_: *const EVP_MD, + e: *mut ENGINE, + pkey: *mut EVP_PKEY) -> c_int; + pub fn EVP_DigestVerifyFinal(ctx: *mut EVP_MD_CTX, + sigret: *const c_uchar, + siglen: size_t) -> c_int; + pub fn EVP_MD_CTX_copy_ex(dst: *mut EVP_MD_CTX, src: *const EVP_MD_CTX) -> c_int; pub fn EVP_PKEY_new() -> *mut EVP_PKEY; From f73313d688fd58f588ddda00742e1519f56da77a Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 15 Oct 2016 10:36:59 -0700 Subject: [PATCH 032/186] Signature and verification support --- openssl/src/crypto/mod.rs | 12 ++- openssl/src/crypto/sign.rs | 200 +++++++++++++++++++++++++++++++++++++ 2 files changed, 207 insertions(+), 5 deletions(-) create mode 100644 openssl/src/crypto/sign.rs diff --git a/openssl/src/crypto/mod.rs b/openssl/src/crypto/mod.rs index 389b7cc9..34e6121d 100644 --- a/openssl/src/crypto/mod.rs +++ b/openssl/src/crypto/mod.rs @@ -14,14 +14,16 @@ // limitations under the License. // +mod util; +pub mod dsa; pub mod hash; pub mod hmac; -pub mod pkcs5; +pub mod memcmp; pub mod pkcs12; +pub mod pkcs5; pub mod pkey; pub mod rand; -pub mod symm; -pub mod memcmp; pub mod rsa; -pub mod dsa; -mod util; +pub mod sign; +pub mod symm; + diff --git a/openssl/src/crypto/sign.rs b/openssl/src/crypto/sign.rs new file mode 100644 index 00000000..f16b9b23 --- /dev/null +++ b/openssl/src/crypto/sign.rs @@ -0,0 +1,200 @@ +use ffi; +use std::io::{self, Write}; +use std::marker::PhantomData; +use std::ptr; + +use HashTypeInternals; +use crypto::hash::Type; +use crypto::pkey::PKey; +use error::ErrorStack; + +#[cfg(ossl110)] +use ffi::{EVP_MD_CTX_new, EVP_MD_CTX_free}; +#[cfg(any(ossl101, ossl102))] +use ffi::{EVP_MD_CTX_create as EVP_MD_CTX_new, EVP_MD_CTX_destroy as EVP_MD_CTX_free}; + +pub struct Signer<'a>(*mut ffi::EVP_MD_CTX, PhantomData<&'a PKey>); + +impl<'a> Drop for Signer<'a> { + fn drop(&mut self) { + unsafe { + EVP_MD_CTX_free(self.0); + } + } +} + +impl<'a> Signer<'a> { + pub fn new(type_: Type, pkey: &'a PKey) -> Result, ErrorStack> { + unsafe { + ffi::init(); + + let ctx = try_ssl_null!(EVP_MD_CTX_new()); + let r = ffi::EVP_DigestSignInit(ctx, + ptr::null_mut(), + type_.evp_md(), + ptr::null_mut(), + pkey.as_ptr()); + if r != 1 { + EVP_MD_CTX_free(ctx); + return Err(ErrorStack::get()); + } + + Ok(Signer(ctx, PhantomData)) + } + } + + pub fn update(&mut self, buf: &[u8]) -> Result<(), ErrorStack> { + unsafe { + try_ssl_if!(ffi::EVP_DigestUpdate(self.0, buf.as_ptr() as *const _, buf.len()) != 1); + Ok(()) + } + } + + pub fn finish(&self) -> Result, ErrorStack> { + unsafe { + let mut len = 0; + try_ssl_if!(ffi::EVP_DigestSignFinal(self.0, ptr::null_mut(), &mut len) != 1); + let mut buf = vec![0; len]; + try_ssl_if!(ffi::EVP_DigestSignFinal(self.0, buf.as_mut_ptr() as *mut _, &mut len) + != 1); + Ok(buf) + } + } +} + +impl<'a> Write for Signer<'a> { + fn write(&mut self, buf: &[u8]) -> io::Result { + try!(self.update(buf)); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +pub struct Verifier<'a>(*mut ffi::EVP_MD_CTX, PhantomData<&'a PKey>); + +impl<'a> Drop for Verifier<'a> { + fn drop(&mut self) { + unsafe { + EVP_MD_CTX_free(self.0); + } + } +} + +impl<'a> Verifier<'a> { + pub fn new(type_: Type, pkey: &'a PKey) -> Result, ErrorStack> { + unsafe { + ffi::init(); + + let ctx = try_ssl_null!(EVP_MD_CTX_new()); + let r = ffi::EVP_DigestVerifyInit(ctx, + ptr::null_mut(), + type_.evp_md(), + ptr::null_mut(), + pkey.as_ptr()); + if r != 1 { + EVP_MD_CTX_free(ctx); + return Err(ErrorStack::get()); + } + + Ok(Verifier(ctx, PhantomData)) + } + } + + pub fn update(&mut self, buf: &[u8]) -> Result<(), ErrorStack> { + unsafe { + try_ssl_if!(ffi::EVP_DigestUpdate(self.0, buf.as_ptr() as *const _, buf.len()) != 1); + Ok(()) + } + } + + pub fn finish(&self, signature: &[u8]) -> Result<(), ErrorStack> { + unsafe { + try_ssl_if!(ffi::EVP_DigestVerifyFinal(self.0, + signature.as_ptr() as *const _, + signature.len()) != 1); + Ok(()) + } + } +} + +impl<'a> Write for Verifier<'a> { + fn write(&mut self, buf: &[u8]) -> io::Result { + try!(self.update(buf)); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[cfg(test)] +mod test { + use crypto::hash::Type; + use crypto::sign::{Signer, Verifier}; + use crypto::rsa::RSA; + use crypto::pkey::PKey; + + static INPUT: &'static [u8] = + &[101, 121, 74, 104, 98, 71, 99, 105, 79, 105, 74, 83, 85, 122, 73, 49, 78, 105, 74, 57, + 46, 101, 121, 74, 112, 99, 51, 77, 105, 79, 105, 74, 113, 98, 50, 85, 105, 76, 65, 48, + 75, 73, 67, 74, 108, 101, 72, 65, 105, 79, 106, 69, 122, 77, 68, 65, 52, 77, 84, 107, + 122, 79, 68, 65, 115, 68, 81, 111, 103, 73, 109, 104, 48, 100, 72, 65, 54, 76, 121, + 57, 108, 101, 71, 70, 116, 99, 71, 120, 108, 76, 109, 78, 118, 98, 83, 57, 112, 99, + 49, 57, 121, 98, 50, 57, 48, 73, 106, 112, 48, 99, 110, 86, 108, 102, 81]; + + static SIGNATURE: &'static [u8] = + &[112, 46, 33, 137, 67, 232, 143, 209, 30, 181, 216, 45, 191, 120, 69, 243, 65, 6, 174, + 27, 129, 255, 247, 115, 17, 22, 173, 209, 113, 125, 131, 101, 109, 66, 10, 253, 60, + 150, 238, 221, 115, 162, 102, 62, 81, 102, 104, 123, 0, 11, 135, 34, 110, 1, 135, 237, + 16, 115, 249, 69, 229, 130, 173, 252, 239, 22, 216, 90, 121, 142, 232, 198, 109, 219, + 61, 184, 151, 91, 23, 208, 148, 2, 190, 237, 213, 217, 217, 112, 7, 16, 141, 178, 129, + 96, 213, 248, 4, 12, 167, 68, 87, 98, 184, 31, 190, 127, 249, 217, 46, 10, 231, 111, + 36, 242, 91, 51, 187, 230, 244, 74, 230, 30, 177, 4, 10, 203, 32, 4, 77, 62, 249, 18, + 142, 212, 1, 48, 121, 91, 212, 189, 59, 65, 238, 202, 208, 102, 171, 101, 25, 129, + 253, 228, 141, 247, 127, 55, 45, 195, 139, 159, 175, 221, 59, 239, 177, 139, 93, 163, + 204, 60, 46, 176, 47, 158, 58, 65, 214, 18, 202, 173, 21, 145, 18, 115, 160, 95, 35, + 185, 232, 56, 250, 175, 132, 157, 105, 132, 41, 239, 90, 30, 136, 121, 130, 54, 195, + 212, 14, 96, 69, 34, 165, 68, 200, 242, 122, 122, 45, 184, 6, 99, 209, 108, 247, 202, + 234, 86, 222, 64, 92, 178, 33, 90, 69, 178, 194, 85, 102, 181, 90, 193, 167, 72, 160, + 112, 223, 200, 163, 42, 70, 149, 67, 208, 25, 238, 251, 71]; + + #[test] + fn test_sign() { + let key = include_bytes!("../../test/rsa.pem"); + let private_key = RSA::private_key_from_pem(key).unwrap(); + let pkey = PKey::from_rsa(private_key).unwrap(); + + let mut signer = Signer::new(Type::SHA256, &pkey).unwrap(); + signer.update(INPUT).unwrap(); + let result = signer.finish().unwrap(); + + assert_eq!(result, SIGNATURE); + } + + #[test] + fn test_verify_ok() { + let key = include_bytes!("../../test/rsa.pem"); + let private_key = RSA::private_key_from_pem(key).unwrap(); + let pkey = PKey::from_rsa(private_key).unwrap(); + + let mut verifier = Verifier::new(Type::SHA256, &pkey).unwrap(); + verifier.update(INPUT).unwrap(); + verifier.finish(SIGNATURE).unwrap(); + } + + #[test] + fn test_verify_err() { + let key = include_bytes!("../../test/rsa.pem"); + let private_key = RSA::private_key_from_pem(key).unwrap(); + let pkey = PKey::from_rsa(private_key).unwrap(); + + let mut verifier = Verifier::new(Type::SHA256, &pkey).unwrap(); + verifier.update(INPUT).unwrap(); + verifier.update(b"foobar"); + assert!(verifier.finish(SIGNATURE).is_err()); + } +} From cce1d44f282f4b40f45dc1bec16813db7b9b30d7 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 15 Oct 2016 10:43:19 -0700 Subject: [PATCH 033/186] Remove old RSA sign and verify methods --- openssl/src/crypto/rsa.rs | 86 -------------------------------------- openssl/src/crypto/sign.rs | 2 +- 2 files changed, 1 insertion(+), 87 deletions(-) diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index f91f39fb..eebb9622 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -7,8 +7,6 @@ use libc::{c_int, c_void, c_char}; use bn::{BigNum, BigNumRef}; use bio::{MemBio, MemBioSlice}; use error::ErrorStack; -use HashTypeInternals; -use crypto::hash; use crypto::util::{CallbackState, invoke_passwd_cb}; /// Type of encryption padding to use. @@ -248,36 +246,6 @@ impl RSA { } } - pub fn sign(&self, hash: hash::Type, message: &[u8]) -> Result, ErrorStack> { - assert!(self.d().is_some(), "private components missing"); - let k_len = self.size().expect("RSA missing an n"); - let mut sig = vec![0; k_len as usize]; - let mut sig_len = k_len; - - unsafe { - try_ssl!(ffi::RSA_sign(hash.as_nid() as c_int, - message.as_ptr(), - message.len() as u32, - sig.as_mut_ptr(), - &mut sig_len, - self.0)); - assert!(sig_len == k_len); - Ok(sig) - } - } - - pub fn verify(&self, hash: hash::Type, message: &[u8], sig: &[u8]) -> Result<(), ErrorStack> { - unsafe { - try_ssl!(ffi::RSA_verify(hash.as_nid() as c_int, - message.as_ptr(), - message.len() as u32, - sig.as_ptr(), - sig.len() as u32, - self.0)); - } - Ok(()) - } - pub fn as_ptr(&self) -> *mut ffi::RSA { self.0 } @@ -429,63 +397,9 @@ mod compat { #[cfg(test)] mod test { - use std::io::Write; use libc::c_char; use super::*; - use crypto::hash::*; - - fn signing_input_rs256() -> Vec { - vec![101, 121, 74, 104, 98, 71, 99, 105, 79, 105, 74, 83, 85, 122, 73, 49, 78, 105, 74, 57, - 46, 101, 121, 74, 112, 99, 51, 77, 105, 79, 105, 74, 113, 98, 50, 85, 105, 76, 65, 48, - 75, 73, 67, 74, 108, 101, 72, 65, 105, 79, 106, 69, 122, 77, 68, 65, 52, 77, 84, 107, - 122, 79, 68, 65, 115, 68, 81, 111, 103, 73, 109, 104, 48, 100, 72, 65, 54, 76, 121, - 57, 108, 101, 71, 70, 116, 99, 71, 120, 108, 76, 109, 78, 118, 98, 83, 57, 112, 99, - 49, 57, 121, 98, 50, 57, 48, 73, 106, 112, 48, 99, 110, 86, 108, 102, 81] - } - - fn signature_rs256() -> Vec { - vec![112, 46, 33, 137, 67, 232, 143, 209, 30, 181, 216, 45, 191, 120, 69, 243, 65, 6, 174, - 27, 129, 255, 247, 115, 17, 22, 173, 209, 113, 125, 131, 101, 109, 66, 10, 253, 60, - 150, 238, 221, 115, 162, 102, 62, 81, 102, 104, 123, 0, 11, 135, 34, 110, 1, 135, 237, - 16, 115, 249, 69, 229, 130, 173, 252, 239, 22, 216, 90, 121, 142, 232, 198, 109, 219, - 61, 184, 151, 91, 23, 208, 148, 2, 190, 237, 213, 217, 217, 112, 7, 16, 141, 178, 129, - 96, 213, 248, 4, 12, 167, 68, 87, 98, 184, 31, 190, 127, 249, 217, 46, 10, 231, 111, - 36, 242, 91, 51, 187, 230, 244, 74, 230, 30, 177, 4, 10, 203, 32, 4, 77, 62, 249, 18, - 142, 212, 1, 48, 121, 91, 212, 189, 59, 65, 238, 202, 208, 102, 171, 101, 25, 129, - 253, 228, 141, 247, 127, 55, 45, 195, 139, 159, 175, 221, 59, 239, 177, 139, 93, 163, - 204, 60, 46, 176, 47, 158, 58, 65, 214, 18, 202, 173, 21, 145, 18, 115, 160, 95, 35, - 185, 232, 56, 250, 175, 132, 157, 105, 132, 41, 239, 90, 30, 136, 121, 130, 54, 195, - 212, 14, 96, 69, 34, 165, 68, 200, 242, 122, 122, 45, 184, 6, 99, 209, 108, 247, 202, - 234, 86, 222, 64, 92, 178, 33, 90, 69, 178, 194, 85, 102, 181, 90, 193, 167, 72, 160, - 112, 223, 200, 163, 42, 70, 149, 67, 208, 25, 238, 251, 71] - } - - #[test] - pub fn test_sign() { - let key = include_bytes!("../../test/rsa.pem"); - let private_key = RSA::private_key_from_pem(key).unwrap(); - - let mut sha = Hasher::new(Type::SHA256).unwrap(); - sha.write_all(&signing_input_rs256()).unwrap(); - let digest = sha.finish().unwrap(); - - let result = private_key.sign(Type::SHA256, &digest).unwrap(); - - assert_eq!(result, signature_rs256()); - } - - #[test] - pub fn test_verify() { - let key = include_bytes!("../../test/rsa.pem.pub"); - let public_key = RSA::public_key_from_pem(key).unwrap(); - - let mut sha = Hasher::new(Type::SHA256).unwrap(); - sha.write_all(&signing_input_rs256()).unwrap(); - let digest = sha.finish().unwrap(); - - assert!(public_key.verify(Type::SHA256, &digest, &signature_rs256()).is_ok()); - } #[test] pub fn test_password() { diff --git a/openssl/src/crypto/sign.rs b/openssl/src/crypto/sign.rs index f16b9b23..01dcbafc 100644 --- a/openssl/src/crypto/sign.rs +++ b/openssl/src/crypto/sign.rs @@ -194,7 +194,7 @@ mod test { let mut verifier = Verifier::new(Type::SHA256, &pkey).unwrap(); verifier.update(INPUT).unwrap(); - verifier.update(b"foobar"); + verifier.update(b"foobar").unwrap(); assert!(verifier.finish(SIGNATURE).is_err()); } } From 6ae472487f3515bbbb058a8342983570611a0273 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 15 Oct 2016 11:06:11 -0700 Subject: [PATCH 034/186] Support HMAC PKeys and remove hmac module --- openssl-sys/src/lib.rs | 6 + openssl/src/crypto/hmac.rs | 565 ------------------------------------- openssl/src/crypto/mod.rs | 1 - openssl/src/crypto/pkey.rs | 14 +- openssl/src/crypto/sign.rs | 74 +++++ 5 files changed, 93 insertions(+), 567 deletions(-) delete mode 100644 openssl/src/crypto/hmac.rs diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 55f783b1..8ad26003 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -109,6 +109,7 @@ pub const CRYPTO_LOCK: c_int = 1; pub const EVP_MAX_MD_SIZE: c_uint = 64; pub const EVP_PKEY_RSA: c_int = NID_rsaEncryption; +pub const EVP_PKEY_HMAC: c_int = NID_hmac; pub const MBSTRING_ASC: c_int = MBSTRING_FLAG | 1; pub const MBSTRING_BMP: c_int = MBSTRING_FLAG | 2; @@ -119,6 +120,7 @@ pub const MBSTRING_UTF8: c_int = MBSTRING_FLAG; pub const NID_rsaEncryption: c_int = 6; pub const NID_ext_key_usage: c_int = 126; pub const NID_key_usage: c_int = 83; +pub const NID_hmac: c_int = 855; pub const PKCS5_SALT_LEN: c_int = 8; @@ -515,6 +517,10 @@ extern { pub fn EVP_PKEY_get1_RSA(k: *mut EVP_PKEY) -> *mut RSA; pub fn EVP_PKEY_set1_RSA(k: *mut EVP_PKEY, r: *mut RSA) -> c_int; pub fn EVP_PKEY_cmp(a: *const EVP_PKEY, b: *const EVP_PKEY) -> c_int; + pub fn EVP_PKEY_new_mac_key(type_: c_int, + e: *mut ENGINE, + key: *const c_uchar, + keylen: c_int) -> *mut EVP_PKEY; pub fn HMAC_CTX_copy(dst: *mut HMAC_CTX, src: *mut HMAC_CTX) -> c_int; diff --git a/openssl/src/crypto/hmac.rs b/openssl/src/crypto/hmac.rs deleted file mode 100644 index 8f44ed7f..00000000 --- a/openssl/src/crypto/hmac.rs +++ /dev/null @@ -1,565 +0,0 @@ -// Copyright 2013 Jack Lloyd -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -use libc::{c_int}; -use std::io; -use std::io::prelude::*; -use ffi; - -use HashTypeInternals; -use crypto::hash::Type; -use error::ErrorStack; - -#[derive(PartialEq, Copy, Clone)] -enum State { - Reset, - Updated, - Finalized, -} - -use self::State::*; - -/// Provides HMAC computation. -/// -/// Requires the `hmac` feature. -/// -/// # Examples -/// -/// Calculate a HMAC in one go. -/// -/// ``` -/// use openssl::crypto::hash::Type; -/// use openssl::crypto::hmac::hmac; -/// let key = b"Jefe"; -/// let data = b"what do ya want for nothing?"; -/// let spec = b"\x75\x0c\x78\x3e\x6a\xb0\xb5\x03\xea\xa8\x6e\x31\x0a\x5d\xb7\x38"; -/// let res = hmac(Type::MD5, key, data).unwrap(); -/// assert_eq!(res, spec); -/// ``` -/// -/// Use the `Write` trait to supply the input in chunks. -/// -/// ``` -/// use openssl::crypto::hash::Type; -/// use openssl::crypto::hmac::HMAC; -/// let key = b"Jefe"; -/// let data: &[&[u8]] = &[b"what do ya ", b"want for nothing?"]; -/// let spec = b"\x75\x0c\x78\x3e\x6a\xb0\xb5\x03\xea\xa8\x6e\x31\x0a\x5d\xb7\x38"; -/// let mut h = HMAC::new(Type::MD5, &*key).unwrap(); -/// h.update(data[0]).unwrap(); -/// h.update(data[1]).unwrap(); -/// let res = h.finish().unwrap(); -/// assert_eq!(res, spec); -/// ``` -pub struct HMAC { - ctx: compat::HMAC_CTX, - state: State, -} - -impl HMAC { - /// Creates a new `HMAC` with the specified hash type using the `key`. - pub fn new(ty: Type, key: &[u8]) -> Result { - ffi::init(); - - let ctx = compat::HMAC_CTX::new(); - let md = ty.evp_md(); - - let mut h = HMAC { - ctx: ctx, - state: Finalized, - }; - try!(h.init_once(md, key)); - Ok(h) - } - - fn init_once(&mut self, md: *const ffi::EVP_MD, key: &[u8]) -> Result<(), ErrorStack> { - unsafe { - try_ssl!(ffi::HMAC_Init_ex(self.ctx.get(), - key.as_ptr() as *const _, - key.len() as c_int, - md, - 0 as *mut _)); - } - self.state = Reset; - Ok(()) - } - - fn init(&mut self) -> Result<(), ErrorStack> { - match self.state { - Reset => return Ok(()), - Updated => { - try!(self.finish()); - } - Finalized => (), - } - // If the key and/or md is not supplied it's reused from the last time - // avoiding redundant initializations - unsafe { - try_ssl!(ffi::HMAC_Init_ex(self.ctx.get(), - 0 as *const _, - 0, - 0 as *const _, - 0 as *mut _)); - } - self.state = Reset; - Ok(()) - } - - pub fn update(&mut self, data: &[u8]) -> Result<(), ErrorStack> { - if self.state == Finalized { - try!(self.init()); - } - unsafe { - try_ssl!(ffi::HMAC_Update(self.ctx.get(), - data.as_ptr(), - data.len())); - } - self.state = Updated; - Ok(()) - } - - /// Returns the hash of the data written since creation or - /// the last `finish` and resets the hasher. - pub fn finish(&mut self) -> Result, ErrorStack> { - if self.state == Finalized { - try!(self.init()); - } - unsafe { - let mut len = ffi::EVP_MAX_MD_SIZE; - let mut res = vec![0; len as usize]; - try_ssl!(ffi::HMAC_Final(self.ctx.get(), - res.as_mut_ptr(), - &mut len)); - res.truncate(len as usize); - self.state = Finalized; - Ok(res) - } - } -} - -impl Write for HMAC { - #[inline] - fn write(&mut self, buf: &[u8]) -> io::Result { - try!(self.update(buf)); - Ok(buf.len()) - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -impl Clone for HMAC { - fn clone(&self) -> HMAC { - let ctx = compat::HMAC_CTX::new(); - unsafe { - let r = ffi::HMAC_CTX_copy(ctx.get(), self.ctx.get()); - assert_eq!(r, 1); - } - HMAC { - ctx: ctx, - state: self.state, - } - } -} - -impl Drop for HMAC { - fn drop(&mut self) { - if self.state != Finalized { - drop(self.finish()); - } - } -} - -/// Computes the HMAC of the `data` with the hash `t` and `key`. -pub fn hmac(t: Type, key: &[u8], data: &[u8]) -> Result, ErrorStack> { - let mut h = try!(HMAC::new(t, key)); - try!(h.update(data)); - h.finish() -} - -#[cfg(ossl110)] -#[allow(bad_style)] -mod compat { - use ffi; - - pub struct HMAC_CTX { - ctx: *mut ffi::HMAC_CTX, - } - - impl HMAC_CTX { - pub fn new() -> HMAC_CTX { - unsafe { - let ctx = ffi::HMAC_CTX_new(); - assert!(!ctx.is_null()); - HMAC_CTX { ctx: ctx } - } - } - - pub fn get(&self) -> *mut ffi::HMAC_CTX { - self.ctx - } - } - - impl Drop for HMAC_CTX { - fn drop(&mut self) { - unsafe { - ffi::HMAC_CTX_free(self.ctx); - } - } - } -} - -#[cfg(ossl10x)] -#[allow(bad_style)] -mod compat { - use std::mem; - use std::cell::UnsafeCell; - - use ffi; - - pub struct HMAC_CTX { - ctx: UnsafeCell, - } - - impl HMAC_CTX { - pub fn new() -> HMAC_CTX { - unsafe { - let mut ctx = mem::zeroed(); - ffi::HMAC_CTX_init(&mut ctx); - HMAC_CTX { ctx: UnsafeCell::new(ctx) } - } - } - - pub fn get(&self) -> *mut ffi::HMAC_CTX { - self.ctx.get() - } - } - - impl Drop for HMAC_CTX { - fn drop(&mut self) { - unsafe { - ffi::HMAC_CTX_cleanup(self.get()); - } - } - } -} - -#[cfg(test)] -mod tests { - use std::iter::repeat; - use serialize::hex::FromHex; - use crypto::hash::Type; - use crypto::hash::Type::*; - use super::{hmac, HMAC}; - use std::io::prelude::*; - - fn test_hmac(ty: Type, tests: &[(Vec, Vec, Vec)]) { - for &(ref key, ref data, ref res) in tests.iter() { - assert_eq!(hmac(ty, &**key, &**data).unwrap(), *res); - } - } - - fn test_hmac_recycle(h: &mut HMAC, test: &(Vec, Vec, Vec)) { - let &(_, ref data, ref res) = test; - h.write_all(&**data).unwrap(); - assert_eq!(h.finish().unwrap(), *res); - } - - #[test] - fn test_hmac_md5() { - // test vectors from RFC 2202 - let tests: [(Vec, Vec, Vec); 7] = - [(repeat(0x0b_u8).take(16).collect(), - b"Hi There".to_vec(), - "9294727a3638bb1c13f48ef8158bfc9d".from_hex().unwrap()), - (b"Jefe".to_vec(), - b"what do ya want for nothing?".to_vec(), - "750c783e6ab0b503eaa86e310a5db738".from_hex().unwrap()), - (repeat(0xaa_u8).take(16).collect(), - repeat(0xdd_u8).take(50).collect(), - "56be34521d144c88dbb8c733f0e8b3f6".from_hex().unwrap()), - ("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(), - repeat(0xcd_u8).take(50).collect(), - "697eaf0aca3a3aea3a75164746ffaa79".from_hex().unwrap()), - (repeat(0x0c_u8).take(16).collect(), - b"Test With Truncation".to_vec(), - "56461ef2342edc00f9bab995690efd4c".from_hex().unwrap()), - (repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(), - "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()), - (repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key \ - and Larger Than One Block-Size Data" - .to_vec(), - "6f630fad67cda0ee1fb1f562db3aa53e".from_hex().unwrap())]; - - test_hmac(MD5, &tests); - } - - #[test] - fn test_hmac_md5_recycle() { - let tests: [(Vec, Vec, Vec); 2] = - [(repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(), - "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()), - (repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key \ - and Larger Than One Block-Size Data" - .to_vec(), - "6f630fad67cda0ee1fb1f562db3aa53e".from_hex().unwrap())]; - - let mut h = HMAC::new(MD5, &*tests[0].0).unwrap(); - for i in 0..100usize { - let test = &tests[i % 2]; - test_hmac_recycle(&mut h, test); - } - } - - #[test] - fn test_finish_twice() { - let test: (Vec, Vec, Vec) = - (repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(), - "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()); - - let mut h = HMAC::new(Type::MD5, &*test.0).unwrap(); - h.write_all(&*test.1).unwrap(); - h.finish().unwrap(); - let res = h.finish().unwrap(); - let null = hmac(Type::MD5, &*test.0, &[]).unwrap(); - assert_eq!(res, null); - } - - #[test] - fn test_clone() { - let tests: [(Vec, Vec, Vec); 2] = - [(repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(), - "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()), - (repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key \ - and Larger Than One Block-Size Data" - .to_vec(), - "6f630fad67cda0ee1fb1f562db3aa53e".from_hex().unwrap())]; - let p = tests[0].0.len() / 2; - let h0 = HMAC::new(Type::MD5, &*tests[0].0).unwrap(); - - println!("Clone a new hmac"); - let mut h1 = h0.clone(); - h1.write_all(&tests[0].1[..p]).unwrap(); - { - println!("Clone an updated hmac"); - let mut h2 = h1.clone(); - h2.write_all(&tests[0].1[p..]).unwrap(); - let res = h2.finish().unwrap(); - assert_eq!(res, tests[0].2); - } - h1.write_all(&tests[0].1[p..]).unwrap(); - let res = h1.finish().unwrap(); - assert_eq!(res, tests[0].2); - - println!("Clone a finished hmac"); - let mut h3 = h1.clone(); - h3.write_all(&*tests[1].1).unwrap(); - let res = h3.finish().unwrap(); - assert_eq!(res, tests[1].2); - } - - #[test] - fn test_hmac_sha1() { - // test vectors from RFC 2202 - let tests: [(Vec, Vec, Vec); 7] = - [(repeat(0x0b_u8).take(20).collect(), - b"Hi There".to_vec(), - "b617318655057264e28bc0b6fb378c8ef146be00".from_hex().unwrap()), - (b"Jefe".to_vec(), - b"what do ya want for nothing?".to_vec(), - "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79".from_hex().unwrap()), - (repeat(0xaa_u8).take(20).collect(), - repeat(0xdd_u8).take(50).collect(), - "125d7342b9ac11cd91a39af48aa17b4f63f175d3".from_hex().unwrap()), - ("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(), - repeat(0xcd_u8).take(50).collect(), - "4c9007f4026250c6bc8414f9bf50c86c2d7235da".from_hex().unwrap()), - (repeat(0x0c_u8).take(20).collect(), - b"Test With Truncation".to_vec(), - "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04".from_hex().unwrap()), - (repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(), - "aa4ae5e15272d00e95705637ce8a3b55ed402112".from_hex().unwrap()), - (repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key \ - and Larger Than One Block-Size Data" - .to_vec(), - "e8e99d0f45237d786d6bbaa7965c7808bbff1a91".from_hex().unwrap())]; - - test_hmac(SHA1, &tests); - } - - #[test] - fn test_hmac_sha1_recycle() { - let tests: [(Vec, Vec, Vec); 2] = - [(repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(), - "aa4ae5e15272d00e95705637ce8a3b55ed402112".from_hex().unwrap()), - (repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key \ - and Larger Than One Block-Size Data" - .to_vec(), - "e8e99d0f45237d786d6bbaa7965c7808bbff1a91".from_hex().unwrap())]; - - let mut h = HMAC::new(SHA1, &*tests[0].0).unwrap(); - for i in 0..100usize { - let test = &tests[i % 2]; - test_hmac_recycle(&mut h, test); - } - } - - - - fn test_sha2(ty: Type, results: &[Vec]) { - // test vectors from RFC 4231 - let tests: [(Vec, Vec); 6] = - [(repeat(0xb_u8).take(20).collect(), b"Hi There".to_vec()), - (b"Jefe".to_vec(), b"what do ya want for nothing?".to_vec()), - (repeat(0xaa_u8).take(20).collect(), repeat(0xdd_u8).take(50).collect()), - ("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(), - repeat(0xcd_u8).take(50).collect()), - (repeat(0xaa_u8).take(131).collect(), - b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec()), - (repeat(0xaa_u8).take(131).collect(), - b"This is a test using a larger than block-size key and a \ - larger than block-size data. The key needs to be hashed \ - before being used by the HMAC algorithm." - .to_vec())]; - - for (&(ref key, ref data), res) in tests.iter().zip(results.iter()) { - assert_eq!(hmac(ty, &**key, &**data).unwrap(), *res); - } - - // recycle test - let mut h = HMAC::new(ty, &*tests[5].0).unwrap(); - for i in 0..100usize { - let test = &tests[4 + i % 2]; - let tup = (test.0.clone(), test.1.clone(), results[4 + i % 2].clone()); - test_hmac_recycle(&mut h, &tup); - } - } - - #[test] - fn test_hmac_sha224() { - let results = ["896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22" - .from_hex() - .unwrap(), - "a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44" - .from_hex() - .unwrap(), - "7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea" - .from_hex() - .unwrap(), - "6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a" - .from_hex() - .unwrap(), - "95e9a0db962095adaebe9b2d6f0dbce2d499f112f2d2b7273fa6870e" - .from_hex() - .unwrap(), - "3a854166ac5d9f023f54d517d0b39dbd946770db9c2b95c9f6f565d1" - .from_hex() - .unwrap()]; - test_sha2(SHA224, &results); - } - - #[test] - fn test_hmac_sha256() { - let results = ["b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7" - .from_hex() - .unwrap(), - "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" - .from_hex() - .unwrap(), - "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe" - .from_hex() - .unwrap(), - "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b" - .from_hex() - .unwrap(), - "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54" - .from_hex() - .unwrap(), - "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2" - .from_hex() - .unwrap()]; - test_sha2(SHA256, &results); - } - - #[test] - fn test_hmac_sha384() { - let results = ["afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c7cebc59cfaea9ea90\ - 76ede7f4af152e8b2fa9cb6" - .from_hex() - .unwrap(), - "af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec3736322445e8e2240ca5\ - e69e2c78b3239ecfab21649" - .from_hex() - .unwrap(), - "88062608d3e6ad8a0aa2ace014c8a86f0aa635d947ac9febe83ef4e55966144b2a5ab39dc\ - 13814b94e3ab6e101a34f27" - .from_hex() - .unwrap(), - "3e8a69b7783c25851933ab6290af6ca77a9981480850009cc5577c6e1f573b4e6801dd23c\ - 4a7d679ccf8a386c674cffb" - .from_hex() - .unwrap(), - "4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05033ac4c60c2ef6ab4\ - 030fe8296248df163f44952" - .from_hex() - .unwrap(), - "6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82461e99c5a678cc31e\ - 799176d3860e6110c46523e" - .from_hex() - .unwrap()]; - test_sha2(SHA384, &results); - } - - #[test] - fn test_hmac_sha512() { - let results = ["87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d\ - 6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854" - .from_hex() - .unwrap(), - "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea2505549758bf75c\ - 05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737" - .from_hex() - .unwrap(), - "fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33b2279d39bf3e84827\ - 9a722c806b485a47e67c807b946a337bee8942674278859e13292fb" - .from_hex() - .unwrap(), - "b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050361ee3dba91ca5c11\ - aa25eb4d679275cc5788063a5f19741120c4f2de2adebeb10a298dd" - .from_hex() - .unwrap(), - "80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b013783f8f3526b56d037e\ - 05f2598bd0fd2215d6a1e5295e64f73f63f0aec8b915a985d786598" - .from_hex() - .unwrap(), - "e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944b6022cac3\ - c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58" - .from_hex() - .unwrap()]; - test_sha2(SHA512, &results); - } -} diff --git a/openssl/src/crypto/mod.rs b/openssl/src/crypto/mod.rs index 34e6121d..0db23bcc 100644 --- a/openssl/src/crypto/mod.rs +++ b/openssl/src/crypto/mod.rs @@ -17,7 +17,6 @@ mod util; pub mod dsa; pub mod hash; -pub mod hmac; pub mod memcmp; pub mod pkcs12; pub mod pkcs5; diff --git a/openssl/src/crypto/pkey.rs b/openssl/src/crypto/pkey.rs index a2a6f9c1..e300843e 100644 --- a/openssl/src/crypto/pkey.rs +++ b/openssl/src/crypto/pkey.rs @@ -1,4 +1,4 @@ -use libc::{c_void, c_char}; +use libc::{c_void, c_char, c_int}; use std::ptr; use std::mem; use ffi; @@ -26,6 +26,18 @@ impl PKey { } } + /// Create a new `PKey` containing an HAMC key. + pub fn hmac(key: &[u8]) -> Result { + unsafe { + assert!(key.len() <= c_int::max_value() as usize); + let key = try_ssl_null!(ffi::EVP_PKEY_new_mac_key(ffi::EVP_PKEY_HMAC, + ptr::null_mut(), + key.as_ptr() as *const _, + key.len() as c_int)); + Ok(PKey(key)) + } + } + pub unsafe fn from_ptr(handle: *mut ffi::EVP_PKEY) -> PKey { PKey(handle) } diff --git a/openssl/src/crypto/sign.rs b/openssl/src/crypto/sign.rs index 01dcbafc..47549574 100644 --- a/openssl/src/crypto/sign.rs +++ b/openssl/src/crypto/sign.rs @@ -133,6 +133,9 @@ impl<'a> Write for Verifier<'a> { #[cfg(test)] mod test { + use serialize::hex::FromHex; + use std::iter; + use crypto::hash::Type; use crypto::sign::{Signer, Verifier}; use crypto::rsa::RSA; @@ -197,4 +200,75 @@ mod test { verifier.update(b"foobar").unwrap(); assert!(verifier.finish(SIGNATURE).is_err()); } + + fn test_hmac(ty: Type, tests: &[(Vec, Vec, Vec)]) { + for &(ref key, ref data, ref res) in tests.iter() { + let pkey = PKey::hmac(key).unwrap(); + let mut signer = Signer::new(ty, &pkey).unwrap(); + signer.update(data).unwrap(); + assert_eq!(signer.finish().unwrap(), *res); + } + } + + #[test] + fn hmac_md5() { + // test vectors from RFC 2202 + let tests: [(Vec, Vec, Vec); 7] = + [(iter::repeat(0x0b_u8).take(16).collect(), + b"Hi There".to_vec(), + "9294727a3638bb1c13f48ef8158bfc9d".from_hex().unwrap()), + (b"Jefe".to_vec(), + b"what do ya want for nothing?".to_vec(), + "750c783e6ab0b503eaa86e310a5db738".from_hex().unwrap()), + (iter::repeat(0xaa_u8).take(16).collect(), + iter::repeat(0xdd_u8).take(50).collect(), + "56be34521d144c88dbb8c733f0e8b3f6".from_hex().unwrap()), + ("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(), + iter::repeat(0xcd_u8).take(50).collect(), + "697eaf0aca3a3aea3a75164746ffaa79".from_hex().unwrap()), + (iter::repeat(0x0c_u8).take(16).collect(), + b"Test With Truncation".to_vec(), + "56461ef2342edc00f9bab995690efd4c".from_hex().unwrap()), + (iter::repeat(0xaa_u8).take(80).collect(), + b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(), + "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()), + (iter::repeat(0xaa_u8).take(80).collect(), + b"Test Using Larger Than Block-Size Key \ + and Larger Than One Block-Size Data" + .to_vec(), + "6f630fad67cda0ee1fb1f562db3aa53e".from_hex().unwrap())]; + + test_hmac(Type::MD5, &tests); + } + + #[test] + fn hmac_sha1() { + // test vectors from RFC 2202 + let tests: [(Vec, Vec, Vec); 7] = + [(iter::repeat(0x0b_u8).take(20).collect(), + b"Hi There".to_vec(), + "b617318655057264e28bc0b6fb378c8ef146be00".from_hex().unwrap()), + (b"Jefe".to_vec(), + b"what do ya want for nothing?".to_vec(), + "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79".from_hex().unwrap()), + (iter::repeat(0xaa_u8).take(20).collect(), + iter::repeat(0xdd_u8).take(50).collect(), + "125d7342b9ac11cd91a39af48aa17b4f63f175d3".from_hex().unwrap()), + ("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(), + iter::repeat(0xcd_u8).take(50).collect(), + "4c9007f4026250c6bc8414f9bf50c86c2d7235da".from_hex().unwrap()), + (iter::repeat(0x0c_u8).take(20).collect(), + b"Test With Truncation".to_vec(), + "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04".from_hex().unwrap()), + (iter::repeat(0xaa_u8).take(80).collect(), + b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(), + "aa4ae5e15272d00e95705637ce8a3b55ed402112".from_hex().unwrap()), + (iter::repeat(0xaa_u8).take(80).collect(), + b"Test Using Larger Than Block-Size Key \ + and Larger Than One Block-Size Data" + .to_vec(), + "e8e99d0f45237d786d6bbaa7965c7808bbff1a91".from_hex().unwrap())]; + + test_hmac(Type::SHA1, &tests); + } } From bb23b33829ef872ae00ceea8c701d6f64f64e39b Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 15 Oct 2016 12:24:20 -0700 Subject: [PATCH 035/186] Fix signature of EVP_DigestVerifyFinal on 1.0.1 --- openssl-sys/src/lib.rs | 5 +++++ openssl-sys/src/ossl10x.rs | 4 +++- openssl/src/crypto/sign.rs | 2 +- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 8ad26003..6fe44750 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -504,6 +504,11 @@ extern { type_: *const EVP_MD, e: *mut ENGINE, pkey: *mut EVP_PKEY) -> c_int; + #[cfg(ossl101)] + pub fn EVP_DigestVerifyFinal(ctx: *mut EVP_MD_CTX, + sigret: *mut c_uchar, + siglen: size_t) -> c_int; + #[cfg(not(ossl101))] pub fn EVP_DigestVerifyFinal(ctx: *mut EVP_MD_CTX, sigret: *const c_uchar, siglen: size_t) -> c_int; diff --git a/openssl-sys/src/ossl10x.rs b/openssl-sys/src/ossl10x.rs index 16d669b0..595b673b 100644 --- a/openssl-sys/src/ossl10x.rs +++ b/openssl-sys/src/ossl10x.rs @@ -2,7 +2,9 @@ use std::sync::{Mutex, MutexGuard}; use std::sync::{Once, ONCE_INIT}; use std::mem; -use libc::{c_int, c_char, c_void, c_long, c_uchar, size_t, c_uint, c_ulong, time_t}; +use libc::{c_int, c_char, c_void, c_long, c_uchar, size_t, c_uint, c_ulong}; +#[cfg(not(ossl101))] +use libc::time_t; #[repr(C)] pub struct stack_st_ASN1_OBJECT { diff --git a/openssl/src/crypto/sign.rs b/openssl/src/crypto/sign.rs index 47549574..db3be9fa 100644 --- a/openssl/src/crypto/sign.rs +++ b/openssl/src/crypto/sign.rs @@ -113,7 +113,7 @@ impl<'a> Verifier<'a> { pub fn finish(&self, signature: &[u8]) -> Result<(), ErrorStack> { unsafe { try_ssl_if!(ffi::EVP_DigestVerifyFinal(self.0, - signature.as_ptr() as *const _, + signature.as_ptr() as *const _ as _, signature.len()) != 1); Ok(()) } From 4d567358a1c64aebfcff6128f8d175cfce4e15dc Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 15 Oct 2016 12:31:06 -0700 Subject: [PATCH 036/186] Distinguish between verification errors and "other" errors. --- openssl/src/crypto/sign.rs | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/openssl/src/crypto/sign.rs b/openssl/src/crypto/sign.rs index db3be9fa..78cc62ab 100644 --- a/openssl/src/crypto/sign.rs +++ b/openssl/src/crypto/sign.rs @@ -110,12 +110,19 @@ impl<'a> Verifier<'a> { } } - pub fn finish(&self, signature: &[u8]) -> Result<(), ErrorStack> { + pub fn finish(&self, signature: &[u8]) -> Result { unsafe { - try_ssl_if!(ffi::EVP_DigestVerifyFinal(self.0, - signature.as_ptr() as *const _ as _, - signature.len()) != 1); - Ok(()) + let r = ffi::EVP_DigestVerifyFinal(self.0, + signature.as_ptr() as *const _ as _, + signature.len()); + match r { + 1 => Ok(true), + 0 => { + ErrorStack::get(); // discard error stack + Ok(false) + } + _ => Err(ErrorStack::get()), + } } } } @@ -186,11 +193,11 @@ mod test { let mut verifier = Verifier::new(Type::SHA256, &pkey).unwrap(); verifier.update(INPUT).unwrap(); - verifier.finish(SIGNATURE).unwrap(); + assert!(verifier.finish(SIGNATURE).unwrap()); } #[test] - fn test_verify_err() { + fn test_verify_invalid() { let key = include_bytes!("../../test/rsa.pem"); let private_key = RSA::private_key_from_pem(key).unwrap(); let pkey = PKey::from_rsa(private_key).unwrap(); @@ -198,7 +205,7 @@ mod test { let mut verifier = Verifier::new(Type::SHA256, &pkey).unwrap(); verifier.update(INPUT).unwrap(); verifier.update(b"foobar").unwrap(); - assert!(verifier.finish(SIGNATURE).is_err()); + assert!(!verifier.finish(SIGNATURE).unwrap()); } fn test_hmac(ty: Type, tests: &[(Vec, Vec, Vec)]) { From ea8cbbe9dc0b7f0b0658b1700a563ec8121e8c31 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 15 Oct 2016 12:31:30 -0700 Subject: [PATCH 037/186] Fix typo --- openssl/src/crypto/pkey.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openssl/src/crypto/pkey.rs b/openssl/src/crypto/pkey.rs index e300843e..8b408d29 100644 --- a/openssl/src/crypto/pkey.rs +++ b/openssl/src/crypto/pkey.rs @@ -26,7 +26,7 @@ impl PKey { } } - /// Create a new `PKey` containing an HAMC key. + /// Create a new `PKey` containing an HMAC key. pub fn hmac(key: &[u8]) -> Result { unsafe { assert!(key.len() <= c_int::max_value() as usize); From 2ff82649b5c962da358813768560afe49b947376 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 15 Oct 2016 12:50:03 -0700 Subject: [PATCH 038/186] Add examples to crypto::sign --- openssl/src/crypto/sign.rs | 56 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/openssl/src/crypto/sign.rs b/openssl/src/crypto/sign.rs index 78cc62ab..2a72a390 100644 --- a/openssl/src/crypto/sign.rs +++ b/openssl/src/crypto/sign.rs @@ -1,3 +1,59 @@ +//! Message signatures. +//! +//! The `Signer` allows for the computation of cryptographic signatures of +//! data given a private key. The `Verifier` can then be used with the +//! corresponding public key to verify the integrity and authenticity of that +//! data given the signature. +//! +//! # Examples +//! +//! Sign and verify data given an RSA keypair: +//! +//! ```rust +//! use openssl::crypto::sign::{Signer, Verifier}; +//! use openssl::crypto::rsa::RSA; +//! use openssl::crypto::pkey::PKey; +//! use openssl::crypto::hash::Type; +//! +//! // Generate a keypair +//! let keypair = RSA::generate(2048).unwrap(); +//! let keypair = PKey::from_rsa(keypair).unwrap(); +//! +//! let data = b"hello, world!"; +//! let data2 = b"hola, mundo!"; +//! +//! // Sign the data +//! let mut signer = Signer::new(Type::SHA256, &keypair).unwrap(); +//! signer.update(data).unwrap(); +//! signer.update(data2).unwrap(); +//! let signature = signer.finish().unwrap(); +//! +//! // Verify the data +//! let mut verifier = Verifier::new(Type::SHA256, &keypair).unwrap(); +//! verifier.update(data).unwrap(); +//! verifier.update(data2).unwrap(); +//! assert!(verifier.finish(&signature).unwrap()); +//! ``` +//! +//! Compute an HMAC (note that `Verifier` cannot be used with HMACs): +//! +//! ```rust +//! use openssl::crypto::sign::Signer; +//! use openssl::crypto::pkey::PKey; +//! use openssl::crypto::hash::Type; +//! +//! // Create a PKey +//! let key = PKey::hmac(b"my secret").unwrap(); +//! +//! let data = b"hello, world!"; +//! let data2 = b"hola, mundo!"; +//! +//! // Compute the HMAC +//! let mut signer = Signer::new(Type::SHA256, &key).unwrap(); +//! signer.update(data).unwrap(); +//! signer.update(data2).unwrap(); +//! let hmac = signer.finish().unwrap(); +//! ``` use ffi; use std::io::{self, Write}; use std::marker::PhantomData; From 4ed81d6426271344a8fcc9bc4401f10d0f530634 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 15 Oct 2016 13:12:37 -0700 Subject: [PATCH 039/186] Fix EVP_DigestVerifyFinal version support --- openssl/src/crypto/sign.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/openssl/src/crypto/sign.rs b/openssl/src/crypto/sign.rs index 2a72a390..c5d54597 100644 --- a/openssl/src/crypto/sign.rs +++ b/openssl/src/crypto/sign.rs @@ -168,9 +168,9 @@ impl<'a> Verifier<'a> { pub fn finish(&self, signature: &[u8]) -> Result { unsafe { - let r = ffi::EVP_DigestVerifyFinal(self.0, - signature.as_ptr() as *const _ as _, - signature.len()); + let r = EVP_DigestVerifyFinal(self.0, + signature.as_ptr() as *const _, + signature.len()); match r { 1 => Ok(true), 0 => { @@ -194,6 +194,17 @@ impl<'a> Write for Verifier<'a> { } } +#[cfg(not(ossl101))] +use ffi::EVP_DigestVerifyFinal; + +#[cfg(ossl101)] +#[allow(bad_style)] +unsafe fn EVP_DigestVerifyFinal(ctx: *mut ffi::EVP_MD_CTX, + sigret: *const ::libc::c_uchar, + siglen: ::libc::size_t) -> ::libc::c_int { + ffi::EVP_DigestVerifyFinal(ctx, sigret as *mut _, siglen) +} + #[cfg(test)] mod test { use serialize::hex::FromHex; From 228b8fbc5b5567f19b66754f589d47851817c411 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 15 Oct 2016 13:39:47 -0700 Subject: [PATCH 040/186] Correctly bind BIO_new_mem_buf --- openssl-sys/src/lib.rs | 3 +++ openssl/src/bio.rs | 11 ++++++++++- systest/build.rs | 4 ---- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 6fe44750..67b93f25 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -344,6 +344,9 @@ extern { pub fn BIO_new_socket(sock: c_int, close_flag: c_int) -> *mut BIO; pub fn BIO_read(b: *mut BIO, buf: *mut c_void, len: c_int) -> c_int; pub fn BIO_write(b: *mut BIO, buf: *const c_void, len: c_int) -> c_int; + #[cfg(ossl101)] + pub fn BIO_new_mem_buf(buf: *mut c_void, len: c_int) -> *mut BIO; + #[cfg(not(ossl101))] pub fn BIO_new_mem_buf(buf: *const c_void, len: c_int) -> *mut BIO; pub fn BIO_set_flags(b: *mut BIO, flags: c_int); pub fn BIO_clear_flags(b: *mut BIO, flags: c_int); diff --git a/openssl/src/bio.rs b/openssl/src/bio.rs index 0d82a6c3..22d2cee3 100644 --- a/openssl/src/bio.rs +++ b/openssl/src/bio.rs @@ -22,7 +22,7 @@ impl<'a> MemBioSlice<'a> { assert!(buf.len() <= c_int::max_value() as usize); let bio = unsafe { - try_ssl_null!(ffi::BIO_new_mem_buf(buf.as_ptr() as *const _, buf.len() as c_int)) + try_ssl_null!(BIO_new_mem_buf(buf.as_ptr() as *const _, buf.len() as c_int)) }; Ok(MemBioSlice(bio, PhantomData)) @@ -65,3 +65,12 @@ impl MemBio { } } } + +#[cfg(not(ossl101))] +use ffi::BIO_new_mem_buf; + +#[cfg(ossl101)] +#[allow(bad_style)] +unsafe fn BIO_new_mem_buf(buf: *const ::libc::c_void, len: ::libc::c_int) -> *mut ffi::BIO { + ffi::BIO_new_mem_buf(buf as *mut _, len) +} diff --git a/systest/build.rs b/systest/build.rs index 94c5534e..8fac5536 100644 --- a/systest/build.rs +++ b/systest/build.rs @@ -81,10 +81,6 @@ fn main() { s == "X509V3_EXT_conf_nid" || // weird lhash first param s == "X509V3_EXT_conf" || // weird lhash first param - // one parameter is `const` in OpenSSL 1.0.1, no need for a new - // definition or a new file here. - (s == "BIO_new_mem_buf" && env::var("DEP_OPENSSL_IS_101").is_ok()) || - // Skip some functions with function pointers on windows, not entirely // sure how to get them to work out... (target.contains("windows") && { From 6609a81685bfd205da024523ccc395750c3fd7f3 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 15 Oct 2016 15:02:02 -0700 Subject: [PATCH 041/186] Migrate DSA sign/verify to EVP APIs --- openssl-sys/src/lib.rs | 2 + openssl/src/crypto/dsa.rs | 110 +------------------------------------ openssl/src/crypto/pkey.rs | 12 ++++ openssl/src/crypto/sign.rs | 59 +++++++++++++++++++- 4 files changed, 73 insertions(+), 110 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 67b93f25..ae38d1b3 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -110,6 +110,7 @@ pub const CRYPTO_LOCK: c_int = 1; pub const EVP_MAX_MD_SIZE: c_uint = 64; pub const EVP_PKEY_RSA: c_int = NID_rsaEncryption; pub const EVP_PKEY_HMAC: c_int = NID_hmac; +pub const EVP_PKEY_DSA: c_int = NID_dsa; pub const MBSTRING_ASC: c_int = MBSTRING_FLAG | 1; pub const MBSTRING_BMP: c_int = MBSTRING_FLAG | 2; @@ -120,6 +121,7 @@ pub const MBSTRING_UTF8: c_int = MBSTRING_FLAG; pub const NID_rsaEncryption: c_int = 6; pub const NID_ext_key_usage: c_int = 126; pub const NID_key_usage: c_int = 83; +pub const NID_dsa: c_int = 116; pub const NID_hmac: c_int = 855; pub const PKCS5_SALT_LEN: c_int = 8; diff --git a/openssl/src/crypto/dsa.rs b/openssl/src/crypto/dsa.rs index bb4fe474..addaae2f 100644 --- a/openssl/src/crypto/dsa.rs +++ b/openssl/src/crypto/dsa.rs @@ -2,16 +2,14 @@ use ffi; use std::fmt; use error::ErrorStack; use std::ptr; -use libc::{c_uint, c_int, c_char, c_void}; +use libc::{c_int, c_char, c_void}; use bn::BigNumRef; use bio::{MemBio, MemBioSlice}; -use crypto::hash; -use HashTypeInternals; use crypto::util::{CallbackState, invoke_passwd_cb}; -/// Builder for upfront DSA parameter generateration +/// Builder for upfront DSA parameter generation pub struct DSAParams(*mut ffi::DSA); impl DSAParams { @@ -156,39 +154,6 @@ impl DSA { } } - pub fn sign(&self, hash: hash::Type, message: &[u8]) -> Result, ErrorStack> { - let k_len = self.size().expect("DSA missing a q") as c_uint; - let mut sig = vec![0; k_len as usize]; - let mut sig_len = k_len; - assert!(self.has_private_key()); - - unsafe { - try_ssl!(ffi::DSA_sign(hash.as_nid() as c_int, - message.as_ptr(), - message.len() as c_int, - sig.as_mut_ptr(), - &mut sig_len, - self.0)); - sig.set_len(sig_len as usize); - sig.shrink_to_fit(); - Ok(sig) - } - } - - pub fn verify(&self, hash: hash::Type, message: &[u8], sig: &[u8]) -> Result { - unsafe { - let result = ffi::DSA_verify(hash.as_nid() as c_int, - message.as_ptr(), - message.len() as c_int, - sig.as_ptr(), - sig.len() as c_int, - self.0); - - try_ssl_if!(result == -1); - Ok(result == 1) - } - } - pub fn as_ptr(&self) -> *mut ffi::DSA { self.0 } @@ -282,76 +247,7 @@ mod test { #[test] pub fn test_generate() { - let key = DSA::generate(1024).unwrap(); - - key.public_key_to_pem().unwrap(); - key.private_key_to_pem().unwrap(); - - let input: Vec = (0..25).cycle().take(1024).collect(); - - let digest = { - let mut sha = Hasher::new(Type::SHA1).unwrap(); - sha.write_all(&input).unwrap(); - sha.finish().unwrap() - }; - - let sig = key.sign(Type::SHA1, &digest).unwrap(); - let verified = key.verify(Type::SHA1, &digest, &sig).unwrap(); - assert!(verified); - } - - #[test] - pub fn test_sign_verify() { - let input: Vec = (0..25).cycle().take(1024).collect(); - - let private_key = { - let key = include_bytes!("../../test/dsa.pem"); - DSA::private_key_from_pem(key).unwrap() - }; - - let public_key = { - let key = include_bytes!("../../test/dsa.pem.pub"); - DSA::public_key_from_pem(key).unwrap() - }; - - let digest = { - let mut sha = Hasher::new(Type::SHA1).unwrap(); - sha.write_all(&input).unwrap(); - sha.finish().unwrap() - }; - - let sig = private_key.sign(Type::SHA1, &digest).unwrap(); - let verified = public_key.verify(Type::SHA1, &digest, &sig).unwrap(); - assert!(verified); - } - - #[test] - pub fn test_sign_verify_fail() { - let input: Vec = (0..25).cycle().take(128).collect(); - let private_key = { - let key = include_bytes!("../../test/dsa.pem"); - DSA::private_key_from_pem(key).unwrap() - }; - - let public_key = { - let key = include_bytes!("../../test/dsa.pem.pub"); - DSA::public_key_from_pem(key).unwrap() - }; - - let digest = { - let mut sha = Hasher::new(Type::SHA1).unwrap(); - sha.write_all(&input).unwrap(); - sha.finish().unwrap() - }; - - let mut sig = private_key.sign(Type::SHA1, &digest).unwrap(); - // tamper with the sig this should cause a failure - let len = sig.len(); - sig[len / 2] = 0; - sig[len - 1] = 0; - if let Ok(true) = public_key.verify(Type::SHA1, &digest, &sig) { - panic!("Tampered with signatures should not verify!"); - } + DSA::generate(1024).unwrap(); } #[test] diff --git a/openssl/src/crypto/pkey.rs b/openssl/src/crypto/pkey.rs index 8b408d29..67ff7520 100644 --- a/openssl/src/crypto/pkey.rs +++ b/openssl/src/crypto/pkey.rs @@ -4,6 +4,7 @@ use std::mem; use ffi; use bio::{MemBio, MemBioSlice}; +use crypto::dsa::DSA; use crypto::rsa::RSA; use error::ErrorStack; use crypto::util::{CallbackState, invoke_passwd_cb}; @@ -26,6 +27,17 @@ impl PKey { } } + /// Create a new `PKey` containing a DSA key. + pub fn from_dsa(dsa: DSA) -> Result { + unsafe { + let evp = try_ssl_null!(ffi::EVP_PKEY_new()); + let pkey = PKey(evp); + try_ssl!(ffi::EVP_PKEY_assign(pkey.0, ffi::EVP_PKEY_DSA, dsa.as_ptr() as *mut _)); + mem::forget(dsa); + Ok(pkey) + } + } + /// Create a new `PKey` containing an HMAC key. pub fn hmac(key: &[u8]) -> Result { unsafe { diff --git a/openssl/src/crypto/sign.rs b/openssl/src/crypto/sign.rs index c5d54597..24078fdc 100644 --- a/openssl/src/crypto/sign.rs +++ b/openssl/src/crypto/sign.rs @@ -113,6 +113,8 @@ impl<'a> Signer<'a> { let mut buf = vec![0; len]; try_ssl_if!(ffi::EVP_DigestSignFinal(self.0, buf.as_mut_ptr() as *mut _, &mut len) != 1); + // The advertised length is not always equal to the real length for things like DSA + buf.truncate(len); Ok(buf) } } @@ -213,6 +215,7 @@ mod test { use crypto::hash::Type; use crypto::sign::{Signer, Verifier}; use crypto::rsa::RSA; + use crypto::dsa::DSA; use crypto::pkey::PKey; static INPUT: &'static [u8] = @@ -240,7 +243,7 @@ mod test { 112, 223, 200, 163, 42, 70, 149, 67, 208, 25, 238, 251, 71]; #[test] - fn test_sign() { + fn rsa_sign() { let key = include_bytes!("../../test/rsa.pem"); let private_key = RSA::private_key_from_pem(key).unwrap(); let pkey = PKey::from_rsa(private_key).unwrap(); @@ -253,7 +256,7 @@ mod test { } #[test] - fn test_verify_ok() { + fn rsa_verify_ok() { let key = include_bytes!("../../test/rsa.pem"); let private_key = RSA::private_key_from_pem(key).unwrap(); let pkey = PKey::from_rsa(private_key).unwrap(); @@ -264,7 +267,7 @@ mod test { } #[test] - fn test_verify_invalid() { + fn rsa_verify_invalid() { let key = include_bytes!("../../test/rsa.pem"); let private_key = RSA::private_key_from_pem(key).unwrap(); let pkey = PKey::from_rsa(private_key).unwrap(); @@ -275,6 +278,56 @@ mod test { assert!(!verifier.finish(SIGNATURE).unwrap()); } + #[test] + pub fn dsa_sign_verify() { + let input: Vec = (0..25).cycle().take(1024).collect(); + + let private_key = { + let key = include_bytes!("../../test/dsa.pem"); + PKey::from_dsa(DSA::private_key_from_pem(key).unwrap()).unwrap() + }; + + let public_key = { + let key = include_bytes!("../../test/dsa.pem.pub"); + PKey::from_dsa(DSA::public_key_from_pem(key).unwrap()).unwrap() + }; + + let mut signer = Signer::new(Type::SHA1, &private_key).unwrap(); + signer.update(&input).unwrap(); + let sig = signer.finish().unwrap(); + + let mut verifier = Verifier::new(Type::SHA1, &public_key).unwrap(); + verifier.update(&input).unwrap(); + assert!(verifier.finish(&sig).unwrap()); + } + + #[test] + pub fn dsa_sign_verify_fail() { + let input: Vec = (0..25).cycle().take(1024).collect(); + + let private_key = { + let key = include_bytes!("../../test/dsa.pem"); + PKey::from_dsa(DSA::private_key_from_pem(key).unwrap()).unwrap() + }; + + let public_key = { + let key = include_bytes!("../../test/dsa.pem.pub"); + PKey::from_dsa(DSA::public_key_from_pem(key).unwrap()).unwrap() + }; + + let mut signer = Signer::new(Type::SHA1, &private_key).unwrap(); + signer.update(&input).unwrap(); + let mut sig = signer.finish().unwrap(); + sig[0] -= 1; + + let mut verifier = Verifier::new(Type::SHA1, &public_key).unwrap(); + verifier.update(&input).unwrap(); + match verifier.finish(&sig) { + Ok(true) => panic!("unexpected success"), + Ok(false) | Err(_) => {}, + } + } + fn test_hmac(ty: Type, tests: &[(Vec, Vec, Vec)]) { for &(ref key, ref data, ref res) in tests.iter() { let pkey = PKey::hmac(key).unwrap(); From c171be551ac8d22c91cbf550e21215ae2c8b6abc Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 15 Oct 2016 15:23:29 -0700 Subject: [PATCH 042/186] De-enumify message digests --- openssl/src/crypto/hash.rs | 112 +++++++++++++++++++---------------- openssl/src/crypto/pkcs12.rs | 6 +- openssl/src/crypto/pkcs5.rs | 25 ++++---- openssl/src/crypto/sign.rs | 43 +++++++------- openssl/src/lib.rs | 7 --- openssl/src/ssl/tests/mod.rs | 12 ++-- openssl/src/x509/mod.rs | 23 ++++--- openssl/src/x509/tests.rs | 6 +- 8 files changed, 116 insertions(+), 118 deletions(-) diff --git a/openssl/src/crypto/hash.rs b/openssl/src/crypto/hash.rs index e3bf4997..2fa75807 100644 --- a/openssl/src/crypto/hash.rs +++ b/openssl/src/crypto/hash.rs @@ -8,48 +8,57 @@ use ffi::{EVP_MD_CTX_new, EVP_MD_CTX_free}; #[cfg(any(ossl101, ossl102))] use ffi::{EVP_MD_CTX_create as EVP_MD_CTX_new, EVP_MD_CTX_destroy as EVP_MD_CTX_free}; -use HashTypeInternals; use error::ErrorStack; -use nid::Nid; -/// Message digest (hash) type. #[derive(Copy, Clone)] -pub enum Type { - MD5, - SHA1, - SHA224, - SHA256, - SHA384, - SHA512, - RIPEMD160, -} +pub struct MessageDigest(*const ffi::EVP_MD); -impl HashTypeInternals for Type { - fn as_nid(&self) -> Nid { - match *self { - Type::MD5 => Nid::MD5, - Type::SHA1 => Nid::SHA1, - Type::SHA224 => Nid::SHA224, - Type::SHA256 => Nid::SHA256, - Type::SHA384 => Nid::SHA384, - Type::SHA512 => Nid::SHA512, - Type::RIPEMD160 => Nid::RIPEMD160, +impl MessageDigest { + pub fn md5() -> MessageDigest { + unsafe { + MessageDigest(ffi::EVP_md5()) } } - fn evp_md(&self) -> *const ffi::EVP_MD { + pub fn sha1() -> MessageDigest { unsafe { - match *self { - Type::MD5 => ffi::EVP_md5(), - Type::SHA1 => ffi::EVP_sha1(), - Type::SHA224 => ffi::EVP_sha224(), - Type::SHA256 => ffi::EVP_sha256(), - Type::SHA384 => ffi::EVP_sha384(), - Type::SHA512 => ffi::EVP_sha512(), - Type::RIPEMD160 => ffi::EVP_ripemd160(), - } + MessageDigest(ffi::EVP_sha1()) } } + + pub fn sha224() -> MessageDigest { + unsafe { + MessageDigest(ffi::EVP_sha224()) + } + } + + pub fn sha256() -> MessageDigest { + unsafe { + MessageDigest(ffi::EVP_sha256()) + } + } + + pub fn sha384() -> MessageDigest { + unsafe { + MessageDigest(ffi::EVP_sha384()) + } + } + + pub fn sha512() -> MessageDigest { + unsafe { + MessageDigest(ffi::EVP_sha512()) + } + } + + pub fn ripemd160() -> MessageDigest { + unsafe { + MessageDigest(ffi::EVP_ripemd160()) + } + } + + pub fn as_ptr(&self) -> *const ffi::EVP_MD { + self.0 + } } #[derive(PartialEq, Copy, Clone)] @@ -68,20 +77,22 @@ use self::State::*; /// Calculate a hash in one go. /// /// ``` -/// use openssl::crypto::hash::{hash, Type}; +/// use openssl::crypto::hash::{hash, MessageDigest}; +/// /// let data = b"\x42\xF4\x97\xE0"; /// let spec = b"\x7c\x43\x0f\x17\x8a\xef\xdf\x14\x87\xfe\xe7\x14\x4e\x96\x41\xe2"; -/// let res = hash(Type::MD5, data).unwrap(); +/// let res = hash(MessageDigest::md5(), data).unwrap(); /// assert_eq!(res, spec); /// ``` /// /// Use the `Write` trait to supply the input in chunks. /// /// ``` -/// use openssl::crypto::hash::{Hasher, Type}; +/// use openssl::crypto::hash::{Hasher, MessageDigest}; +/// /// let data = [b"\x42\xF4", b"\x97\xE0"]; /// let spec = b"\x7c\x43\x0f\x17\x8a\xef\xdf\x14\x87\xfe\xe7\x14\x4e\x96\x41\xe2"; -/// let mut h = Hasher::new(Type::MD5).unwrap(); +/// let mut h = Hasher::new(MessageDigest::md5()).unwrap(); /// h.update(data[0]).unwrap(); /// h.update(data[1]).unwrap(); /// let res = h.finish().unwrap(); @@ -96,21 +107,20 @@ use self::State::*; pub struct Hasher { ctx: *mut ffi::EVP_MD_CTX, md: *const ffi::EVP_MD, - type_: Type, + type_: MessageDigest, state: State, } impl Hasher { /// Creates a new `Hasher` with the specified hash type. - pub fn new(ty: Type) -> Result { + pub fn new(ty: MessageDigest) -> Result { ffi::init(); let ctx = unsafe { try_ssl_null!(EVP_MD_CTX_new()) }; - let md = ty.evp_md(); let mut h = Hasher { ctx: ctx, - md: md, + md: ty.as_ptr(), type_: ty, state: Finalized, }; @@ -204,7 +214,7 @@ impl Drop for Hasher { } /// Computes the hash of the `data` with the hash `t`. -pub fn hash(t: Type, data: &[u8]) -> Result, ErrorStack> { +pub fn hash(t: MessageDigest, data: &[u8]) -> Result, ErrorStack> { let mut h = try!(Hasher::new(t)); try!(h.update(data)); h.finish() @@ -213,10 +223,10 @@ pub fn hash(t: Type, data: &[u8]) -> Result, ErrorStack> { #[cfg(test)] mod tests { use serialize::hex::{FromHex, ToHex}; - use super::{hash, Hasher, Type}; + use super::{hash, Hasher, MessageDigest}; use std::io::prelude::*; - fn hash_test(hashtype: Type, hashtest: &(&str, &str)) { + fn hash_test(hashtype: MessageDigest, hashtest: &(&str, &str)) { let res = hash(hashtype, &*hashtest.0.from_hex().unwrap()).unwrap(); assert_eq!(res.to_hex(), hashtest.1); } @@ -259,13 +269,13 @@ mod tests { #[test] fn test_md5() { for test in md5_tests.iter() { - hash_test(Type::MD5, test); + hash_test(MessageDigest::md5(), test); } } #[test] fn test_md5_recycle() { - let mut h = Hasher::new(Type::MD5).unwrap(); + let mut h = Hasher::new(MessageDigest::md5()).unwrap(); for test in md5_tests.iter() { hash_recycle_test(&mut h, test); } @@ -273,11 +283,11 @@ mod tests { #[test] fn test_finish_twice() { - let mut h = Hasher::new(Type::MD5).unwrap(); + let mut h = Hasher::new(MessageDigest::md5()).unwrap(); h.write_all(&*md5_tests[6].0.from_hex().unwrap()).unwrap(); h.finish().unwrap(); let res = h.finish().unwrap(); - let null = hash(Type::MD5, &[]).unwrap(); + let null = hash(MessageDigest::md5(), &[]).unwrap(); assert_eq!(res, null); } @@ -287,7 +297,7 @@ mod tests { let inp = md5_tests[i].0.from_hex().unwrap(); assert!(inp.len() > 2); let p = inp.len() / 2; - let h0 = Hasher::new(Type::MD5).unwrap(); + let h0 = Hasher::new(MessageDigest::md5()).unwrap(); println!("Clone a new hasher"); let mut h1 = h0.clone(); @@ -315,7 +325,7 @@ mod tests { let tests = [("616263", "a9993e364706816aba3e25717850c26c9cd0d89d")]; for test in tests.iter() { - hash_test(Type::SHA1, test); + hash_test(MessageDigest::sha1(), test); } } @@ -325,7 +335,7 @@ mod tests { "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")]; for test in tests.iter() { - hash_test(Type::SHA256, test); + hash_test(MessageDigest::sha256(), test); } } @@ -334,7 +344,7 @@ mod tests { let tests = [("616263", "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc")]; for test in tests.iter() { - hash_test(Type::RIPEMD160, test); + hash_test(MessageDigest::ripemd160(), test); } } } diff --git a/openssl/src/crypto/pkcs12.rs b/openssl/src/crypto/pkcs12.rs index 5f03a3d5..b028f29d 100644 --- a/openssl/src/crypto/pkcs12.rs +++ b/openssl/src/crypto/pkcs12.rs @@ -97,7 +97,7 @@ mod compat { #[cfg(test)] mod test { - use crypto::hash::Type::SHA1; + use crypto::hash::MessageDigest; use serialize::hex::ToHex; use super::*; @@ -108,11 +108,11 @@ mod test { let pkcs12 = Pkcs12::from_der(der).unwrap(); let parsed = pkcs12.parse("mypass").unwrap(); - assert_eq!(parsed.cert.fingerprint(SHA1).unwrap().to_hex(), + assert_eq!(parsed.cert.fingerprint(MessageDigest::sha1()).unwrap().to_hex(), "59172d9313e84459bcff27f967e79e6e9217e584"); assert_eq!(parsed.chain.len(), 1); - assert_eq!(parsed.chain[0].fingerprint(SHA1).unwrap().to_hex(), + assert_eq!(parsed.chain[0].fingerprint(MessageDigest::sha1()).unwrap().to_hex(), "c0cbdf7cdd03c9773e5468e1f6d2da7d5cbb1875"); } } diff --git a/openssl/src/crypto/pkcs5.rs b/openssl/src/crypto/pkcs5.rs index adcbc9db..56ce3e26 100644 --- a/openssl/src/crypto/pkcs5.rs +++ b/openssl/src/crypto/pkcs5.rs @@ -2,8 +2,7 @@ use libc::c_int; use std::ptr; use ffi; -use HashTypeInternals; -use crypto::hash; +use crypto::hash::MessageDigest; use crypto::symm; use error::ErrorStack; @@ -24,7 +23,7 @@ pub struct KeyIvPair { /// New applications should not use this and instead use `pbkdf2_hmac_sha1` or /// another more modern key derivation algorithm. pub fn evp_bytes_to_key_pbkdf1_compatible(typ: symm::Type, - message_digest_type: hash::Type, + message_digest_type: MessageDigest, data: &[u8], salt: Option<&[u8]>, count: u32) @@ -41,7 +40,7 @@ pub fn evp_bytes_to_key_pbkdf1_compatible(typ: symm::Type, ffi::init(); let typ = typ.as_ptr(); - let message_digest_type = message_digest_type.evp_md(); + let message_digest_type = message_digest_type.as_ptr(); let len = ffi::EVP_BytesToKey(typ, message_digest_type, @@ -97,7 +96,7 @@ pub fn pbkdf2_hmac_sha1(pass: &[u8], pub fn pbkdf2_hmac(pass: &[u8], salt: &[u8], iter: usize, - hash: hash::Type, + hash: MessageDigest, keylen: usize) -> Result, ErrorStack> { unsafe { @@ -108,7 +107,7 @@ pub fn pbkdf2_hmac(pass: &[u8], salt.as_ptr(), salt.len() as c_int, iter as c_int, - hash.evp_md(), + hash.as_ptr(), keylen as c_int, out.as_mut_ptr())); Ok(out) @@ -117,7 +116,7 @@ pub fn pbkdf2_hmac(pass: &[u8], #[cfg(test)] mod tests { - use crypto::hash; + use crypto::hash::MessageDigest; use crypto::symm; // Test vectors from @@ -162,11 +161,11 @@ mod tests { // https://git.lysator.liu.se/nettle/nettle/blob/nettle_3.1.1_release_20150424/testsuite/pbkdf2-test.c #[test] fn test_pbkdf2_hmac_sha256() { - assert_eq!(super::pbkdf2_hmac(b"passwd", b"salt", 1, hash::Type::SHA256, 16).unwrap(), + assert_eq!(super::pbkdf2_hmac(b"passwd", b"salt", 1, MessageDigest::sha256(), 16).unwrap(), vec![0x55_u8, 0xac_u8, 0x04_u8, 0x6e_u8, 0x56_u8, 0xe3_u8, 0x08_u8, 0x9f_u8, 0xec_u8, 0x16_u8, 0x91_u8, 0xc2_u8, 0x25_u8, 0x44_u8, 0xb6_u8, 0x05_u8]); - assert_eq!(super::pbkdf2_hmac(b"Password", b"NaCl", 80000, hash::Type::SHA256, 16).unwrap(), + assert_eq!(super::pbkdf2_hmac(b"Password", b"NaCl", 80000, MessageDigest::sha256(), 16).unwrap(), vec![0x4d_u8, 0xdc_u8, 0xd8_u8, 0xf6_u8, 0x0b_u8, 0x98_u8, 0xbe_u8, 0x21_u8, 0x83_u8, 0x0c_u8, 0xee_u8, 0x5e_u8, 0xf2_u8, 0x27_u8, 0x01_u8, 0xf9_u8]); } @@ -175,7 +174,7 @@ mod tests { // https://git.lysator.liu.se/nettle/nettle/blob/nettle_3.1.1_release_20150424/testsuite/pbkdf2-test.c #[test] fn test_pbkdf2_hmac_sha512() { - assert_eq!(super::pbkdf2_hmac(b"password", b"NaCL", 1, hash::Type::SHA512, 64).unwrap(), + assert_eq!(super::pbkdf2_hmac(b"password", b"NaCL", 1, MessageDigest::sha512(), 64).unwrap(), vec![0x73_u8, 0xde_u8, 0xcf_u8, 0xa5_u8, 0x8a_u8, 0xa2_u8, 0xe8_u8, 0x4f_u8, 0x94_u8, 0x77_u8, 0x1a_u8, 0x75_u8, 0x73_u8, 0x6b_u8, 0xb8_u8, 0x8b_u8, 0xd3_u8, 0xc7_u8, 0xb3_u8, 0x82_u8, 0x70_u8, 0xcf_u8, 0xb5_u8, 0x0c_u8, @@ -185,7 +184,7 @@ mod tests { 0x60_u8, 0x60_u8, 0xa0_u8, 0x9f_u8, 0x76_u8, 0x41_u8, 0x5e_u8, 0x9f_u8, 0x71_u8, 0xea_u8, 0x47_u8, 0xf9_u8, 0xe9_u8, 0x06_u8, 0x43_u8, 0x06_u8]); - assert_eq!(super::pbkdf2_hmac(b"pass\0word", b"sa\0lt", 1, hash::Type::SHA512, 64).unwrap(), + assert_eq!(super::pbkdf2_hmac(b"pass\0word", b"sa\0lt", 1, MessageDigest::sha512(), 64).unwrap(), vec![0x71_u8, 0xa0_u8, 0xec_u8, 0x84_u8, 0x2a_u8, 0xbd_u8, 0x5c_u8, 0x67_u8, 0x8b_u8, 0xcf_u8, 0xd1_u8, 0x45_u8, 0xf0_u8, 0x9d_u8, 0x83_u8, 0x52_u8, 0x2f_u8, 0x93_u8, 0x36_u8, 0x15_u8, 0x60_u8, 0x56_u8, 0x3c_u8, 0x4d_u8, @@ -198,7 +197,7 @@ mod tests { assert_eq!(super::pbkdf2_hmac(b"passwordPASSWORDpassword", b"salt\0\0\0", 50, - hash::Type::SHA512, + MessageDigest::sha512(), 64).unwrap(), vec![0x01_u8, 0x68_u8, 0x71_u8, 0xa4_u8, 0xc4_u8, 0xb7_u8, 0x5f_u8, 0x96_u8, 0x85_u8, 0x7f_u8, 0xd2_u8, 0xb9_u8, 0xf8_u8, 0xca_u8, 0x28_u8, 0x02_u8, @@ -230,7 +229,7 @@ mod tests { 0_u8, 0_u8, 0_u8]; assert_eq!(super::evp_bytes_to_key_pbkdf1_compatible(symm::Type::AES_256_CBC, - hash::Type::SHA1, + MessageDigest::sha1(), &data, Some(&salt), 1).unwrap(), diff --git a/openssl/src/crypto/sign.rs b/openssl/src/crypto/sign.rs index 24078fdc..fdedd4d5 100644 --- a/openssl/src/crypto/sign.rs +++ b/openssl/src/crypto/sign.rs @@ -13,7 +13,7 @@ //! use openssl::crypto::sign::{Signer, Verifier}; //! use openssl::crypto::rsa::RSA; //! use openssl::crypto::pkey::PKey; -//! use openssl::crypto::hash::Type; +//! use openssl::crypto::hash::MessageDigest; //! //! // Generate a keypair //! let keypair = RSA::generate(2048).unwrap(); @@ -23,13 +23,13 @@ //! let data2 = b"hola, mundo!"; //! //! // Sign the data -//! let mut signer = Signer::new(Type::SHA256, &keypair).unwrap(); +//! let mut signer = Signer::new(MessageDigest::sha256(), &keypair).unwrap(); //! signer.update(data).unwrap(); //! signer.update(data2).unwrap(); //! let signature = signer.finish().unwrap(); //! //! // Verify the data -//! let mut verifier = Verifier::new(Type::SHA256, &keypair).unwrap(); +//! let mut verifier = Verifier::new(MessageDigest::sha256(), &keypair).unwrap(); //! verifier.update(data).unwrap(); //! verifier.update(data2).unwrap(); //! assert!(verifier.finish(&signature).unwrap()); @@ -40,7 +40,7 @@ //! ```rust //! use openssl::crypto::sign::Signer; //! use openssl::crypto::pkey::PKey; -//! use openssl::crypto::hash::Type; +//! use openssl::crypto::hash::MessageDigest; //! //! // Create a PKey //! let key = PKey::hmac(b"my secret").unwrap(); @@ -49,7 +49,7 @@ //! let data2 = b"hola, mundo!"; //! //! // Compute the HMAC -//! let mut signer = Signer::new(Type::SHA256, &key).unwrap(); +//! let mut signer = Signer::new(MessageDigest::sha256(), &key).unwrap(); //! signer.update(data).unwrap(); //! signer.update(data2).unwrap(); //! let hmac = signer.finish().unwrap(); @@ -59,8 +59,7 @@ use std::io::{self, Write}; use std::marker::PhantomData; use std::ptr; -use HashTypeInternals; -use crypto::hash::Type; +use crypto::hash::MessageDigest; use crypto::pkey::PKey; use error::ErrorStack; @@ -80,14 +79,14 @@ impl<'a> Drop for Signer<'a> { } impl<'a> Signer<'a> { - pub fn new(type_: Type, pkey: &'a PKey) -> Result, ErrorStack> { + pub fn new(type_: MessageDigest, pkey: &'a PKey) -> Result, ErrorStack> { unsafe { ffi::init(); let ctx = try_ssl_null!(EVP_MD_CTX_new()); let r = ffi::EVP_DigestSignInit(ctx, ptr::null_mut(), - type_.evp_md(), + type_.as_ptr(), ptr::null_mut(), pkey.as_ptr()); if r != 1 { @@ -142,14 +141,14 @@ impl<'a> Drop for Verifier<'a> { } impl<'a> Verifier<'a> { - pub fn new(type_: Type, pkey: &'a PKey) -> Result, ErrorStack> { + pub fn new(type_: MessageDigest, pkey: &'a PKey) -> Result, ErrorStack> { unsafe { ffi::init(); let ctx = try_ssl_null!(EVP_MD_CTX_new()); let r = ffi::EVP_DigestVerifyInit(ctx, ptr::null_mut(), - type_.evp_md(), + type_.as_ptr(), ptr::null_mut(), pkey.as_ptr()); if r != 1 { @@ -212,7 +211,7 @@ mod test { use serialize::hex::FromHex; use std::iter; - use crypto::hash::Type; + use crypto::hash::MessageDigest; use crypto::sign::{Signer, Verifier}; use crypto::rsa::RSA; use crypto::dsa::DSA; @@ -248,7 +247,7 @@ mod test { let private_key = RSA::private_key_from_pem(key).unwrap(); let pkey = PKey::from_rsa(private_key).unwrap(); - let mut signer = Signer::new(Type::SHA256, &pkey).unwrap(); + let mut signer = Signer::new(MessageDigest::sha256(), &pkey).unwrap(); signer.update(INPUT).unwrap(); let result = signer.finish().unwrap(); @@ -261,7 +260,7 @@ mod test { let private_key = RSA::private_key_from_pem(key).unwrap(); let pkey = PKey::from_rsa(private_key).unwrap(); - let mut verifier = Verifier::new(Type::SHA256, &pkey).unwrap(); + let mut verifier = Verifier::new(MessageDigest::sha256(), &pkey).unwrap(); verifier.update(INPUT).unwrap(); assert!(verifier.finish(SIGNATURE).unwrap()); } @@ -272,7 +271,7 @@ mod test { let private_key = RSA::private_key_from_pem(key).unwrap(); let pkey = PKey::from_rsa(private_key).unwrap(); - let mut verifier = Verifier::new(Type::SHA256, &pkey).unwrap(); + let mut verifier = Verifier::new(MessageDigest::sha256(), &pkey).unwrap(); verifier.update(INPUT).unwrap(); verifier.update(b"foobar").unwrap(); assert!(!verifier.finish(SIGNATURE).unwrap()); @@ -292,11 +291,11 @@ mod test { PKey::from_dsa(DSA::public_key_from_pem(key).unwrap()).unwrap() }; - let mut signer = Signer::new(Type::SHA1, &private_key).unwrap(); + let mut signer = Signer::new(MessageDigest::sha1(), &private_key).unwrap(); signer.update(&input).unwrap(); let sig = signer.finish().unwrap(); - let mut verifier = Verifier::new(Type::SHA1, &public_key).unwrap(); + let mut verifier = Verifier::new(MessageDigest::sha1(), &public_key).unwrap(); verifier.update(&input).unwrap(); assert!(verifier.finish(&sig).unwrap()); } @@ -315,12 +314,12 @@ mod test { PKey::from_dsa(DSA::public_key_from_pem(key).unwrap()).unwrap() }; - let mut signer = Signer::new(Type::SHA1, &private_key).unwrap(); + let mut signer = Signer::new(MessageDigest::sha1(), &private_key).unwrap(); signer.update(&input).unwrap(); let mut sig = signer.finish().unwrap(); sig[0] -= 1; - let mut verifier = Verifier::new(Type::SHA1, &public_key).unwrap(); + let mut verifier = Verifier::new(MessageDigest::sha1(), &public_key).unwrap(); verifier.update(&input).unwrap(); match verifier.finish(&sig) { Ok(true) => panic!("unexpected success"), @@ -328,7 +327,7 @@ mod test { } } - fn test_hmac(ty: Type, tests: &[(Vec, Vec, Vec)]) { + fn test_hmac(ty: MessageDigest, tests: &[(Vec, Vec, Vec)]) { for &(ref key, ref data, ref res) in tests.iter() { let pkey = PKey::hmac(key).unwrap(); let mut signer = Signer::new(ty, &pkey).unwrap(); @@ -365,7 +364,7 @@ mod test { .to_vec(), "6f630fad67cda0ee1fb1f562db3aa53e".from_hex().unwrap())]; - test_hmac(Type::MD5, &tests); + test_hmac(MessageDigest::md5(), &tests); } #[test] @@ -396,6 +395,6 @@ mod test { .to_vec(), "e8e99d0f45237d786d6bbaa7965c7808bbff1a91".from_hex().unwrap())]; - test_hmac(Type::SHA1, &tests); + test_hmac(MessageDigest::sha1(), &tests); } } diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index aa34753c..62968742 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -16,8 +16,6 @@ extern crate tempdir; #[doc(inline)] pub use ffi::init; -use nid::Nid; - mod macros; pub mod asn1; @@ -30,8 +28,3 @@ pub mod nid; pub mod ssl; pub mod version; pub mod x509; - -trait HashTypeInternals { - fn as_nid(&self) -> Nid; - fn evp_md(&self) -> *const ffi::EVP_MD; -} diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index ce1ba8ca..284f5c78 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -14,7 +14,7 @@ use std::time::Duration; use tempdir::TempDir; -use crypto::hash::Type::SHA256; +use crypto::hash::MessageDigest; use ssl; use ssl::SSL_VERIFY_PEER; use ssl::SslMethod::Tls; @@ -171,7 +171,7 @@ macro_rules! run_test( use ssl::SslMethod; use ssl::{SslContext, Ssl, SslStream}; use ssl::SSL_VERIFY_PEER; - use crypto::hash::Type::{SHA1, SHA256}; + use crypto::hash::MessageDigest; use x509::X509StoreContext; use serialize::hex::FromHex; use super::Server; @@ -314,7 +314,7 @@ run_test!(verify_callback_data, |method, stream| { match cert { None => false, Some(cert) => { - let fingerprint = cert.fingerprint(SHA1).unwrap(); + let fingerprint = cert.fingerprint(MessageDigest::sha1()).unwrap(); fingerprint == node_id } } @@ -343,7 +343,7 @@ run_test!(ssl_verify_callback, |method, stream| { match x509.current_cert() { None => false, Some(cert) => { - let fingerprint = cert.fingerprint(SHA1).unwrap(); + let fingerprint = cert.fingerprint(MessageDigest::sha1()).unwrap(); fingerprint == node_id } } @@ -440,7 +440,7 @@ fn test_write_direct() { run_test!(get_peer_certificate, |method, stream| { let stream = SslStream::connect(&SslContext::new(method).unwrap(), stream).unwrap(); let cert = stream.ssl().peer_certificate().unwrap(); - let fingerprint = cert.fingerprint(SHA1).unwrap(); + let fingerprint = cert.fingerprint(MessageDigest::sha1()).unwrap(); let node_hash_str = "59172d9313e84459bcff27f967e79e6e9217e584"; let node_id = node_hash_str.from_hex().unwrap(); assert_eq!(node_id, fingerprint) @@ -797,7 +797,7 @@ mod dtlsv1 { use std::net::TcpStream; use std::thread; - use crypto::hash::Type::SHA256; + use crypto::hash::MessageDigest; use ssl::SslMethod; use ssl::SslMethod::Dtls; use ssl::{SslContext, SslStream}; diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 9fed94e2..c429b486 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -10,13 +10,10 @@ use std::slice; use std::collections::HashMap; use std::marker::PhantomData; -use HashTypeInternals; use asn1::Asn1Time; use asn1::Asn1TimeRef; - use bio::{MemBio, MemBioSlice}; -use crypto::hash; -use crypto::hash::Type as HashType; +use crypto::hash::MessageDigest; use crypto::pkey::PKey; use crypto::rand::rand_bytes; use ffi; @@ -129,7 +126,7 @@ impl X509StoreContext { /// # Example /// /// ``` -/// use openssl::crypto::hash::Type; +/// use openssl::crypto::hash::MessageDigest; /// use openssl::crypto::pkey::PKey; /// use openssl::crypto::rsa::RSA; /// use openssl::x509::X509Generator; @@ -141,7 +138,7 @@ impl X509StoreContext { /// let gen = X509Generator::new() /// .set_valid_period(365*2) /// .add_name("CN".to_owned(), "SuperMegaCorp Inc.".to_owned()) -/// .set_sign_hash(Type::SHA256) +/// .set_sign_hash(MessageDigest::sha256()) /// .add_extension(Extension::KeyUsage(vec![KeyUsageOption::DigitalSignature])); /// /// let cert = gen.sign(&pkey).unwrap(); @@ -152,7 +149,7 @@ pub struct X509Generator { days: u32, names: Vec<(String, String)>, extensions: Extensions, - hash_type: HashType, + hash_type: MessageDigest, } impl X509Generator { @@ -168,7 +165,7 @@ impl X509Generator { days: 365, names: vec![], extensions: Extensions::new(), - hash_type: HashType::SHA1, + hash_type: MessageDigest::sha1(), } } @@ -239,7 +236,7 @@ impl X509Generator { self } - pub fn set_sign_hash(mut self, hash_type: hash::Type) -> X509Generator { + pub fn set_sign_hash(mut self, hash_type: MessageDigest) -> X509Generator { self.hash_type = hash_type; self } @@ -358,7 +355,7 @@ impl X509Generator { &ext.to_string())); } - let hash_fn = self.hash_type.evp_md(); + let hash_fn = self.hash_type.as_ptr(); try_ssl!(ffi::X509_sign(x509.as_ptr(), p_key.as_ptr(), hash_fn)); Ok(x509) } @@ -380,7 +377,7 @@ impl X509Generator { try_ssl!(ffi::X509_REQ_add_extensions(req, exts as *mut _)); } - let hash_fn = self.hash_type.evp_md(); + let hash_fn = self.hash_type.as_ptr(); try_ssl!(ffi::X509_REQ_sign(req, p_key.as_ptr(), hash_fn)); Ok(X509Req::new(req)) @@ -438,9 +435,9 @@ impl<'a> X509Ref<'a> { } /// Returns certificate fingerprint calculated using provided hash - pub fn fingerprint(&self, hash_type: hash::Type) -> Result, ErrorStack> { + pub fn fingerprint(&self, hash_type: MessageDigest) -> Result, ErrorStack> { unsafe { - let evp = hash_type.evp_md(); + let evp = hash_type.as_ptr(); let mut len = ffi::EVP_MAX_MD_SIZE; let mut buf = vec![0u8; len as usize]; try_ssl!(ffi::X509_digest(self.0, evp, buf.as_mut_ptr() as *mut _, &mut len)); diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index 07d9e1d4..afb06408 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -1,6 +1,6 @@ use serialize::hex::FromHex; -use crypto::hash::Type::SHA1; +use crypto::hash::MessageDigest; use crypto::pkey::PKey; use crypto::rsa::RSA; use x509::{X509, X509Generator}; @@ -14,7 +14,7 @@ fn get_generator() -> X509Generator { X509Generator::new() .set_valid_period(365 * 2) .add_name("CN".to_string(), "test_me".to_string()) - .set_sign_hash(SHA1) + .set_sign_hash(MessageDigest::sha1()) .add_extension(KeyUsage(vec![DigitalSignature, KeyEncipherment])) .add_extension(ExtKeyUsage(vec![ClientAuth, ServerAuth, @@ -83,7 +83,7 @@ fn test_req_gen() { fn test_cert_loading() { let cert = include_bytes!("../../test/cert.pem"); let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); - let fingerprint = cert.fingerprint(SHA1).unwrap(); + let fingerprint = cert.fingerprint(MessageDigest::sha1()).unwrap(); let hash_str = "59172d9313e84459bcff27f967e79e6e9217e584"; let hash_vec = hash_str.from_hex().unwrap(); From 1cecaeb62dc7e37b84e7a6758828a90bd6eb63b6 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 15 Oct 2016 15:47:40 -0700 Subject: [PATCH 043/186] De-enumify Cipher --- openssl/src/crypto/pkcs5.rs | 22 ++-- openssl/src/crypto/symm.rs | 199 ++++++++++++++++++++++++------------ 2 files changed, 142 insertions(+), 79 deletions(-) diff --git a/openssl/src/crypto/pkcs5.rs b/openssl/src/crypto/pkcs5.rs index 56ce3e26..9d348b89 100644 --- a/openssl/src/crypto/pkcs5.rs +++ b/openssl/src/crypto/pkcs5.rs @@ -3,7 +3,7 @@ use std::ptr; use ffi; use crypto::hash::MessageDigest; -use crypto::symm; +use crypto::symm::Cipher; use error::ErrorStack; #[derive(Clone, Eq, PartialEq, Hash, Debug)] @@ -22,8 +22,8 @@ pub struct KeyIvPair { /// /// New applications should not use this and instead use `pbkdf2_hmac_sha1` or /// another more modern key derivation algorithm. -pub fn evp_bytes_to_key_pbkdf1_compatible(typ: symm::Type, - message_digest_type: MessageDigest, +pub fn evp_bytes_to_key_pbkdf1_compatible(cipher: Cipher, + digest: MessageDigest, data: &[u8], salt: Option<&[u8]>, count: u32) @@ -39,11 +39,11 @@ pub fn evp_bytes_to_key_pbkdf1_compatible(typ: symm::Type, ffi::init(); - let typ = typ.as_ptr(); - let message_digest_type = message_digest_type.as_ptr(); + let cipher = cipher.as_ptr(); + let digest = digest.as_ptr(); - let len = ffi::EVP_BytesToKey(typ, - message_digest_type, + let len = ffi::EVP_BytesToKey(cipher, + digest, salt_ptr, data.as_ptr(), data.len() as c_int, @@ -57,8 +57,8 @@ pub fn evp_bytes_to_key_pbkdf1_compatible(typ: symm::Type, let mut key = vec![0; len as usize]; let mut iv = vec![0; len as usize]; - try_ssl!(ffi::EVP_BytesToKey(typ, - message_digest_type, + try_ssl!(ffi::EVP_BytesToKey(cipher, + digest, salt_ptr, data.as_ptr(), data.len() as c_int, @@ -117,7 +117,7 @@ pub fn pbkdf2_hmac(pass: &[u8], #[cfg(test)] mod tests { use crypto::hash::MessageDigest; - use crypto::symm; + use crypto::symm::Cipher; // Test vectors from // http://tools.ietf.org/html/draft-josefsson-pbkdf2-test-vectors-06 @@ -228,7 +228,7 @@ mod tests { 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8]; - assert_eq!(super::evp_bytes_to_key_pbkdf1_compatible(symm::Type::AES_256_CBC, + assert_eq!(super::evp_bytes_to_key_pbkdf1_compatible(Cipher::aes_256_cbc(), MessageDigest::sha1(), &data, Some(&salt), diff --git a/openssl/src/crypto/symm.rs b/openssl/src/crypto/symm.rs index 37754387..8ac6b7cf 100644 --- a/openssl/src/crypto/symm.rs +++ b/openssl/src/crypto/symm.rs @@ -11,57 +11,120 @@ pub enum Mode { Decrypt, } -#[allow(non_camel_case_types)] #[derive(Copy, Clone)] -pub enum Type { - AES_128_ECB, - AES_128_CBC, - AES_128_XTS, - AES_128_CTR, - AES_128_CFB1, - AES_128_CFB128, - AES_128_CFB8, - AES_256_ECB, - AES_256_CBC, - AES_256_XTS, - AES_256_CTR, - AES_256_CFB1, - AES_256_CFB128, - AES_256_CFB8, - DES_CBC, - DES_ECB, - RC4_128, -} +pub struct Cipher(*const ffi::EVP_CIPHER); -impl Type { - pub fn as_ptr(&self) -> *const ffi::EVP_CIPHER { +impl Cipher { + pub fn aes_128_ecb() -> Cipher { unsafe { - match *self { - Type::AES_128_ECB => ffi::EVP_aes_128_ecb(), - Type::AES_128_CBC => ffi::EVP_aes_128_cbc(), - Type::AES_128_XTS => ffi::EVP_aes_128_xts(), - Type::AES_128_CTR => ffi::EVP_aes_128_ctr(), - Type::AES_128_CFB1 => ffi::EVP_aes_128_cfb1(), - Type::AES_128_CFB128 => ffi::EVP_aes_128_cfb128(), - Type::AES_128_CFB8 => ffi::EVP_aes_128_cfb8(), - Type::AES_256_ECB => ffi::EVP_aes_256_ecb(), - Type::AES_256_CBC => ffi::EVP_aes_256_cbc(), - Type::AES_256_XTS => ffi::EVP_aes_256_xts(), - Type::AES_256_CTR => ffi::EVP_aes_256_ctr(), - Type::AES_256_CFB1 => ffi::EVP_aes_256_cfb1(), - Type::AES_256_CFB128 => ffi::EVP_aes_256_cfb128(), - Type::AES_256_CFB8 => ffi::EVP_aes_256_cfb8(), - Type::DES_CBC => ffi::EVP_des_cbc(), - Type::DES_ECB => ffi::EVP_des_ecb(), - Type::RC4_128 => ffi::EVP_rc4(), - } + Cipher(ffi::EVP_aes_128_ecb()) } } + pub fn aes_128_cbc() -> Cipher { + unsafe { + Cipher(ffi::EVP_aes_128_cbc()) + } + } + + pub fn aes_128_xts() -> Cipher { + unsafe { + Cipher(ffi::EVP_aes_128_xts()) + } + } + + pub fn aes_128_ctr() -> Cipher { + unsafe { + Cipher(ffi::EVP_aes_128_ctr()) + } + } + + pub fn aes_128_cfb1() -> Cipher { + unsafe { + Cipher(ffi::EVP_aes_128_cfb1()) + } + } + + pub fn aes_128_cfb128() -> Cipher { + unsafe { + Cipher(ffi::EVP_aes_128_cfb128()) + } + } + + pub fn aes_128_cfb8() -> Cipher { + unsafe { + Cipher(ffi::EVP_aes_128_cfb8()) + } + } + + pub fn aes_256_ecb() -> Cipher { + unsafe { + Cipher(ffi::EVP_aes_256_ecb()) + } + } + + pub fn aes_256_cbc() -> Cipher { + unsafe { + Cipher(ffi::EVP_aes_256_cbc()) + } + } + + pub fn aes_256_xts() -> Cipher { + unsafe { + Cipher(ffi::EVP_aes_256_xts()) + } + } + + pub fn aes_256_ctr() -> Cipher { + unsafe { + Cipher(ffi::EVP_aes_256_ctr()) + } + } + + pub fn aes_256_cfb1() -> Cipher { + unsafe { + Cipher(ffi::EVP_aes_256_cfb1()) + } + } + + pub fn aes_256_cfb128() -> Cipher { + unsafe { + Cipher(ffi::EVP_aes_256_cfb128()) + } + } + + pub fn aes_256_cfb8() -> Cipher { + unsafe { + Cipher(ffi::EVP_aes_256_cfb8()) + } + } + + pub fn des_cbc() -> Cipher { + unsafe { + Cipher(ffi::EVP_des_cbc()) + } + } + + pub fn des_ecb() -> Cipher { + unsafe { + Cipher(ffi::EVP_des_ecb()) + } + } + + pub fn rc4() -> Cipher { + unsafe { + Cipher(ffi::EVP_rc4()) + } + } + + pub fn as_ptr(&self) -> *const ffi::EVP_CIPHER { + self.0 + } + /// Returns the length of keys used with this cipher. pub fn key_len(&self) -> usize { unsafe { - EVP_CIPHER_key_length(self.as_ptr()) as usize + EVP_CIPHER_key_length(self.0) as usize } } @@ -69,7 +132,7 @@ impl Type { /// cipher does not use an IV. pub fn iv_len(&self) -> Option { unsafe { - let len = EVP_CIPHER_iv_length(self.as_ptr()) as usize; + let len = EVP_CIPHER_iv_length(self.0) as usize; if len == 0 { None } else { @@ -85,7 +148,7 @@ impl Type { /// Stream ciphers such as RC4 have a block size of 1. pub fn block_size(&self) -> usize { unsafe { - EVP_CIPHER_block_size(self.as_ptr()) as usize + EVP_CIPHER_block_size(self.0) as usize } } } @@ -102,8 +165,8 @@ impl Crypter { /// # Panics /// /// Panics if an IV is required by the cipher but not provided, or if the - /// IV's length does not match the expected length (see `Type::iv_len`). - pub fn new(t: Type, mode: Mode, key: &[u8], iv: Option<&[u8]>) -> Result { + /// IV's length does not match the expected length (see `Cipher::iv_len`). + pub fn new(t: Cipher, mode: Mode, key: &[u8], iv: Option<&[u8]>) -> Result { ffi::init(); unsafe { @@ -165,7 +228,7 @@ impl Crypter { /// # Panics /// /// Panics if `output.len() < input.len() + block_size` where - /// `block_size` is the block size of the cipher (see `Type::block_size`), + /// `block_size` is the block size of the cipher (see `Cipher::block_size`), /// or if `output.len() > c_int::max_value()`. pub fn update(&mut self, input: &[u8], output: &mut [u8]) -> Result { unsafe { @@ -218,7 +281,7 @@ impl Drop for Crypter { * Encrypts data, using the specified crypter type in encrypt mode with the * specified key and iv; returns the resulting (encrypted) data. */ -pub fn encrypt(t: Type, +pub fn encrypt(t: Cipher, key: &[u8], iv: Option<&[u8]>, data: &[u8]) @@ -230,7 +293,7 @@ pub fn encrypt(t: Type, * Decrypts data, using the specified crypter type in decrypt mode with the * specified key and iv; returns the resulting (decrypted) data. */ -pub fn decrypt(t: Type, +pub fn decrypt(t: Cipher, key: &[u8], iv: Option<&[u8]>, data: &[u8]) @@ -238,7 +301,7 @@ pub fn decrypt(t: Type, cipher(t, Mode::Decrypt, key, iv, data) } -fn cipher(t: Type, +fn cipher(t: Cipher, mode: Mode, key: &[u8], iv: Option<&[u8]>, @@ -292,23 +355,23 @@ mod tests { 0xaau8, 0xbbu8, 0xccu8, 0xddu8, 0xeeu8, 0xffu8]; let c0 = [0x8eu8, 0xa2u8, 0xb7u8, 0xcau8, 0x51u8, 0x67u8, 0x45u8, 0xbfu8, 0xeau8, 0xfcu8, 0x49u8, 0x90u8, 0x4bu8, 0x49u8, 0x60u8, 0x89u8]; - let mut c = super::Crypter::new(super::Type::AES_256_ECB, + let mut c = super::Crypter::new(super::Cipher::aes_256_ecb(), super::Mode::Encrypt, &k0, None).unwrap(); c.pad(false); - let mut r0 = vec![0; c0.len() + super::Type::AES_256_ECB.block_size()]; + let mut r0 = vec![0; c0.len() + super::Cipher::aes_256_ecb().block_size()]; let count = c.update(&p0, &mut r0).unwrap(); let rest = c.finalize(&mut r0[count..]).unwrap(); r0.truncate(count + rest); assert_eq!(r0.to_hex(), c0.to_hex()); - let mut c = super::Crypter::new(super::Type::AES_256_ECB, + let mut c = super::Crypter::new(super::Cipher::aes_256_ecb(), super::Mode::Decrypt, &k0, None).unwrap(); c.pad(false); - let mut p1 = vec![0; r0.len() + super::Type::AES_256_ECB.block_size()]; + let mut p1 = vec![0; r0.len() + super::Cipher::aes_256_ecb().block_size()]; let count = c.update(&r0, &mut p1).unwrap(); let rest = c.finalize(&mut p1[count..]).unwrap(); p1.truncate(count + rest); @@ -326,12 +389,12 @@ mod tests { let ciphered_data = [0x4a_u8, 0x2e_u8, 0xe5_u8, 0x6_u8, 0xbf_u8, 0xcf_u8, 0xf2_u8, 0xd7_u8, 0xea_u8, 0x2d_u8, 0xb1_u8, 0x85_u8, 0x6c_u8, 0x93_u8, 0x65_u8, 0x6f_u8]; - let mut cr = super::Crypter::new(super::Type::AES_256_CBC, + let mut cr = super::Crypter::new(super::Cipher::aes_256_cbc(), super::Mode::Decrypt, &data, Some(&iv)).unwrap(); cr.pad(false); - let mut unciphered_data = vec![0; data.len() + super::Type::AES_256_CBC.block_size()]; + let mut unciphered_data = vec![0; data.len() + super::Cipher::aes_256_cbc().block_size()]; let count = cr.update(&ciphered_data, &mut unciphered_data).unwrap(); let rest = cr.finalize(&mut unciphered_data[count..]).unwrap(); unciphered_data.truncate(count + rest); @@ -341,7 +404,7 @@ mod tests { assert_eq!(&unciphered_data, expected_unciphered_data); } - fn cipher_test(ciphertype: super::Type, pt: &str, ct: &str, key: &str, iv: &str) { + fn cipher_test(ciphertype: super::Cipher, pt: &str, ct: &str, key: &str, iv: &str) { use serialize::hex::ToHex; let pt = pt.from_hex().unwrap(); @@ -372,7 +435,7 @@ mod tests { let key = "97CD440324DA5FD1F7955C1C13B6B466"; let iv = ""; - cipher_test(super::Type::RC4_128, pt, ct, key, iv); + cipher_test(super::Cipher::rc4(), pt, ct, key, iv); } #[test] @@ -387,7 +450,7 @@ mod tests { 4180026ad640b74243b3133e7b9fae629403f6733423dae28"; let iv = "db200efb7eaaa737dbdf40babb68953f"; - cipher_test(super::Type::AES_256_XTS, pt, ct, key, iv); + cipher_test(super::Cipher::aes_256_xts(), pt, ct, key, iv); } #[test] @@ -400,7 +463,7 @@ mod tests { let key = "2B7E151628AED2A6ABF7158809CF4F3C"; let iv = "F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF"; - cipher_test(super::Type::AES_128_CTR, pt, ct, key, iv); + cipher_test(super::Cipher::aes_128_ctr(), pt, ct, key, iv); } #[test] @@ -412,7 +475,7 @@ mod tests { let key = "2b7e151628aed2a6abf7158809cf4f3c"; let iv = "000102030405060708090a0b0c0d0e0f"; - cipher_test(super::Type::AES_128_CFB1, pt, ct, key, iv); + cipher_test(super::Cipher::aes_128_cfb1(), pt, ct, key, iv); } #[test] @@ -423,7 +486,7 @@ mod tests { let key = "2b7e151628aed2a6abf7158809cf4f3c"; let iv = "000102030405060708090a0b0c0d0e0f"; - cipher_test(super::Type::AES_128_CFB128, pt, ct, key, iv); + cipher_test(super::Cipher::aes_128_cfb128(), pt, ct, key, iv); } #[test] @@ -434,7 +497,7 @@ mod tests { let key = "2b7e151628aed2a6abf7158809cf4f3c"; let iv = "000102030405060708090a0b0c0d0e0f"; - cipher_test(super::Type::AES_128_CFB8, pt, ct, key, iv); + cipher_test(super::Cipher::aes_128_cfb8(), pt, ct, key, iv); } #[test] @@ -445,7 +508,7 @@ mod tests { let key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; let iv = "000102030405060708090a0b0c0d0e0f"; - cipher_test(super::Type::AES_256_CFB1, pt, ct, key, iv); + cipher_test(super::Cipher::aes_256_cfb1(), pt, ct, key, iv); } #[test] @@ -456,7 +519,7 @@ mod tests { let key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; let iv = "000102030405060708090a0b0c0d0e0f"; - cipher_test(super::Type::AES_256_CFB128, pt, ct, key, iv); + cipher_test(super::Cipher::aes_256_cfb128(), pt, ct, key, iv); } #[test] @@ -467,7 +530,7 @@ mod tests { let key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; let iv = "000102030405060708090a0b0c0d0e0f"; - cipher_test(super::Type::AES_256_CFB8, pt, ct, key, iv); + cipher_test(super::Cipher::aes_256_cfb8(), pt, ct, key, iv); } #[test] @@ -478,7 +541,7 @@ mod tests { let key = "7cb66337f3d3c0fe"; let iv = "0001020304050607"; - cipher_test(super::Type::DES_CBC, pt, ct, key, iv); + cipher_test(super::Cipher::des_cbc(), pt, ct, key, iv); } #[test] @@ -489,6 +552,6 @@ mod tests { let key = "7cb66337f3d3c0fe"; let iv = "0001020304050607"; - cipher_test(super::Type::DES_ECB, pt, ct, key, iv); + cipher_test(super::Cipher::des_ecb(), pt, ct, key, iv); } } From ee189885843b2b4f75f180ccc5b66689c3cdd553 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 15 Oct 2016 16:10:03 -0700 Subject: [PATCH 044/186] De-enumify SslMethod --- openssl/src/dh/mod.rs | 9 ++-- openssl/src/ssl/mod.rs | 73 +++++++++++++++++++------------ openssl/src/ssl/tests/mod.rs | 83 +++++++++++++++++------------------- 3 files changed, 88 insertions(+), 77 deletions(-) diff --git a/openssl/src/dh/mod.rs b/openssl/src/dh/mod.rs index b716ffe0..83807f39 100644 --- a/openssl/src/dh/mod.rs +++ b/openssl/src/dh/mod.rs @@ -88,13 +88,12 @@ mod compat { mod tests { use super::DH; use bn::BigNum; - use ssl::SslContext; - use ssl::SslMethod::Tls; + use ssl::{SslMethod, SslContext}; #[test] #[cfg(feature = "openssl-102")] fn test_dh_rfc5114() { - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); let dh1 = DH::get_1024_160().unwrap(); ctx.set_tmp_dh(&dh1).unwrap(); let dh2 = DH::get_2048_224().unwrap(); @@ -105,7 +104,7 @@ mod tests { #[test] fn test_dh() { - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); let p = BigNum::from_hex_str("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435\ E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF429\ 6D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C02\ @@ -135,7 +134,7 @@ mod tests { #[test] fn test_dh_from_pem() { - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); let params = include_bytes!("../../test/dhparams.pem"); let dh = DH::from_pem(params).ok().expect("Failed to load PEM"); ctx.set_tmp_dh(&dh).unwrap(); diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 076ac400..73ff0b47 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -76,13 +76,29 @@ bitflags! { } } -/// Determines the SSL method supported -#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] -pub enum SslMethod { - /// Support the TLS protocol - Tls, - /// Support DTLS protocol - Dtls, +#[derive(Copy, Clone)] +pub struct SslMethod(*const ffi::SSL_METHOD); + +impl SslMethod { + /// Support all versions of the TLS protocol. + /// + /// This corresponds to `TLS_method` on OpenSSL 1.1.0 and `SSLv23_method` + /// on OpenSSL 1.0.x. + pub fn tls() -> SslMethod { + SslMethod(compat::tls_method()) + } + + /// Support all versions of the DTLS protocol. + /// + /// This corresponds to `DTLS_method` on OpenSSL 1.1.0 and `DTLSv1_method` + /// on OpenSSL 1.0.x. + pub fn dtls() -> SslMethod { + SslMethod(compat::dtls_method()) + } + + pub fn as_ptr(&self) -> *const ffi::SSL_METHOD { + self.0 + } } /// Determines the type of certificate verification used @@ -653,15 +669,10 @@ impl SslContext { init(); let mut ctx = unsafe { - let method = compat::get_method(method); - let ctx = try_ssl_null!(ffi::SSL_CTX_new(method)); + let ctx = try_ssl_null!(ffi::SSL_CTX_new(method.as_ptr())); SslContext::from_ptr(ctx) }; - match method { - SslMethod::Dtls => ctx.set_read_ahead(1), - _ => {} - } // this is a bit dubious (?) try!(ctx.set_mode(ffi::SSL_MODE_AUTO_RETRY | ffi::SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)); @@ -1374,8 +1385,6 @@ mod compat { pub use ffi::{SSL_CTX_get_options, SSL_CTX_set_options}; pub use ffi::{SSL_CTX_clear_options, SSL_CTX_up_ref}; - use super::SslMethod; - pub unsafe fn get_new_idx(f: ffi::CRYPTO_EX_free) -> c_int { ffi::CRYPTO_get_ex_new_index(ffi::CRYPTO_EX_INDEX_SSL_CTX, 0, @@ -1394,10 +1403,15 @@ mod compat { Some(f)) } - pub unsafe fn get_method(method: SslMethod) -> *const ffi::SSL_METHOD { - match method { - SslMethod::Tls => ffi::TLS_method(), - SslMethod::Dtls => ffi::DTLS_method(), + pub fn tls_method() -> *const ffi::SSL_METHOD { + unsafe { + ffi::TLS_method() + } + } + + pub fn dtls_method() -> *const ffi::SSL_METHOD { + unsafe { + ffi::DTLS_method() } } } @@ -1410,8 +1424,6 @@ mod compat { use ffi; use libc::{self, c_long, c_ulong, c_int}; - use super::SslMethod; - pub unsafe fn SSL_CTX_get_options(ctx: *const ffi::SSL_CTX) -> c_ulong { ffi::SSL_CTX_ctrl(ctx as *mut _, ffi::SSL_CTRL_OPTIONS, @@ -1451,13 +1463,6 @@ mod compat { Some(f)) } - pub unsafe fn get_method(method: SslMethod) -> *const ffi::SSL_METHOD { - match method { - SslMethod::Tls => ffi::SSLv23_method(), - SslMethod::Dtls => ffi::DTLSv1_method(), - } - } - pub unsafe fn SSL_CTX_up_ref(ssl: *mut ffi::SSL_CTX) -> libc::c_int { ffi::CRYPTO_add_lock(&mut (*ssl).references, 1, @@ -1466,4 +1471,16 @@ mod compat { line!() as libc::c_int); 0 } + + pub fn tls_method() -> *const ffi::SSL_METHOD { + unsafe { + ffi::SSLv23_method() + } + } + + pub fn dtls_method() -> *const ffi::SSL_METHOD { + unsafe { + ffi::DTLSv1_method() + } + } } diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 284f5c78..ac7505f8 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -17,7 +17,6 @@ use tempdir::TempDir; use crypto::hash::MessageDigest; use ssl; use ssl::SSL_VERIFY_PEER; -use ssl::SslMethod::Tls; use ssl::{SslMethod, HandshakeError}; use ssl::error::Error; use ssl::{SslContext, SslStream}; @@ -31,7 +30,6 @@ use x509::verify::X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS; use crypto::pkey::PKey; use std::net::UdpSocket; -use ssl::SslMethod::Dtls; mod select; @@ -179,14 +177,14 @@ macro_rules! run_test( #[test] fn sslv23() { let (_s, stream) = Server::new(); - $blk(SslMethod::Tls, stream); + $blk(SslMethod::tls(), stream); } #[test] #[cfg_attr(any(windows, target_arch = "arm"), ignore)] // FIXME(#467) fn dtlsv1() { let (_s, stream) = Server::new_dtlsv1(Some("hello")); - $blk(SslMethod::Dtls, stream); + $blk(SslMethod::dtls(), stream); } } ); @@ -364,7 +362,7 @@ fn test_write_hits_stream() { let addr = listener.local_addr().unwrap(); let guard = thread::spawn(move || { - let ctx = SslContext::new(Tls).unwrap(); + let ctx = SslContext::new(SslMethod::tls()).unwrap(); let stream = TcpStream::connect(addr).unwrap(); let mut stream = SslStream::connect(&ctx, stream).unwrap(); @@ -372,7 +370,7 @@ fn test_write_hits_stream() { stream }); - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM).unwrap(); ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM).unwrap(); @@ -392,7 +390,7 @@ fn test_set_certificate_and_private_key() { let cert = include_bytes!("../../../test/cert.pem"); let cert = X509::from_pem(cert).unwrap(); - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_private_key(&key).unwrap(); ctx.set_certificate(&cert).unwrap(); @@ -420,7 +418,7 @@ run_test!(clear_ctx_options, |method, _| { #[test] fn test_write() { let (_s, stream) = Server::new(); - let mut stream = SslStream::connect(&SslContext::new(Tls).unwrap(), stream).unwrap(); + let mut stream = SslStream::connect(&SslContext::new(SslMethod::tls()).unwrap(), stream).unwrap(); stream.write_all("hello".as_bytes()).unwrap(); stream.flush().unwrap(); stream.write_all(" there".as_bytes()).unwrap(); @@ -430,7 +428,7 @@ fn test_write() { #[test] fn test_write_direct() { let (_s, stream) = Server::new(); - let mut stream = SslStream::connect(&SslContext::new(Tls).unwrap(), stream).unwrap(); + let mut stream = SslStream::connect(&SslContext::new(SslMethod::tls()).unwrap(), stream).unwrap(); stream.write_all("hello".as_bytes()).unwrap(); stream.flush().unwrap(); stream.write_all(" there".as_bytes()).unwrap(); @@ -451,7 +449,7 @@ run_test!(get_peer_certificate, |method, stream| { fn test_write_dtlsv1() { let (_s, stream) = Server::new_dtlsv1(iter::repeat("y\n")); - let mut stream = SslStream::connect(&SslContext::new(Dtls).unwrap(), stream).unwrap(); + let mut stream = SslStream::connect(&SslContext::new(SslMethod::dtls()).unwrap(), stream).unwrap(); stream.write_all(b"hello").unwrap(); stream.flush().unwrap(); stream.write_all(b" there").unwrap(); @@ -461,7 +459,7 @@ fn test_write_dtlsv1() { #[test] fn test_read() { let (_s, tcp) = Server::new(); - let mut stream = SslStream::connect(&SslContext::new(Tls).unwrap(), tcp).unwrap(); + let mut stream = SslStream::connect(&SslContext::new(SslMethod::tls()).unwrap(), tcp).unwrap(); stream.write_all("GET /\r\n\r\n".as_bytes()).unwrap(); stream.flush().unwrap(); io::copy(&mut stream, &mut io::sink()).ok().expect("read error"); @@ -470,7 +468,7 @@ fn test_read() { #[test] fn test_read_direct() { let (_s, tcp) = Server::new(); - let mut stream = SslStream::connect(&SslContext::new(Tls).unwrap(), tcp).unwrap(); + let mut stream = SslStream::connect(&SslContext::new(SslMethod::tls()).unwrap(), tcp).unwrap(); stream.write_all("GET /\r\n\r\n".as_bytes()).unwrap(); stream.flush().unwrap(); io::copy(&mut stream, &mut io::sink()).ok().expect("read error"); @@ -479,7 +477,7 @@ fn test_read_direct() { #[test] fn test_pending() { let (_s, tcp) = Server::new(); - let mut stream = SslStream::connect(&SslContext::new(Tls).unwrap(), tcp).unwrap(); + let mut stream = SslStream::connect(&SslContext::new(SslMethod::tls()).unwrap(), tcp).unwrap(); stream.write_all("GET /\r\n\r\n".as_bytes()).unwrap(); stream.flush().unwrap(); @@ -502,7 +500,7 @@ fn test_pending() { #[test] fn test_state() { let (_s, tcp) = Server::new(); - let stream = SslStream::connect(&SslContext::new(Tls).unwrap(), tcp).unwrap(); + let stream = SslStream::connect(&SslContext::new(SslMethod::tls()).unwrap(), tcp).unwrap(); assert_eq!(stream.ssl().state_string(), "SSLOK "); assert_eq!(stream.ssl().state_string_long(), "SSL negotiation finished successfully"); @@ -514,7 +512,7 @@ fn test_state() { #[cfg(feature = "openssl-102")] fn test_connect_with_unilateral_alpn() { let (_s, stream) = Server::new(); - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -535,7 +533,7 @@ fn test_connect_with_unilateral_alpn() { #[test] fn test_connect_with_unilateral_npn() { let (_s, stream) = Server::new(); - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -557,7 +555,7 @@ fn test_connect_with_unilateral_npn() { #[cfg(feature = "openssl-102")] fn test_connect_with_alpn_successful_multiple_matching() { let (_s, stream) = Server::new_alpn(); - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"spdy/3.1", b"http/1.1"]); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -579,7 +577,7 @@ fn test_connect_with_alpn_successful_multiple_matching() { #[cfg(feature = "openssl-102")] fn test_connect_with_npn_successful_multiple_matching() { let (_s, stream) = Server::new_alpn(); - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"spdy/3.1", b"http/1.1"]); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -602,7 +600,7 @@ fn test_connect_with_npn_successful_multiple_matching() { #[cfg(feature = "openssl-102")] fn test_connect_with_alpn_successful_single_match() { let (_s, stream) = Server::new_alpn(); - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"spdy/3.1"]); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -626,7 +624,7 @@ fn test_connect_with_alpn_successful_single_match() { #[cfg(feature = "openssl-102")] fn test_connect_with_npn_successful_single_match() { let (_s, stream) = Server::new_alpn(); - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"spdy/3.1"]); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -650,7 +648,7 @@ fn test_npn_server_advertise_multiple() { let localhost = listener.local_addr().unwrap(); // We create a different context instance for the server... let listener_ctx = { - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]); assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) @@ -665,7 +663,7 @@ fn test_npn_server_advertise_multiple() { let _ = SslStream::accept(&listener_ctx, stream).unwrap(); }); - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"spdy/3.1"]); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -691,7 +689,7 @@ fn test_alpn_server_advertise_multiple() { let localhost = listener.local_addr().unwrap(); // We create a different context instance for the server... let listener_ctx = { - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]); assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) @@ -706,7 +704,7 @@ fn test_alpn_server_advertise_multiple() { let _ = SslStream::accept(&listener_ctx, stream).unwrap(); }); - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"spdy/3.1"]); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -732,7 +730,7 @@ fn test_alpn_server_select_none() { let localhost = listener.local_addr().unwrap(); // We create a different context instance for the server... let listener_ctx = { - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]); assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) @@ -747,7 +745,7 @@ fn test_alpn_server_select_none() { let _ = SslStream::accept(&listener_ctx, stream).unwrap(); }); - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/2"]); ctx.set_CA_file(&Path::new("test/root-ca.pem")).unwrap(); @@ -767,7 +765,7 @@ fn test_alpn_server_select_none() { let localhost = listener.local_addr().unwrap(); // We create a different context instance for the server... let listener_ctx = { - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]); assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) @@ -782,7 +780,7 @@ fn test_alpn_server_select_none() { assert!(SslStream::accept(&listener_ctx, stream).is_err()); }); - let mut ctx = SslContext::new(Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/2"]); ctx.set_CA_file(&Path::new("test/root-ca.pem")).unwrap(); @@ -799,16 +797,13 @@ mod dtlsv1 { use crypto::hash::MessageDigest; use ssl::SslMethod; - use ssl::SslMethod::Dtls; use ssl::{SslContext, SslStream}; use ssl::SSL_VERIFY_PEER; use x509::X509StoreContext; - const PROTOCOL: SslMethod = Dtls; - #[test] fn test_new_ctx() { - SslContext::new(PROTOCOL).unwrap(); + SslContext::new(SslMethod::dtls()).unwrap(); } } @@ -817,7 +812,7 @@ mod dtlsv1 { fn test_read_dtlsv1() { let (_s, stream) = Server::new_dtlsv1(Some("hello")); - let mut stream = SslStream::connect(&SslContext::new(Dtls).unwrap(), stream).unwrap(); + let mut stream = SslStream::connect(&SslContext::new(SslMethod::dtls()).unwrap(), stream).unwrap(); let mut buf = [0u8; 100]; assert!(stream.read(&mut buf).is_ok()); } @@ -857,7 +852,7 @@ fn handshake(res: Result, HandshakeError>) fn test_write_nonblocking() { let (_s, stream) = Server::new(); stream.set_nonblocking(true).unwrap(); - let cx = SslContext::new(Tls).unwrap(); + let cx = SslContext::new(SslMethod::tls()).unwrap(); let mut stream = handshake(SslStream::connect(&cx, stream)); let mut iterations = 0; @@ -895,7 +890,7 @@ fn test_write_nonblocking() { fn test_read_nonblocking() { let (_s, stream) = Server::new(); stream.set_nonblocking(true).unwrap(); - let cx = SslContext::new(Tls).unwrap(); + let cx = SslContext::new(SslMethod::tls()).unwrap(); let mut stream = handshake(SslStream::connect(&cx, stream)); let mut iterations = 0; @@ -969,7 +964,7 @@ fn write_panic() { let (_s, stream) = Server::new(); let stream = ExplodingStream(stream); - let ctx = SslContext::new(SslMethod::Tls).unwrap(); + let ctx = SslContext::new(SslMethod::tls()).unwrap(); let _ = SslStream::connect(&ctx, stream); } @@ -997,7 +992,7 @@ fn read_panic() { let (_s, stream) = Server::new(); let stream = ExplodingStream(stream); - let ctx = SslContext::new(SslMethod::Tls).unwrap(); + let ctx = SslContext::new(SslMethod::tls()).unwrap(); let _ = SslStream::connect(&ctx, stream); } @@ -1025,7 +1020,7 @@ fn flush_panic() { let (_s, stream) = Server::new(); let stream = ExplodingStream(stream); - let ctx = SslContext::new(SslMethod::Tls).unwrap(); + let ctx = SslContext::new(SslMethod::tls()).unwrap(); let mut stream = SslStream::connect(&ctx, stream).ok().unwrap(); let _ = stream.flush(); } @@ -1033,12 +1028,12 @@ fn flush_panic() { #[test] fn refcount_ssl_context() { let mut ssl = { - let ctx = SslContext::new(SslMethod::Tls).unwrap(); + let ctx = SslContext::new(SslMethod::tls()).unwrap(); ssl::Ssl::new(&ctx).unwrap() }; { - let new_ctx_a = SslContext::new(SslMethod::Tls).unwrap(); + let new_ctx_a = SslContext::new(SslMethod::tls()).unwrap(); let _new_ctx_b = ssl.set_ssl_context(&new_ctx_a); } } @@ -1046,7 +1041,7 @@ fn refcount_ssl_context() { #[test] #[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( fn default_verify_paths() { - let mut ctx = SslContext::new(SslMethod::Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_default_verify_paths().unwrap(); ctx.set_verify(SSL_VERIFY_PEER); let s = TcpStream::connect("google.com:443").unwrap(); @@ -1065,7 +1060,7 @@ fn default_verify_paths() { fn add_extra_chain_cert() { let cert = include_bytes!("../../../test/cert.pem"); let cert = X509::from_pem(cert).unwrap(); - let mut ctx = SslContext::new(SslMethod::Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.add_extra_chain_cert(&cert).unwrap(); } @@ -1073,7 +1068,7 @@ fn add_extra_chain_cert() { #[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( #[cfg(feature = "openssl-102")] fn valid_hostname() { - let mut ctx = SslContext::new(SslMethod::Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_default_verify_paths().unwrap(); ctx.set_verify(SSL_VERIFY_PEER); @@ -1097,7 +1092,7 @@ fn valid_hostname() { #[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( #[cfg(feature = "openssl-102")] fn invalid_hostname() { - let mut ctx = SslContext::new(SslMethod::Tls).unwrap(); + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_default_verify_paths().unwrap(); ctx.set_verify(SSL_VERIFY_PEER); From 4ba5292a0a421d35675f1b43ba2551eb7b16b343 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 15 Oct 2016 16:19:19 -0700 Subject: [PATCH 045/186] De-enumify Padding --- openssl/src/crypto/rsa.rs | 46 +++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index eebb9622..1212ee3a 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -11,19 +11,19 @@ use crypto::util::{CallbackState, invoke_passwd_cb}; /// Type of encryption padding to use. #[derive(Copy, Clone)] -pub enum Padding { - None, - OAEP, - PKCS1v15 -} +pub struct Padding(c_int); impl Padding { - fn openssl_padding_code(&self) -> c_int { - match *self { - Padding::None => ffi::RSA_NO_PADDING, - Padding::OAEP => ffi::RSA_PKCS1_OAEP_PADDING, - Padding::PKCS1v15 => ffi::RSA_PKCS1_PADDING - } + pub fn none() -> Padding { + Padding(ffi::RSA_NO_PADDING) + } + + pub fn pkcs1() -> Padding { + Padding(ffi::RSA_PKCS1_PADDING) + } + + pub fn pkcs1_oaep() -> Padding { + Padding(ffi::RSA_PKCS1_OAEP_PADDING) } } @@ -183,7 +183,7 @@ impl RSA { from.as_ptr(), to.as_mut_ptr(), self.0, - padding.openssl_padding_code())); + padding.0)); to.truncate(enc_len as usize); Ok(to) } @@ -202,7 +202,7 @@ impl RSA { from.as_ptr(), to.as_mut_ptr(), self.0, - padding.openssl_padding_code())); + padding.0)); assert!(enc_len as u32 == k_len); Ok(to) @@ -221,7 +221,7 @@ impl RSA { from.as_ptr(), to.as_mut_ptr(), self.0, - padding.openssl_padding_code())); + padding.0)); to.truncate(enc_len as usize); Ok(to) } @@ -239,7 +239,7 @@ impl RSA { from.as_ptr(), to.as_mut_ptr(), self.0, - padding.openssl_padding_code())); + padding.0)); assert!(enc_len as u32 == k_len); Ok(to) @@ -425,13 +425,13 @@ mod test { let public_key = RSA::public_key_from_pem(key).unwrap(); let original_data: Vec = "This is test".to_string().into_bytes(); - let result = public_key.public_encrypt(&original_data, Padding::PKCS1v15).unwrap(); + let result = public_key.public_encrypt(&original_data, Padding::pkcs1()).unwrap(); assert_eq!(result.len(), 256); let pkey = include_bytes!("../../test/rsa.pem"); let private_key = RSA::private_key_from_pem(pkey).unwrap(); - let dec_result = private_key.private_decrypt(&result, Padding::PKCS1v15).unwrap(); + let dec_result = private_key.private_decrypt(&result, Padding::pkcs1()).unwrap(); assert_eq!(dec_result, original_data); } @@ -444,8 +444,8 @@ mod test { let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); - let emsg = k0.private_encrypt(&msg, Padding::PKCS1v15).unwrap(); - let dmsg = k1.public_decrypt(&emsg, Padding::PKCS1v15).unwrap(); + let emsg = k0.private_encrypt(&msg, Padding::pkcs1()).unwrap(); + let dmsg = k1.public_decrypt(&emsg, Padding::pkcs1()).unwrap(); assert!(msg == dmsg); } @@ -457,8 +457,8 @@ mod test { let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); - let emsg = k1.public_encrypt(&msg, Padding::OAEP).unwrap(); - let dmsg = k0.private_decrypt(&emsg, Padding::OAEP).unwrap(); + let emsg = k1.public_encrypt(&msg, Padding::pkcs1_oaep()).unwrap(); + let dmsg = k0.private_decrypt(&emsg, Padding::pkcs1_oaep()).unwrap(); assert!(msg == dmsg); } @@ -470,8 +470,8 @@ mod test { let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); - let emsg = k1.public_encrypt(&msg, super::Padding::PKCS1v15).unwrap(); - let dmsg = k0.private_decrypt(&emsg, super::Padding::PKCS1v15).unwrap(); + let emsg = k1.public_encrypt(&msg, super::Padding::pkcs1()).unwrap(); + let dmsg = k0.private_decrypt(&emsg, super::Padding::pkcs1()).unwrap(); assert!(msg == dmsg); } From 872fcfc3d509b807b1bbb4d818fa28448085a58e Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 15 Oct 2016 16:51:29 -0700 Subject: [PATCH 046/186] Always build updated OpenSSL Trusty's default OpenSSL seems to have a bug with DTLS if read_ahead isn't enabled, even though that's not supposed to do anything for DTLS (!?!). --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 347a23c5..55ba716d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,6 +6,7 @@ dist: trusty env: global: - TARGET=x86_64-unknown-linux-gnu + - BUILD_OPENSSL_VERSION=1.0.1u matrix: include: # ARM-bit version compat @@ -44,7 +45,6 @@ matrix: - rust: nightly # 64-bit version compat - - env: BUILD_OPENSSL_VERSION=1.0.1u - env: BUILD_OPENSSL_VERSION=1.0.2h - env: BUILD_OPENSSL_VERSION=1.1.0b From 6ea551dc822ed9d32332662e0c7afae1aebf86c0 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 15 Oct 2016 16:53:10 -0700 Subject: [PATCH 047/186] Fix set_read_ahead signature --- openssl/src/ssl/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 73ff0b47..7b4f831b 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -407,9 +407,9 @@ impl<'a> SslContextRef<'a> { } } - pub fn set_read_ahead(&mut self, m: u32) { + pub fn set_read_ahead(&mut self, read_ahead: bool) { unsafe { - ffi::SSL_CTX_set_read_ahead(self.as_ptr(), m as c_long); + ffi::SSL_CTX_set_read_ahead(self.as_ptr(), read_ahead as c_long); } } From 8f89f0bfa98ac69582f22244dae0f5cc923046e1 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 16 Oct 2016 15:54:09 -0700 Subject: [PATCH 048/186] Start on error + BN refactor --- openssl/src/{asn1/mod.rs => asn1.rs} | 9 +- openssl/src/{bn/mod.rs => bn.rs} | 386 ++++++++++++--------------- openssl/src/{dh/mod.rs => dh.rs} | 2 +- openssl/src/lib.rs | 28 ++ 4 files changed, 210 insertions(+), 215 deletions(-) rename openssl/src/{asn1/mod.rs => asn1.rs} (91%) rename openssl/src/{bn/mod.rs => bn.rs} (74%) rename openssl/src/{dh/mod.rs => dh.rs} (98%) diff --git a/openssl/src/asn1/mod.rs b/openssl/src/asn1.rs similarity index 91% rename from openssl/src/asn1/mod.rs rename to openssl/src/asn1.rs index 1eab9f04..91f920a3 100644 --- a/openssl/src/asn1/mod.rs +++ b/openssl/src/asn1.rs @@ -2,9 +2,10 @@ use libc::c_long; use std::{ptr, fmt}; use std::marker::PhantomData; use std::ops::Deref; - -use bio::MemBio; use ffi; + +use {cvt, cvt_p}; +use bio::MemBio; use error::ErrorStack; /// Corresponds to the ASN.1 structure Time defined in RFC5280 @@ -20,7 +21,7 @@ impl Asn1Time { ffi::init(); unsafe { - let handle = try_ssl_null!(ffi::X509_gmtime_adj(ptr::null_mut(), period)); + let handle = try!(cvt_p(ffi::X509_gmtime_adj(ptr::null_mut(), period))); Ok(Asn1Time::from_ptr(handle)) } } @@ -58,7 +59,7 @@ impl<'a> fmt::Display for Asn1TimeRef<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mem_bio = try!(MemBio::new()); let as_str = unsafe { - try_ssl!(ffi::ASN1_TIME_print(mem_bio.as_ptr(), self.0)); + try!(cvt(ffi::ASN1_TIME_print(mem_bio.as_ptr(), self.0))); String::from_utf8_unchecked(mem_bio.get_buf().to_owned()) }; write!(f, "{}", as_str) diff --git a/openssl/src/bn/mod.rs b/openssl/src/bn.rs similarity index 74% rename from openssl/src/bn/mod.rs rename to openssl/src/bn.rs index 7d1f5458..22924e67 100644 --- a/openssl/src/bn/mod.rs +++ b/openssl/src/bn.rs @@ -1,11 +1,12 @@ +use ffi; use libc::{c_int, c_void}; -use std::ffi::{CStr, CString}; use std::cmp::Ordering; +use std::ffi::{CStr, CString}; use std::{fmt, ptr}; use std::marker::PhantomData; use std::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub, Deref, DerefMut}; -use ffi; +use {cvt, cvt_p, cvt_n}; use error::ErrorStack; /// Specifies the desired properties of a randomly generated `BigNum`. @@ -74,199 +75,141 @@ macro_rules! with_bn_in_ctx( }); ); -/// A borrowed, signed, arbitrary-precision integer. -#[derive(Copy, Clone)] -pub struct BigNumRef<'a>(*mut ffi::BIGNUM, PhantomData<&'a ()>); +/// A context object for `BigNum` operations. +pub struct BnCtx(*mut ffi::BN_CTX); - -impl<'a> BigNumRef<'a> { - pub unsafe fn from_ptr(handle: *mut ffi::BIGNUM) -> BigNumRef<'a> { - BigNumRef(handle, PhantomData) - } - - /// Returns the square of `self`. - /// - /// ``` - /// # use openssl::bn::BigNum; - /// let ref n = BigNum::new_from(10).unwrap(); - /// let squared = BigNum::new_from(100).unwrap(); - /// - /// assert_eq!(n.checked_sqr().unwrap(), squared); - /// assert_eq!(n * n, squared); - /// ``` - pub fn checked_sqr(&self) -> Result { +impl Drop for BnCtx { + fn drop(&mut self) { unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_sqr(r.as_ptr(), self.as_ptr(), ctx) == 1 - }) + ffi::BN_CTX_free(self.0); + } + } +} + +impl BnCtx { + /// Returns a new `BnCtx`. + pub fn new() -> Result { + unsafe { + cvt_p(ffi::BN_CTX_new()).map(BnCtx) } } - /// Returns the unsigned remainder of the division `self / n`. - pub fn checked_nnmod(&self, n: &BigNumRef) -> Result { + /// Places the result of `a²` in `r`. + pub fn sqr(&mut self, r: &mut BigNumRef, a: &BigNumRef) -> Result<(), ErrorStack> { unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_nnmod(r.as_ptr(), self.as_ptr(), n.as_ptr(), ctx) == 1 - }) + cvt(ffi::BN_sqr(r.as_ptr(), a.as_ptr(), self.0)).map(|_| ()) } } - /// Equivalent to `(self + a) mod n`. - /// - /// ``` - /// # use openssl::bn::BigNum; - /// let ref s = BigNum::new_from(10).unwrap(); - /// let ref a = BigNum::new_from(20).unwrap(); - /// let ref n = BigNum::new_from(29).unwrap(); - /// let result = BigNum::new_from(1).unwrap(); - /// - /// assert_eq!(s.checked_mod_add(a, n).unwrap(), result); - /// ``` - pub fn checked_mod_add(&self, a: &BigNumRef, n: &BigNumRef) -> Result { + /// Places the result of `a mod m` in `r`. + pub fn nnmod(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + m: &BigNumRef) -> Result<(), ErrorStack> { unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_mod_add(r.as_ptr(), self.as_ptr(), a.as_ptr(), n.as_ptr(), ctx) == 1 - }) + cvt(ffi::BN_nnmod(r.as_ptr(), a.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) } } - /// Equivalent to `(self - a) mod n`. - pub fn checked_mod_sub(&self, a: &BigNumRef, n: &BigNumRef) -> Result { + /// Places the result of `(a + b) mod m` in `r`. + pub fn mod_add(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + b: &BigNumRef, + m: &BigNumRef) + -> Result<(), ErrorStack> { unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_mod_sub(r.as_ptr(), self.as_ptr(), a.as_ptr(), n.as_ptr(), ctx) == 1 - }) + cvt(ffi::BN_mod_add(r.as_ptr(), a.as_ptr(), b.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) } } - /// Equivalent to `(self * a) mod n`. - pub fn checked_mod_mul(&self, a: &BigNumRef, n: &BigNumRef) -> Result { + /// Places the result of `(a - b) mod m` in `r`. + pub fn mod_sub(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + b: &BigNumRef, + m: &BigNumRef) + -> Result<(), ErrorStack> { unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_mod_mul(r.as_ptr(), self.as_ptr(), a.as_ptr(), n.as_ptr(), ctx) == 1 - }) + cvt(ffi::BN_mod_sub(r.as_ptr(), a.as_ptr(), b.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) } } - /// Equivalent to `self² mod n`. - pub fn checked_mod_sqr(&self, n: &BigNumRef) -> Result { + /// Places the result of `(a * b) mod m` in `r`. + pub fn mod_mul(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + b: &BigNumRef, + m: &BigNumRef) + -> Result<(), ErrorStack> { unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_mod_sqr(r.as_ptr(), self.as_ptr(), n.as_ptr(), ctx) == 1 - }) + cvt(ffi::BN_mod_mul(r.as_ptr(), a.as_ptr(), b.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) } } - /// Raises `self` to the `p`th power. - pub fn checked_exp(&self, p: &BigNumRef) -> Result { + /// Places the result of `a² mod m` in `r`. + pub fn mod_sqr(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + m: &BigNumRef) -> Result<(), ErrorStack> { unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_exp(r.as_ptr(), self.as_ptr(), p.as_ptr(), ctx) == 1 - }) + cvt(ffi::BN_mod_sqr(r.as_ptr(), a.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) } } - /// Equivalent to `self.checked_exp(p) mod n`. - pub fn checked_mod_exp(&self, p: &BigNumRef, n: &BigNumRef) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_mod_exp(r.as_ptr(), self.as_ptr(), p.as_ptr(), n.as_ptr(), ctx) == 1 - }) + /// Places the result of `a^p` in `r`. + pub fn exp(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + p: &BigNumRef) -> Result<(), ErrorStack> { + unsafe{ + cvt(ffi::BN_exp(r.as_ptr(), a.as_ptr(), p.as_ptr(), self.0)).map(|_| ()) } } - /// Calculates the modular multiplicative inverse of `self` modulo `n`, that is, an integer `r` - /// such that `(self * r) % n == 1`. - pub fn checked_mod_inv(&self, n: &BigNumRef) -> Result { + /// Places the result of `a^p mod m` in `r`. + pub fn mod_exp(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + p: &BigNumRef, + m: &BigNumRef) -> Result<(), ErrorStack> { unsafe { - with_bn_in_ctx!(r, ctx, { - !ffi::BN_mod_inverse(r.as_ptr(), self.as_ptr(), n.as_ptr(), ctx).is_null() - }) + cvt(ffi::BN_mod_exp(r.as_ptr(), a.as_ptr(), p.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) } } - /// Add a `u32` to `self`. This is more efficient than adding a - /// `BigNum`. - pub fn add_word(&mut self, w: u32) -> Result<(), ErrorStack> { + /// Places the inverse of `a` modulo `n` in `r`. + pub fn mod_inverse(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + n: &BigNumRef) -> Result<(), ErrorStack> { unsafe { - if ffi::BN_add_word(self.as_ptr(), w as ffi::BN_ULONG) == 1 { - Ok(()) - } else { - Err(ErrorStack::get()) - } + cvt_p(ffi::BN_mod_inverse(r.0, a.0, n.0, self.0)).map(|_| ()) } } - pub fn sub_word(&mut self, w: u32) -> Result<(), ErrorStack> { + /// Places the greatest common denominator of `a` and `b` in `r`. + pub fn gcd(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + b: &BigNumRef) -> Result<(), ErrorStack> { unsafe { - if ffi::BN_sub_word(self.as_ptr(), w as ffi::BN_ULONG) == 1 { - Ok(()) - } else { - Err(ErrorStack::get()) - } + cvt(ffi::BN_gcd(r.0, a.0, b.0, self.0)).map(|_| ()) } } - pub fn mul_word(&mut self, w: u32) -> Result<(), ErrorStack> { - unsafe { - if ffi::BN_mul_word(self.as_ptr(), w as ffi::BN_ULONG) == 1 { - Ok(()) - } else { - Err(ErrorStack::get()) - } - } - } - - pub fn div_word(&mut self, w: u32) -> Result { - unsafe { - let result = ffi::BN_div_word(self.as_ptr(), w as ffi::BN_ULONG); - if result != !0 { - Ok(result.into()) - } else { - Err(ErrorStack::get()) - } - } - } - - pub fn mod_word(&self, w: u32) -> Result { - unsafe { - let result = ffi::BN_mod_word(self.as_ptr(), w as ffi::BN_ULONG); - if result != !0 { - Ok(result as u64) - } else { - Err(ErrorStack::get()) - } - } - } - - /// Computes the greatest common denominator of `self` and `a`. - pub fn checked_gcd(&self, a: &BigNumRef) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_gcd(r.as_ptr(), self.as_ptr(), a.as_ptr(), ctx) == 1 - }) - } - } - - /// Checks whether `self` is prime. + /// Checks whether `p` is prime. /// /// Performs a Miller-Rabin probabilistic primality test with `checks` iterations. /// - /// # Return Value - /// - /// Returns `true` if `self` is prime with an error probability of less than `0.25 ^ checks`. - pub fn is_prime(&self, checks: i32) -> Result { + /// Returns `true` if `p` is prime with an error probability of less than `0.25 ^ checks`. + pub fn is_prime(&mut self, p: &BigNumRef, checks: i32) -> Result { unsafe { - with_ctx!(ctx, { - Ok(ffi::BN_is_prime_ex(self.as_ptr(), - checks as c_int, - ctx, - ptr::null_mut()) == 1) - }) + cvt_n(ffi::BN_is_prime_ex(p.0, checks.into(), self.0, ptr::null_mut())).map(|r| r != 0) } } - /// Checks whether `self` is prime with optional trial division. + /// Checks whether `p` is prime with optional trial division. /// /// If `do_trial_division` is `true`, first performs trial division by a number of small primes. /// Then, like `is_prime`, performs a Miller-Rabin probabilistic primality test with `checks` @@ -274,35 +217,88 @@ impl<'a> BigNumRef<'a> { /// /// # Return Value /// - /// Returns `true` if `self` is prime with an error probability of less than `0.25 ^ checks`. - pub fn is_prime_fast(&self, checks: i32, do_trial_division: bool) -> Result { + /// Returns `true` if `p` is prime with an error probability of less than `0.25 ^ checks`. + pub fn is_prime_fasttest(&mut self, + p: &BigNumRef, + checks: i32, + do_trial_division: bool) -> Result { unsafe { - with_ctx!(ctx, { - Ok(ffi::BN_is_prime_fasttest_ex(self.as_ptr(), - checks as c_int, - ctx, - do_trial_division as c_int, - ptr::null_mut()) == 1) - }) + cvt_n(ffi::BN_is_prime_fasttest_ex(p.0, + checks.into(), + self.0, + do_trial_division as c_int, + ptr::null_mut())) + .map(|r| r != 0) + } + } +} + +/// A borrowed, signed, arbitrary-precision integer. +#[derive(Copy, Clone)] +pub struct BigNumRef<'a>(*mut ffi::BIGNUM, PhantomData<&'a ()>); + +impl<'a> BigNumRef<'a> { + pub unsafe fn from_ptr(handle: *mut ffi::BIGNUM) -> BigNumRef<'a> { + BigNumRef(handle, PhantomData) + } + + /// Adds a `u32` to `self`. + pub fn add_word(&mut self, w: u32) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_add_word(self.0, w as ffi::BN_ULONG)).map(|_| ()) } } - /// Generates a cryptographically strong pseudo-random `BigNum` `r` in the range - /// `0 <= r < self`. - pub fn checked_rand_in_range(&self) -> Result { + /// Subtracts a `u32` from `self`. + pub fn sub_word(&mut self, w: u32) -> Result<(), ErrorStack> { unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_rand_range(r.as_ptr(), self.as_ptr()) == 1 - }) + cvt(ffi::BN_sub_word(self.0, w as ffi::BN_ULONG)).map(|_| ()) } } - /// The cryptographically weak counterpart to `checked_rand_in_range`. - pub fn checked_pseudo_rand_in_range(&self) -> Result { + /// Multiplies a `u32` by `self`. + pub fn mul_word(&mut self, w: u32) -> Result<(), ErrorStack> { unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_pseudo_rand_range(r.as_ptr(), self.as_ptr()) == 1 - }) + cvt(ffi::BN_mul_word(self.0, w as ffi::BN_ULONG)).map(|_| ()) + } + } + + /// Divides `self` by a `u32`, returning the remainder. + pub fn div_word(&mut self, w: u32) -> Result { + unsafe { + let r = ffi::BN_div_word(self.0, w.into()); + if r == ffi::BN_ULONG::max_value() { + Err(ErrorStack::get()) + } else { + Ok(r.into()) + } + } + } + + /// Returns the result of `self` modulo `w`. + pub fn mod_word(&self, w: u32) -> Result { + unsafe { + let r = ffi::BN_mod_word(self.0, w.into()); + if r == ffi::BN_ULONG::max_value() { + Err(ErrorStack::get()) + } else { + Ok(r.into()) + } + } + } + + /// Places a cryptographically-secure pseudo-random number nonnegative + /// number less than `self` in `rnd`. + pub fn rand_in_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_rand_range(self.0, rnd.0)).map(|_| ()) + } + } + + /// The cryptographically weak counterpart to `rand_in_range`. + pub fn pseudo_rand_in_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_pseudo_rand_range(self.0, rnd.0)).map(|_| ()) } } @@ -311,11 +307,7 @@ impl<'a> BigNumRef<'a> { /// When setting a bit outside of `self`, it is expanded. pub fn set_bit(&mut self, n: i32) -> Result<(), ErrorStack> { unsafe { - if ffi::BN_set_bit(self.as_ptr(), n as c_int) == 1 { - Ok(()) - } else { - Err(ErrorStack::get()) - } + cvt(ffi::BN_set_bit(self.0, n.into())).map(|_| ()) } } @@ -324,17 +316,15 @@ impl<'a> BigNumRef<'a> { /// When clearing a bit outside of `self`, an error is returned. pub fn clear_bit(&mut self, n: i32) -> Result<(), ErrorStack> { unsafe { - if ffi::BN_clear_bit(self.as_ptr(), n as c_int) == 1 { - Ok(()) - } else { - Err(ErrorStack::get()) - } + cvt(ffi::BN_clear_bit(self.0, n.into())).map(|_| ()) } } /// Returns `true` if the `n`th bit of `self` is set to 1, `false` otherwise. pub fn is_bit_set(&self, n: i32) -> bool { - unsafe { ffi::BN_is_bit_set(self.as_ptr(), n as c_int) == 1 } + unsafe { + ffi::BN_is_bit_set(self.0, n.into()) == 1 + } } /// Truncates `self` to the lowest `n` bits. @@ -342,46 +332,21 @@ impl<'a> BigNumRef<'a> { /// An error occurs if `self` is already shorter than `n` bits. pub fn mask_bits(&mut self, n: i32) -> Result<(), ErrorStack> { unsafe { - if ffi::BN_mask_bits(self.as_ptr(), n as c_int) == 1 { - Ok(()) - } else { - Err(ErrorStack::get()) - } + cvt(ffi::BN_mask_bits(self.0, n.into())).map(|_| ()) } } - /// Returns `self`, shifted left by 1 bit. `self` may be negative. - /// - /// ``` - /// # use openssl::bn::BigNum; - /// let ref s = BigNum::new_from(0b0100).unwrap(); - /// let result = BigNum::new_from(0b1000).unwrap(); - /// - /// assert_eq!(s.checked_shl1().unwrap(), result); - /// ``` - /// - /// ``` - /// # use openssl::bn::BigNum; - /// let ref s = -BigNum::new_from(8).unwrap(); - /// let result = -BigNum::new_from(16).unwrap(); - /// - /// // (-8) << 1 == -16 - /// assert_eq!(s.checked_shl1().unwrap(), result); - /// ``` - pub fn checked_shl1(&self) -> Result { + /// Places `self << 1` in `r`. + pub fn lshift1(&self, r: &mut BigNumRef) -> Result<(), ErrorStack> { unsafe { - with_bn!(r, { - ffi::BN_lshift1(r.as_ptr(), self.as_ptr()) == 1 - }) + cvt(ffi::BN_lshift1(r.0, self.0)).map(|_| ()) } } - /// Returns `self`, shifted right by 1 bit. `self` may be negative. - pub fn checked_shr1(&self) -> Result { + /// Places `self >> 1` in `r`. + pub fn rshift1(&self, r: &mut BigNumRef) -> Result<(), ErrorStack> { unsafe { - with_bn!(r, { - ffi::BN_rshift1(r.as_ptr(), self.as_ptr()) == 1 - }) + cvt(ffi::BN_rshift1(r.0, self.0)).map(|_| ()) } } @@ -1006,7 +971,7 @@ impl Neg for BigNum { #[cfg(test)] mod tests { - use bn::BigNum; + use bn::{BnCtx, BigNum}; #[test] fn test_to_from_slice() { @@ -1031,7 +996,8 @@ mod tests { let a = BigNum::new_from(19029017).unwrap(); let p = BigNum::checked_generate_prime(128, true, None, Some(&a)).unwrap(); - assert!(p.is_prime(100).unwrap()); - assert!(p.is_prime_fast(100, true).unwrap()); + let mut ctx = BnCtx::new().unwrap(); + assert!(ctx.is_prime(&p, 100).unwrap()); + assert!(ctx.is_prime_fasttest(&p, 100, true).unwrap()); } } diff --git a/openssl/src/dh/mod.rs b/openssl/src/dh.rs similarity index 98% rename from openssl/src/dh/mod.rs rename to openssl/src/dh.rs index 83807f39..6d0800a1 100644 --- a/openssl/src/dh/mod.rs +++ b/openssl/src/dh.rs @@ -135,7 +135,7 @@ mod tests { #[test] fn test_dh_from_pem() { let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); - let params = include_bytes!("../../test/dhparams.pem"); + let params = include_bytes!("../test/dhparams.pem"); let dh = DH::from_pem(params).ok().expect("Failed to load PEM"); ctx.set_tmp_dh(&dh).unwrap(); } diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index 62968742..39c9fffe 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -16,6 +16,10 @@ extern crate tempdir; #[doc(inline)] pub use ffi::init; +use libc::c_int; + +use error::ErrorStack; + mod macros; pub mod asn1; @@ -28,3 +32,27 @@ pub mod nid; pub mod ssl; pub mod version; pub mod x509; + +pub fn cvt_p(r: *mut T) -> Result<*mut T, ErrorStack> { + if r.is_null() { + Err(ErrorStack::get()) + } else { + Ok(r) + } +} + +pub fn cvt(r: c_int) -> Result { + if r <= 0 { + Err(ErrorStack::get()) + } else { + Ok(r) + } +} + +pub fn cvt_n(r: c_int) -> Result { + if r < 0 { + Err(ErrorStack::get()) + } else { + Ok(r) + } +} From 73ccfe7a29f55d4823fe9530e3c326d0b3099d6b Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 16 Oct 2016 16:42:56 -0700 Subject: [PATCH 049/186] Continue error handling cleanup Also overhaul/clean up pkcs5 internals --- openssl/src/crypto/dsa.rs | 53 ++++---- openssl/src/crypto/hash.rs | 12 +- openssl/src/crypto/pkcs5.rs | 239 ++++++++++++++---------------------- 3 files changed, 126 insertions(+), 178 deletions(-) diff --git a/openssl/src/crypto/dsa.rs b/openssl/src/crypto/dsa.rs index addaae2f..e0f31766 100644 --- a/openssl/src/crypto/dsa.rs +++ b/openssl/src/crypto/dsa.rs @@ -4,26 +4,25 @@ use error::ErrorStack; use std::ptr; use libc::{c_int, c_char, c_void}; +use {cvt, cvt_p}; use bn::BigNumRef; use bio::{MemBio, MemBioSlice}; use crypto::util::{CallbackState, invoke_passwd_cb}; - /// Builder for upfront DSA parameter generation pub struct DSAParams(*mut ffi::DSA); impl DSAParams { pub fn with_size(size: u32) -> Result { unsafe { - // Wrap it so that if we panic we'll call the dtor - let dsa = DSAParams(try_ssl_null!(ffi::DSA_new())); - try_ssl!(ffi::DSA_generate_parameters_ex(dsa.0, + let dsa = DSAParams(try!(cvt_p(ffi::DSA_new()))); + try!(cvt(ffi::DSA_generate_parameters_ex(dsa.0, size as c_int, ptr::null(), 0, ptr::null_mut(), ptr::null_mut(), - ptr::null_mut())); + ptr::null_mut()))); Ok(dsa) } } @@ -31,7 +30,7 @@ impl DSAParams { /// Generate a key pair from the initialized parameters pub fn generate(self) -> Result { unsafe { - try_ssl!(ffi::DSA_generate_key(self.0)); + try!(cvt(ffi::DSA_generate_key(self.0))); let dsa = DSA(self.0); ::std::mem::forget(self); Ok(dsa) @@ -75,13 +74,11 @@ impl DSA { let mem_bio = try!(MemBioSlice::new(buf)); unsafe { - let dsa = try_ssl_null!(ffi::PEM_read_bio_DSAPrivateKey(mem_bio.as_ptr(), - ptr::null_mut(), - None, - ptr::null_mut())); - let dsa = DSA(dsa); - assert!(dsa.has_private_key()); - Ok(dsa) + let dsa = try!(cvt_p(ffi::PEM_read_bio_DSAPrivateKey(mem_bio.as_ptr(), + ptr::null_mut(), + None, + ptr::null_mut()))); + Ok(DSA(dsa)) } } @@ -99,13 +96,11 @@ impl DSA { unsafe { let cb_ptr = &mut cb as *mut _ as *mut c_void; - let dsa = try_ssl_null!(ffi::PEM_read_bio_DSAPrivateKey(mem_bio.as_ptr(), - ptr::null_mut(), - Some(invoke_passwd_cb::), - cb_ptr)); - let dsa = DSA(dsa); - assert!(dsa.has_private_key()); - Ok(dsa) + let dsa = try!(cvt_p(ffi::PEM_read_bio_DSAPrivateKey(mem_bio.as_ptr(), + ptr::null_mut(), + Some(invoke_passwd_cb::), + cb_ptr))); + Ok(DSA(dsa)) } } @@ -116,9 +111,9 @@ impl DSA { let mem_bio = try!(MemBio::new()); unsafe { - try_ssl!(ffi::PEM_write_bio_DSAPrivateKey(mem_bio.as_ptr(), self.0, - ptr::null(), ptr::null_mut(), 0, - None, ptr::null_mut())) + try!(cvt(ffi::PEM_write_bio_DSAPrivateKey(mem_bio.as_ptr(), self.0, + ptr::null(), ptr::null_mut(), 0, + None, ptr::null_mut()))) }; Ok(mem_bio.get_buf().to_owned()) @@ -131,10 +126,10 @@ impl DSA { let mem_bio = try!(MemBioSlice::new(buf)); unsafe { - let dsa = try_ssl_null!(ffi::PEM_read_bio_DSA_PUBKEY(mem_bio.as_ptr(), - ptr::null_mut(), - None, - ptr::null_mut())); + let dsa = try!(cvt_p(ffi::PEM_read_bio_DSA_PUBKEY(mem_bio.as_ptr(), + ptr::null_mut(), + None, + ptr::null_mut()))); Ok(DSA(dsa)) } } @@ -142,7 +137,9 @@ impl DSA { /// Writes an DSA public key as PEM formatted data pub fn public_key_to_pem(&self) -> Result, ErrorStack> { let mem_bio = try!(MemBio::new()); - unsafe { try_ssl!(ffi::PEM_write_bio_DSA_PUBKEY(mem_bio.as_ptr(), self.0)) }; + unsafe { + try!(cvt(ffi::PEM_write_bio_DSA_PUBKEY(mem_bio.as_ptr(), self.0))); + } Ok(mem_bio.get_buf().to_owned()) } diff --git a/openssl/src/crypto/hash.rs b/openssl/src/crypto/hash.rs index 2fa75807..ec265631 100644 --- a/openssl/src/crypto/hash.rs +++ b/openssl/src/crypto/hash.rs @@ -1,6 +1,5 @@ use std::io::prelude::*; use std::io; -use std::ptr; use ffi; #[cfg(ossl110)] @@ -8,6 +7,7 @@ use ffi::{EVP_MD_CTX_new, EVP_MD_CTX_free}; #[cfg(any(ossl101, ossl102))] use ffi::{EVP_MD_CTX_create as EVP_MD_CTX_new, EVP_MD_CTX_destroy as EVP_MD_CTX_free}; +use {cvt, cvt_p}; use error::ErrorStack; #[derive(Copy, Clone)] @@ -116,7 +116,7 @@ impl Hasher { pub fn new(ty: MessageDigest) -> Result { ffi::init(); - let ctx = unsafe { try_ssl_null!(EVP_MD_CTX_new()) }; + let ctx = unsafe { try!(cvt_p(EVP_MD_CTX_new())) }; let mut h = Hasher { ctx: ctx, @@ -136,7 +136,7 @@ impl Hasher { } Finalized => (), } - unsafe { try_ssl!(ffi::EVP_DigestInit_ex(self.ctx, self.md, 0 as *mut _)); } + unsafe { try!(cvt(ffi::EVP_DigestInit_ex(self.ctx, self.md, 0 as *mut _))); } self.state = Reset; Ok(()) } @@ -147,9 +147,9 @@ impl Hasher { try!(self.init()); } unsafe { - try_ssl!(ffi::EVP_DigestUpdate(self.ctx, + try!(cvt(ffi::EVP_DigestUpdate(self.ctx, data.as_ptr() as *mut _, - data.len())); + data.len()))); } self.state = Updated; Ok(()) @@ -164,7 +164,7 @@ impl Hasher { unsafe { let mut len = ffi::EVP_MAX_MD_SIZE; let mut res = vec![0; len as usize]; - try_ssl!(ffi::EVP_DigestFinal_ex(self.ctx, res.as_mut_ptr(), &mut len)); + try!(cvt(ffi::EVP_DigestFinal_ex(self.ctx, res.as_mut_ptr(), &mut len))); res.truncate(len as usize); self.state = Finalized; Ok(res) diff --git a/openssl/src/crypto/pkcs5.rs b/openssl/src/crypto/pkcs5.rs index 9d348b89..8bcb9b31 100644 --- a/openssl/src/crypto/pkcs5.rs +++ b/openssl/src/crypto/pkcs5.rs @@ -2,6 +2,7 @@ use libc::c_int; use std::ptr; use ffi; +use cvt; use crypto::hash::MessageDigest; use crypto::symm::Cipher; use error::ErrorStack; @@ -9,26 +10,27 @@ use error::ErrorStack; #[derive(Clone, Eq, PartialEq, Hash, Debug)] pub struct KeyIvPair { pub key: Vec, - pub iv: Vec, + pub iv: Option>, } /// Derives a key and an IV from various parameters. /// -/// If specified `salt` must be 8 bytes in length. +/// If specified, `salt` must be 8 bytes in length. /// /// If the total key and IV length is less than 16 bytes and MD5 is used then /// the algorithm is compatible with the key derivation algorithm from PKCS#5 /// v1.5 or PBKDF1 from PKCS#5 v2.0. /// -/// New applications should not use this and instead use `pbkdf2_hmac_sha1` or -/// another more modern key derivation algorithm. -pub fn evp_bytes_to_key_pbkdf1_compatible(cipher: Cipher, - digest: MessageDigest, - data: &[u8], - salt: Option<&[u8]>, - count: u32) - -> Result { +/// New applications should not use this and instead use +/// `pkcs5_pbkdf2_hmac_sha1` or another more modern key derivation algorithm. +pub fn bytes_to_key(cipher: Cipher, + digest: MessageDigest, + data: &[u8], + salt: Option<&[u8]>, + count: i32) + -> Result { unsafe { + assert!(data.len() <= c_int::max_value() as usize); let salt_ptr = match salt { Some(salt) => { assert_eq!(salt.len(), ffi::PKCS5_SALT_LEN as usize); @@ -39,78 +41,58 @@ pub fn evp_bytes_to_key_pbkdf1_compatible(cipher: Cipher, ffi::init(); + let mut iv = cipher.iv_len().map(|l| vec![0; l]); + let cipher = cipher.as_ptr(); let digest = digest.as_ptr(); - let len = ffi::EVP_BytesToKey(cipher, - digest, - salt_ptr, - data.as_ptr(), - data.len() as c_int, - count as c_int, - ptr::null_mut(), - ptr::null_mut()); - if len == 0 { - return Err(ErrorStack::get()); - } + let len = try!(cvt(ffi::EVP_BytesToKey(cipher, + digest, + salt_ptr, + ptr::null(), + data.len() as c_int, + count.into(), + ptr::null_mut(), + ptr::null_mut()))); let mut key = vec![0; len as usize]; - let mut iv = vec![0; len as usize]; + let iv_ptr = iv.as_mut().map(|v| v.as_mut_ptr()).unwrap_or(ptr::null_mut()); - try_ssl!(ffi::EVP_BytesToKey(cipher, + try!(cvt(ffi::EVP_BytesToKey(cipher, digest, salt_ptr, data.as_ptr(), data.len() as c_int, count as c_int, key.as_mut_ptr(), - iv.as_mut_ptr())); + iv_ptr))); Ok(KeyIvPair { key: key, iv: iv }) } } -/// Derives a key from a password and salt using the PBKDF2-HMAC-SHA1 algorithm. -pub fn pbkdf2_hmac_sha1(pass: &[u8], - salt: &[u8], - iter: usize, - keylen: usize) - -> Result, ErrorStack> { - unsafe { - let mut out = vec![0; keylen]; - - ffi::init(); - - try_ssl!(ffi::PKCS5_PBKDF2_HMAC_SHA1(pass.as_ptr() as *const _, - pass.len() as c_int, - salt.as_ptr(), - salt.len() as c_int, - iter as c_int, - keylen as c_int, - out.as_mut_ptr())); - Ok(out) - } -} - /// Derives a key from a password and salt using the PBKDF2-HMAC algorithm with a digest function. pub fn pbkdf2_hmac(pass: &[u8], salt: &[u8], iter: usize, hash: MessageDigest, - keylen: usize) - -> Result, ErrorStack> { + key: &mut [u8]) + -> Result<(), ErrorStack> { unsafe { - let mut out = vec![0; keylen]; + assert!(pass.len() <= c_int::max_value() as usize); + assert!(salt.len() <= c_int::max_value() as usize); + assert!(key.len() <= c_int::max_value() as usize); + ffi::init(); - try_ssl!(ffi::PKCS5_PBKDF2_HMAC(pass.as_ptr() as *const _, - pass.len() as c_int, - salt.as_ptr(), - salt.len() as c_int, - iter as c_int, - hash.as_ptr(), - keylen as c_int, - out.as_mut_ptr())); - Ok(out) + cvt(ffi::PKCS5_PBKDF2_HMAC(pass.as_ptr() as *const _, + pass.len() as c_int, + salt.as_ptr(), + salt.len() as c_int, + iter as c_int, + hash.as_ptr(), + key.len() as c_int, + key.as_mut_ptr())) + .map(|_| ()) } } @@ -120,96 +102,67 @@ mod tests { use crypto::symm::Cipher; // Test vectors from - // http://tools.ietf.org/html/draft-josefsson-pbkdf2-test-vectors-06 + // https://git.lysator.liu.se/nettle/nettle/blob/nettle_3.1.1_release_20150424/testsuite/pbkdf2-test.c #[test] - fn test_pbkdf2_hmac_sha1() { - assert_eq!(super::pbkdf2_hmac_sha1(b"password", b"salt", 1, 20).unwrap(), - vec![0x0c_u8, 0x60_u8, 0xc8_u8, 0x0f_u8, 0x96_u8, 0x1f_u8, 0x0e_u8, 0x71_u8, - 0xf3_u8, 0xa9_u8, 0xb5_u8, 0x24_u8, 0xaf_u8, 0x60_u8, 0x12_u8, 0x06_u8, - 0x2f_u8, 0xe0_u8, 0x37_u8, 0xa6_u8]); + fn pbkdf2_hmac_sha256() { + let mut buf = [0; 16]; - assert_eq!(super::pbkdf2_hmac_sha1(b"password", b"salt", 2, 20).unwrap(), - vec![0xea_u8, 0x6c_u8, 0x01_u8, 0x4d_u8, 0xc7_u8, 0x2d_u8, 0x6f_u8, 0x8c_u8, - 0xcd_u8, 0x1e_u8, 0xd9_u8, 0x2a_u8, 0xce_u8, 0x1d_u8, 0x41_u8, 0xf0_u8, - 0xd8_u8, 0xde_u8, 0x89_u8, 0x57_u8]); + super::pbkdf2_hmac(b"passwd", b"salt", 1, MessageDigest::sha256(), &mut buf).unwrap(); + assert_eq!(buf, + &[0x55_u8, 0xac_u8, 0x04_u8, 0x6e_u8, 0x56_u8, 0xe3_u8, 0x08_u8, 0x9f_u8, + 0xec_u8, 0x16_u8, 0x91_u8, 0xc2_u8, 0x25_u8, 0x44_u8, 0xb6_u8, 0x05_u8][..]); - assert_eq!(super::pbkdf2_hmac_sha1(b"password", b"salt", 4096, 20).unwrap(), - vec![0x4b_u8, 0x00_u8, 0x79_u8, 0x01_u8, 0xb7_u8, 0x65_u8, 0x48_u8, 0x9a_u8, - 0xbe_u8, 0xad_u8, 0x49_u8, 0xd9_u8, 0x26_u8, 0xf7_u8, 0x21_u8, 0xd0_u8, - 0x65_u8, 0xa4_u8, 0x29_u8, 0xc1_u8]); - - assert_eq!(super::pbkdf2_hmac_sha1(b"password", b"salt", 16777216, 20).unwrap(), - vec![0xee_u8, 0xfe_u8, 0x3d_u8, 0x61_u8, 0xcd_u8, 0x4d_u8, 0xa4_u8, 0xe4_u8, - 0xe9_u8, 0x94_u8, 0x5b_u8, 0x3d_u8, 0x6b_u8, 0xa2_u8, 0x15_u8, 0x8c_u8, - 0x26_u8, 0x34_u8, 0xe9_u8, 0x84_u8]); - - assert_eq!(super::pbkdf2_hmac_sha1(b"passwordPASSWORDpassword", - b"saltSALTsaltSALTsaltSALTsaltSALTsalt", - 4096, - 25).unwrap(), - vec![0x3d_u8, 0x2e_u8, 0xec_u8, 0x4f_u8, 0xe4_u8, 0x1c_u8, 0x84_u8, 0x9b_u8, - 0x80_u8, 0xc8_u8, 0xd8_u8, 0x36_u8, 0x62_u8, 0xc0_u8, 0xe4_u8, 0x4a_u8, - 0x8b_u8, 0x29_u8, 0x1a_u8, 0x96_u8, 0x4c_u8, 0xf2_u8, 0xf0_u8, 0x70_u8, - 0x38_u8]); - - assert_eq!(super::pbkdf2_hmac_sha1(b"pass\x00word", b"sa\x00lt", 4096, 16).unwrap(), - vec![0x56_u8, 0xfa_u8, 0x6a_u8, 0xa7_u8, 0x55_u8, 0x48_u8, 0x09_u8, 0x9d_u8, - 0xcc_u8, 0x37_u8, 0xd7_u8, 0xf0_u8, 0x34_u8, 0x25_u8, 0xe0_u8, 0xc3_u8]); + super::pbkdf2_hmac(b"Password", b"NaCl", 80000, MessageDigest::sha256(), &mut buf).unwrap(); + assert_eq!(buf, + &[0x4d_u8, 0xdc_u8, 0xd8_u8, 0xf6_u8, 0x0b_u8, 0x98_u8, 0xbe_u8, 0x21_u8, + 0x83_u8, 0x0c_u8, 0xee_u8, 0x5e_u8, 0xf2_u8, 0x27_u8, 0x01_u8, 0xf9_u8][..]); } // Test vectors from // https://git.lysator.liu.se/nettle/nettle/blob/nettle_3.1.1_release_20150424/testsuite/pbkdf2-test.c #[test] - fn test_pbkdf2_hmac_sha256() { - assert_eq!(super::pbkdf2_hmac(b"passwd", b"salt", 1, MessageDigest::sha256(), 16).unwrap(), - vec![0x55_u8, 0xac_u8, 0x04_u8, 0x6e_u8, 0x56_u8, 0xe3_u8, 0x08_u8, 0x9f_u8, - 0xec_u8, 0x16_u8, 0x91_u8, 0xc2_u8, 0x25_u8, 0x44_u8, 0xb6_u8, 0x05_u8]); + fn pbkdf2_hmac_sha512() { + let mut buf = [0; 64]; - assert_eq!(super::pbkdf2_hmac(b"Password", b"NaCl", 80000, MessageDigest::sha256(), 16).unwrap(), - vec![0x4d_u8, 0xdc_u8, 0xd8_u8, 0xf6_u8, 0x0b_u8, 0x98_u8, 0xbe_u8, 0x21_u8, - 0x83_u8, 0x0c_u8, 0xee_u8, 0x5e_u8, 0xf2_u8, 0x27_u8, 0x01_u8, 0xf9_u8]); - } + super::pbkdf2_hmac(b"password", b"NaCL", 1, MessageDigest::sha512(), &mut buf).unwrap(); + assert_eq!(&buf[..], + &[0x73_u8, 0xde_u8, 0xcf_u8, 0xa5_u8, 0x8a_u8, 0xa2_u8, 0xe8_u8, 0x4f_u8, + 0x94_u8, 0x77_u8, 0x1a_u8, 0x75_u8, 0x73_u8, 0x6b_u8, 0xb8_u8, 0x8b_u8, + 0xd3_u8, 0xc7_u8, 0xb3_u8, 0x82_u8, 0x70_u8, 0xcf_u8, 0xb5_u8, 0x0c_u8, + 0xb3_u8, 0x90_u8, 0xed_u8, 0x78_u8, 0xb3_u8, 0x05_u8, 0x65_u8, 0x6a_u8, + 0xf8_u8, 0x14_u8, 0x8e_u8, 0x52_u8, 0x45_u8, 0x2b_u8, 0x22_u8, 0x16_u8, + 0xb2_u8, 0xb8_u8, 0x09_u8, 0x8b_u8, 0x76_u8, 0x1f_u8, 0xc6_u8, 0x33_u8, + 0x60_u8, 0x60_u8, 0xa0_u8, 0x9f_u8, 0x76_u8, 0x41_u8, 0x5e_u8, 0x9f_u8, + 0x71_u8, 0xea_u8, 0x47_u8, 0xf9_u8, 0xe9_u8, 0x06_u8, 0x43_u8, 0x06_u8][..]); - // Test vectors from - // https://git.lysator.liu.se/nettle/nettle/blob/nettle_3.1.1_release_20150424/testsuite/pbkdf2-test.c - #[test] - fn test_pbkdf2_hmac_sha512() { - assert_eq!(super::pbkdf2_hmac(b"password", b"NaCL", 1, MessageDigest::sha512(), 64).unwrap(), - vec![0x73_u8, 0xde_u8, 0xcf_u8, 0xa5_u8, 0x8a_u8, 0xa2_u8, 0xe8_u8, 0x4f_u8, - 0x94_u8, 0x77_u8, 0x1a_u8, 0x75_u8, 0x73_u8, 0x6b_u8, 0xb8_u8, 0x8b_u8, - 0xd3_u8, 0xc7_u8, 0xb3_u8, 0x82_u8, 0x70_u8, 0xcf_u8, 0xb5_u8, 0x0c_u8, - 0xb3_u8, 0x90_u8, 0xed_u8, 0x78_u8, 0xb3_u8, 0x05_u8, 0x65_u8, 0x6a_u8, - 0xf8_u8, 0x14_u8, 0x8e_u8, 0x52_u8, 0x45_u8, 0x2b_u8, 0x22_u8, 0x16_u8, - 0xb2_u8, 0xb8_u8, 0x09_u8, 0x8b_u8, 0x76_u8, 0x1f_u8, 0xc6_u8, 0x33_u8, - 0x60_u8, 0x60_u8, 0xa0_u8, 0x9f_u8, 0x76_u8, 0x41_u8, 0x5e_u8, 0x9f_u8, - 0x71_u8, 0xea_u8, 0x47_u8, 0xf9_u8, 0xe9_u8, 0x06_u8, 0x43_u8, 0x06_u8]); + super::pbkdf2_hmac(b"pass\0word", b"sa\0lt", 1, MessageDigest::sha512(), &mut buf).unwrap(); + assert_eq!(&buf[..], + &[0x71_u8, 0xa0_u8, 0xec_u8, 0x84_u8, 0x2a_u8, 0xbd_u8, 0x5c_u8, 0x67_u8, + 0x8b_u8, 0xcf_u8, 0xd1_u8, 0x45_u8, 0xf0_u8, 0x9d_u8, 0x83_u8, 0x52_u8, + 0x2f_u8, 0x93_u8, 0x36_u8, 0x15_u8, 0x60_u8, 0x56_u8, 0x3c_u8, 0x4d_u8, + 0x0d_u8, 0x63_u8, 0xb8_u8, 0x83_u8, 0x29_u8, 0x87_u8, 0x10_u8, 0x90_u8, + 0xe7_u8, 0x66_u8, 0x04_u8, 0xa4_u8, 0x9a_u8, 0xf0_u8, 0x8f_u8, 0xe7_u8, + 0xc9_u8, 0xf5_u8, 0x71_u8, 0x56_u8, 0xc8_u8, 0x79_u8, 0x09_u8, 0x96_u8, + 0xb2_u8, 0x0f_u8, 0x06_u8, 0xbc_u8, 0x53_u8, 0x5e_u8, 0x5a_u8, 0xb5_u8, + 0x44_u8, 0x0d_u8, 0xf7_u8, 0xe8_u8, 0x78_u8, 0x29_u8, 0x6f_u8, 0xa7_u8][..]); - assert_eq!(super::pbkdf2_hmac(b"pass\0word", b"sa\0lt", 1, MessageDigest::sha512(), 64).unwrap(), - vec![0x71_u8, 0xa0_u8, 0xec_u8, 0x84_u8, 0x2a_u8, 0xbd_u8, 0x5c_u8, 0x67_u8, - 0x8b_u8, 0xcf_u8, 0xd1_u8, 0x45_u8, 0xf0_u8, 0x9d_u8, 0x83_u8, 0x52_u8, - 0x2f_u8, 0x93_u8, 0x36_u8, 0x15_u8, 0x60_u8, 0x56_u8, 0x3c_u8, 0x4d_u8, - 0x0d_u8, 0x63_u8, 0xb8_u8, 0x83_u8, 0x29_u8, 0x87_u8, 0x10_u8, 0x90_u8, - 0xe7_u8, 0x66_u8, 0x04_u8, 0xa4_u8, 0x9a_u8, 0xf0_u8, 0x8f_u8, 0xe7_u8, - 0xc9_u8, 0xf5_u8, 0x71_u8, 0x56_u8, 0xc8_u8, 0x79_u8, 0x09_u8, 0x96_u8, - 0xb2_u8, 0x0f_u8, 0x06_u8, 0xbc_u8, 0x53_u8, 0x5e_u8, 0x5a_u8, 0xb5_u8, - 0x44_u8, 0x0d_u8, 0xf7_u8, 0xe8_u8, 0x78_u8, 0x29_u8, 0x6f_u8, 0xa7_u8]); - - assert_eq!(super::pbkdf2_hmac(b"passwordPASSWORDpassword", - b"salt\0\0\0", - 50, - MessageDigest::sha512(), - 64).unwrap(), - vec![0x01_u8, 0x68_u8, 0x71_u8, 0xa4_u8, 0xc4_u8, 0xb7_u8, 0x5f_u8, 0x96_u8, - 0x85_u8, 0x7f_u8, 0xd2_u8, 0xb9_u8, 0xf8_u8, 0xca_u8, 0x28_u8, 0x02_u8, - 0x3b_u8, 0x30_u8, 0xee_u8, 0x2a_u8, 0x39_u8, 0xf5_u8, 0xad_u8, 0xca_u8, - 0xc8_u8, 0xc9_u8, 0x37_u8, 0x5f_u8, 0x9b_u8, 0xda_u8, 0x1c_u8, 0xcd_u8, - 0x1b_u8, 0x6f_u8, 0x0b_u8, 0x2f_u8, 0xc3_u8, 0xad_u8, 0xda_u8, 0x50_u8, - 0x54_u8, 0x12_u8, 0xe7_u8, 0x9d_u8, 0x89_u8, 0x00_u8, 0x56_u8, 0xc6_u8, - 0x2e_u8, 0x52_u8, 0x4c_u8, 0x7d_u8, 0x51_u8, 0x15_u8, 0x4b_u8, 0x1a_u8, - 0x85_u8, 0x34_u8, 0x57_u8, 0x5b_u8, 0xd0_u8, 0x2d_u8, 0xee_u8, 0x39_u8]); + super::pbkdf2_hmac(b"passwordPASSWORDpassword", + b"salt\0\0\0", + 50, + MessageDigest::sha512(), + &mut buf).unwrap(); + assert_eq!(&buf[..], + &[0x01_u8, 0x68_u8, 0x71_u8, 0xa4_u8, 0xc4_u8, 0xb7_u8, 0x5f_u8, 0x96_u8, + 0x85_u8, 0x7f_u8, 0xd2_u8, 0xb9_u8, 0xf8_u8, 0xca_u8, 0x28_u8, 0x02_u8, + 0x3b_u8, 0x30_u8, 0xee_u8, 0x2a_u8, 0x39_u8, 0xf5_u8, 0xad_u8, 0xca_u8, + 0xc8_u8, 0xc9_u8, 0x37_u8, 0x5f_u8, 0x9b_u8, 0xda_u8, 0x1c_u8, 0xcd_u8, + 0x1b_u8, 0x6f_u8, 0x0b_u8, 0x2f_u8, 0xc3_u8, 0xad_u8, 0xda_u8, 0x50_u8, + 0x54_u8, 0x12_u8, 0xe7_u8, 0x9d_u8, 0x89_u8, 0x00_u8, 0x56_u8, 0xc6_u8, + 0x2e_u8, 0x52_u8, 0x4c_u8, 0x7d_u8, 0x51_u8, 0x15_u8, 0x4b_u8, 0x1a_u8, + 0x85_u8, 0x34_u8, 0x57_u8, 0x5b_u8, 0xd0_u8, 0x2d_u8, 0xee_u8, 0x39_u8][..]); } #[test] - fn test_evp_bytes_to_key_pbkdf1_compatible() { + fn bytes_to_key() { let salt = [16_u8, 34_u8, 19_u8, 23_u8, 141_u8, 4_u8, 207_u8, 221_u8]; let data = [143_u8, 210_u8, 75_u8, 63_u8, 214_u8, 179_u8, 155_u8, 241_u8, 242_u8, 31_u8, @@ -224,18 +177,16 @@ mod tests { 98_u8, 245_u8, 246_u8, 238_u8, 177_u8, 229_u8, 161_u8, 183_u8, 224_u8, 174_u8, 3_u8, 6_u8, 244_u8, 236_u8, 255_u8]; let expected_iv = vec![4_u8, 223_u8, 153_u8, 219_u8, 28_u8, 142_u8, 234_u8, 68_u8, 227_u8, - 69_u8, 98_u8, 107_u8, 208_u8, 14_u8, 236_u8, 60_u8, 0_u8, 0_u8, - 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, - 0_u8, 0_u8, 0_u8]; + 69_u8, 98_u8, 107_u8, 208_u8, 14_u8, 236_u8, 60_u8]; - assert_eq!(super::evp_bytes_to_key_pbkdf1_compatible(Cipher::aes_256_cbc(), - MessageDigest::sha1(), - &data, - Some(&salt), - 1).unwrap(), + assert_eq!(super::bytes_to_key(Cipher::aes_256_cbc(), + MessageDigest::sha1(), + &data, + Some(&salt), + 1).unwrap(), super::KeyIvPair { key: expected_key, - iv: expected_iv, + iv: Some(expected_iv), }); } } From 19440c298143aa311578ead17c8949312f4b94af Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 16 Oct 2016 19:06:02 -0700 Subject: [PATCH 050/186] More error cleanup Also allocation free RSA --- openssl/src/crypto/dsa.rs | 2 - openssl/src/crypto/pkcs12.rs | 5 +- openssl/src/crypto/pkey.rs | 55 ++++---- openssl/src/crypto/rand.rs | 5 +- openssl/src/crypto/rsa.rs | 261 ++++++++++++++++++----------------- 5 files changed, 170 insertions(+), 158 deletions(-) diff --git a/openssl/src/crypto/dsa.rs b/openssl/src/crypto/dsa.rs index e0f31766..f9044661 100644 --- a/openssl/src/crypto/dsa.rs +++ b/openssl/src/crypto/dsa.rs @@ -236,11 +236,9 @@ impl fmt::Debug for DSA { #[cfg(test)] mod test { - use std::io::Write; use libc::c_char; use super::*; - use crypto::hash::*; #[test] pub fn test_generate() { diff --git a/openssl/src/crypto/pkcs12.rs b/openssl/src/crypto/pkcs12.rs index b028f29d..846b7baf 100644 --- a/openssl/src/crypto/pkcs12.rs +++ b/openssl/src/crypto/pkcs12.rs @@ -6,6 +6,7 @@ use std::cmp; use std::ptr; use std::ffi::CString; +use {cvt, cvt_p}; use crypto::pkey::PKey; use error::ErrorStack; use x509::X509; @@ -26,7 +27,7 @@ impl Pkcs12 { ffi::init(); let mut ptr = der.as_ptr() as *const c_uchar; let length = cmp::min(der.len(), c_long::max_value() as usize) as c_long; - let p12 = try_ssl_null!(ffi::d2i_PKCS12(ptr::null_mut(), &mut ptr, length)); + let p12 = try!(cvt_p(ffi::d2i_PKCS12(ptr::null_mut(), &mut ptr, length))); Ok(Pkcs12(p12)) } } @@ -40,7 +41,7 @@ impl Pkcs12 { let mut cert = ptr::null_mut(); let mut chain = ptr::null_mut(); - try_ssl!(ffi::PKCS12_parse(self.0, pass.as_ptr(), &mut pkey, &mut cert, &mut chain)); + try!(cvt(ffi::PKCS12_parse(self.0, pass.as_ptr(), &mut pkey, &mut cert, &mut chain))); let pkey = PKey::from_ptr(pkey); let cert = X509::from_ptr(cert); diff --git a/openssl/src/crypto/pkey.rs b/openssl/src/crypto/pkey.rs index 67ff7520..1d062cfa 100644 --- a/openssl/src/crypto/pkey.rs +++ b/openssl/src/crypto/pkey.rs @@ -3,6 +3,7 @@ use std::ptr; use std::mem; use ffi; +use {cvt, cvt_p}; use bio::{MemBio, MemBioSlice}; use crypto::dsa::DSA; use crypto::rsa::RSA; @@ -19,9 +20,9 @@ impl PKey { /// Create a new `PKey` containing an RSA key. pub fn from_rsa(rsa: RSA) -> Result { unsafe { - let evp = try_ssl_null!(ffi::EVP_PKEY_new()); + let evp = try!(cvt_p(ffi::EVP_PKEY_new())); let pkey = PKey(evp); - try_ssl!(ffi::EVP_PKEY_assign(pkey.0, ffi::EVP_PKEY_RSA, rsa.as_ptr() as *mut _)); + try!(cvt(ffi::EVP_PKEY_assign(pkey.0, ffi::EVP_PKEY_RSA, rsa.as_ptr() as *mut _))); mem::forget(rsa); Ok(pkey) } @@ -30,9 +31,9 @@ impl PKey { /// Create a new `PKey` containing a DSA key. pub fn from_dsa(dsa: DSA) -> Result { unsafe { - let evp = try_ssl_null!(ffi::EVP_PKEY_new()); + let evp = try!(cvt_p(ffi::EVP_PKEY_new())); let pkey = PKey(evp); - try_ssl!(ffi::EVP_PKEY_assign(pkey.0, ffi::EVP_PKEY_DSA, dsa.as_ptr() as *mut _)); + try!(cvt(ffi::EVP_PKEY_assign(pkey.0, ffi::EVP_PKEY_DSA, dsa.as_ptr() as *mut _))); mem::forget(dsa); Ok(pkey) } @@ -42,10 +43,10 @@ impl PKey { pub fn hmac(key: &[u8]) -> Result { unsafe { assert!(key.len() <= c_int::max_value() as usize); - let key = try_ssl_null!(ffi::EVP_PKEY_new_mac_key(ffi::EVP_PKEY_HMAC, - ptr::null_mut(), - key.as_ptr() as *const _, - key.len() as c_int)); + let key = try!(cvt_p(ffi::EVP_PKEY_new_mac_key(ffi::EVP_PKEY_HMAC, + ptr::null_mut(), + key.as_ptr() as *const _, + key.len() as c_int))); Ok(PKey(key)) } } @@ -59,10 +60,10 @@ impl PKey { ffi::init(); let mem_bio = try!(MemBioSlice::new(buf)); unsafe { - let evp = try_ssl_null!(ffi::PEM_read_bio_PrivateKey(mem_bio.as_ptr(), - ptr::null_mut(), - None, - ptr::null_mut())); + let evp = try!(cvt_p(ffi::PEM_read_bio_PrivateKey(mem_bio.as_ptr(), + ptr::null_mut(), + None, + ptr::null_mut()))); Ok(PKey::from_ptr(evp)) } } @@ -79,10 +80,10 @@ impl PKey { let mut cb = CallbackState::new(pass_cb); let mem_bio = try!(MemBioSlice::new(buf)); unsafe { - let evp = try_ssl_null!(ffi::PEM_read_bio_PrivateKey(mem_bio.as_ptr(), - ptr::null_mut(), - Some(invoke_passwd_cb::), - &mut cb as *mut _ as *mut c_void)); + let evp = try!(cvt_p(ffi::PEM_read_bio_PrivateKey(mem_bio.as_ptr(), + ptr::null_mut(), + Some(invoke_passwd_cb::), + &mut cb as *mut _ as *mut c_void))); Ok(PKey::from_ptr(evp)) } } @@ -92,10 +93,10 @@ impl PKey { ffi::init(); let mem_bio = try!(MemBioSlice::new(buf)); unsafe { - let evp = try_ssl_null!(ffi::PEM_read_bio_PUBKEY(mem_bio.as_ptr(), - ptr::null_mut(), - None, - ptr::null_mut())); + let evp = try!(cvt_p(ffi::PEM_read_bio_PUBKEY(mem_bio.as_ptr(), + ptr::null_mut(), + None, + ptr::null_mut()))); Ok(PKey::from_ptr(evp)) } } @@ -105,15 +106,15 @@ impl PKey { unsafe { // this needs to be a reference as the set1_RSA ups the reference count let rsa_ptr = rsa.as_ptr(); - try_ssl!(ffi::EVP_PKEY_set1_RSA(self.0, rsa_ptr)); + try!(cvt(ffi::EVP_PKEY_set1_RSA(self.0, rsa_ptr))); Ok(()) } } /// Get a reference to the interal RSA key for direct access to the key components - pub fn get_rsa(&self) -> Result { + pub fn rsa(&self) -> Result { unsafe { - let rsa = try_ssl_null!(ffi::EVP_PKEY_get1_RSA(self.0)); + let rsa = try!(cvt_p(ffi::EVP_PKEY_get1_RSA(self.0))); // this is safe as the ffi increments a reference counter to the internal key Ok(RSA::from_ptr(rsa)) } @@ -124,13 +125,13 @@ impl PKey { pub fn private_key_to_pem(&self) -> Result, ErrorStack> { let mem_bio = try!(MemBio::new()); unsafe { - try_ssl!(ffi::PEM_write_bio_PrivateKey(mem_bio.as_ptr(), + try!(cvt(ffi::PEM_write_bio_PrivateKey(mem_bio.as_ptr(), self.0, ptr::null(), ptr::null_mut(), -1, None, - ptr::null_mut())); + ptr::null_mut()))); } Ok(mem_bio.get_buf().to_owned()) @@ -139,7 +140,9 @@ impl PKey { /// Stores public key as a PEM pub fn public_key_to_pem(&self) -> Result, ErrorStack> { let mem_bio = try!(MemBio::new()); - unsafe { try_ssl!(ffi::PEM_write_bio_PUBKEY(mem_bio.as_ptr(), self.0)) } + unsafe { + try!(cvt(ffi::PEM_write_bio_PUBKEY(mem_bio.as_ptr(), self.0))); + } Ok(mem_bio.get_buf().to_owned()) } diff --git a/openssl/src/crypto/rand.rs b/openssl/src/crypto/rand.rs index 519449e9..c1c49e7b 100644 --- a/openssl/src/crypto/rand.rs +++ b/openssl/src/crypto/rand.rs @@ -1,13 +1,14 @@ use libc::c_int; use ffi; + +use cvt; use error::ErrorStack; pub fn rand_bytes(buf: &mut [u8]) -> Result<(), ErrorStack> { unsafe { ffi::init(); assert!(buf.len() <= c_int::max_value() as usize); - try_ssl_if!(ffi::RAND_bytes(buf.as_mut_ptr(), buf.len() as c_int) != 1); - Ok(()) + cvt(ffi::RAND_bytes(buf.as_mut_ptr(), buf.len() as c_int)).map(|_| ()) } } diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index 1212ee3a..95675abe 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -4,6 +4,7 @@ use std::ptr; use std::mem; use libc::{c_int, c_void, c_char}; +use {cvt, cvt_p, cvt_n}; use bn::{BigNum, BigNumRef}; use bio::{MemBio, MemBioSlice}; use error::ErrorStack; @@ -42,11 +43,11 @@ impl RSA { /// the supplied load and save methods for DER formatted keys. pub fn from_public_components(n: BigNum, e: BigNum) -> Result { unsafe { - let rsa = RSA(try_ssl_null!(ffi::RSA_new())); - try_ssl!(compat::set_key(rsa.0, + let rsa = RSA(try!(cvt_p(ffi::RSA_new()))); + try!(cvt(compat::set_key(rsa.0, n.as_ptr(), e.as_ptr(), - ptr::null_mut())); + ptr::null_mut()))); mem::forget((n, e)); Ok(rsa) } @@ -62,13 +63,13 @@ impl RSA { qi: BigNum) -> Result { unsafe { - let rsa = RSA(try_ssl_null!(ffi::RSA_new())); - try_ssl!(compat::set_key(rsa.0, n.as_ptr(), e.as_ptr(), d.as_ptr())); + let rsa = RSA(try!(cvt_p(ffi::RSA_new()))); + try!(cvt(compat::set_key(rsa.0, n.as_ptr(), e.as_ptr(), d.as_ptr()))); mem::forget((n, e, d)); - try_ssl!(compat::set_factors(rsa.0, p.as_ptr(), q.as_ptr())); + try!(cvt(compat::set_factors(rsa.0, p.as_ptr(), q.as_ptr()))); mem::forget((p, q)); - try_ssl!(compat::set_crt_params(rsa.0, dp.as_ptr(), dq.as_ptr(), - qi.as_ptr())); + try!(cvt(compat::set_crt_params(rsa.0, dp.as_ptr(), dq.as_ptr(), + qi.as_ptr()))); mem::forget((dp, dq, qi)); Ok(rsa) } @@ -83,12 +84,9 @@ impl RSA { /// The public exponent will be 65537. pub fn generate(bits: u32) -> Result { unsafe { - let rsa = try_ssl_null!(ffi::RSA_new()); - let rsa = RSA(rsa); + let rsa = RSA(try!(cvt_p(ffi::RSA_new()))); let e = try!(BigNum::new_from(ffi::RSA_F4 as u32)); - - try_ssl!(ffi::RSA_generate_key_ex(rsa.0, bits as c_int, e.as_ptr(), ptr::null_mut())); - + try!(cvt(ffi::RSA_generate_key_ex(rsa.0, bits as c_int, e.as_ptr(), ptr::null_mut()))); Ok(rsa) } } @@ -97,10 +95,10 @@ impl RSA { pub fn private_key_from_pem(buf: &[u8]) -> Result { let mem_bio = try!(MemBioSlice::new(buf)); unsafe { - let rsa = try_ssl_null!(ffi::PEM_read_bio_RSAPrivateKey(mem_bio.as_ptr(), - ptr::null_mut(), - None, - ptr::null_mut())); + let rsa = try!(cvt_p(ffi::PEM_read_bio_RSAPrivateKey(mem_bio.as_ptr(), + ptr::null_mut(), + None, + ptr::null_mut()))); Ok(RSA(rsa)) } } @@ -114,11 +112,10 @@ impl RSA { unsafe { let cb_ptr = &mut cb as *mut _ as *mut c_void; - let rsa = try_ssl_null!(ffi::PEM_read_bio_RSAPrivateKey(mem_bio.as_ptr(), - ptr::null_mut(), - Some(invoke_passwd_cb::), - cb_ptr)); - + let rsa = try!(cvt_p(ffi::PEM_read_bio_RSAPrivateKey(mem_bio.as_ptr(), + ptr::null_mut(), + Some(invoke_passwd_cb::), + cb_ptr))); Ok(RSA(rsa)) } } @@ -127,10 +124,10 @@ impl RSA { pub fn public_key_from_pem(buf: &[u8]) -> Result { let mem_bio = try!(MemBioSlice::new(buf)); unsafe { - let rsa = try_ssl_null!(ffi::PEM_read_bio_RSA_PUBKEY(mem_bio.as_ptr(), - ptr::null_mut(), - None, - ptr::null_mut())); + let rsa = try!(cvt_p(ffi::PEM_read_bio_RSA_PUBKEY(mem_bio.as_ptr(), + ptr::null_mut(), + None, + ptr::null_mut()))); Ok(RSA(rsa)) } } @@ -140,13 +137,13 @@ impl RSA { let mem_bio = try!(MemBio::new()); unsafe { - try_ssl!(ffi::PEM_write_bio_RSAPrivateKey(mem_bio.as_ptr(), - self.0, - ptr::null(), - ptr::null_mut(), - 0, - None, - ptr::null_mut())); + try!(cvt(ffi::PEM_write_bio_RSAPrivateKey(mem_bio.as_ptr(), + self.0, + ptr::null(), + ptr::null_mut(), + 0, + None, + ptr::null_mut()))); } Ok(mem_bio.get_buf().to_owned()) } @@ -156,93 +153,113 @@ impl RSA { let mem_bio = try!(MemBio::new()); unsafe { - try_ssl!(ffi::PEM_write_bio_RSA_PUBKEY(mem_bio.as_ptr(), self.0)) - }; + try!(cvt(ffi::PEM_write_bio_RSA_PUBKEY(mem_bio.as_ptr(), self.0))); + } Ok(mem_bio.get_buf().to_owned()) } - pub fn size(&self) -> Option { - if self.n().is_some() { - unsafe { Some(ffi::RSA_size(self.0) as u32) } - } else { - None + pub fn size(&self) -> usize { + unsafe { + assert!(self.n().is_some()); + + ffi::RSA_size(self.0) as usize } } - /** - * Decrypts data with the private key, using provided padding, returning the decrypted data. - */ - pub fn private_decrypt(&self, from: &[u8], padding: Padding) -> Result, ErrorStack> { + /// Decrypts data using the private key, returning the number of decrypted bytes. + /// + /// # Panics + /// + /// Panics if `self` has no private components, or if `to` is smaller + /// than `self.size()`. + pub fn private_decrypt(&self, + from: &[u8], + to: &mut [u8], + padding: Padding) + -> Result { assert!(self.d().is_some(), "private components missing"); - let k_len = self.size().expect("RSA missing an n"); - let mut to: Vec = vec![0; k_len as usize]; + assert!(from.len() <= i32::max_value() as usize); + assert!(to.len() >= self.size()); unsafe { - let enc_len = try_ssl_returns_size!(ffi::RSA_private_decrypt(from.len() as i32, - from.as_ptr(), - to.as_mut_ptr(), - self.0, - padding.0)); - to.truncate(enc_len as usize); - Ok(to) + let len = try!(cvt_n(ffi::RSA_private_decrypt(from.len() as c_int, + from.as_ptr(), + to.as_mut_ptr(), + self.0, + padding.0))); + Ok(len as usize) } } - /** - * Encrypts data with the private key, using provided padding, returning the encrypted data. - */ - pub fn private_encrypt(&self, from: &[u8], padding: Padding) -> Result, ErrorStack> { + /// Encrypts data using the private key, returning the number of encrypted bytes. + /// + /// # Panics + /// + /// Panics if `self` has no private components, or if `to` is smaller + /// than `self.size()`. + pub fn private_encrypt(&self, + from: &[u8], + to: &mut [u8], + padding: Padding) + -> Result { assert!(self.d().is_some(), "private components missing"); - let k_len = self.size().expect("RSA missing an n"); - let mut to:Vec = vec![0; k_len as usize]; + assert!(from.len() <= i32::max_value() as usize); + assert!(to.len() >= self.size()); unsafe { - let enc_len = try_ssl_returns_size!(ffi::RSA_private_encrypt(from.len() as c_int, - from.as_ptr(), - to.as_mut_ptr(), - self.0, - padding.0)); - assert!(enc_len as u32 == k_len); - - Ok(to) + let len = try!(cvt_n(ffi::RSA_private_encrypt(from.len() as c_int, + from.as_ptr(), + to.as_mut_ptr(), + self.0, + padding.0))); + Ok(len as usize) } } - /** - * Decrypts data with the public key, using provided padding, returning the decrypted data. - */ - pub fn public_decrypt(&self, from: &[u8], padding: Padding) -> Result, ErrorStack> { - let k_len = self.size().expect("RSA missing an n"); - let mut to: Vec = vec![0; k_len as usize]; + /// Decrypts data using the public key, returning the number of decrypted bytes. + /// + /// # Panics + /// + /// Panics if `to` is smaller than `self.size()`. + pub fn public_decrypt(&self, + from: &[u8], + to: &mut [u8], + padding: Padding) + -> Result { + assert!(from.len() <= i32::max_value() as usize); + assert!(to.len() >= self.size()); unsafe { - let enc_len = try_ssl_returns_size!(ffi::RSA_public_decrypt(from.len() as i32, - from.as_ptr(), - to.as_mut_ptr(), - self.0, - padding.0)); - to.truncate(enc_len as usize); - Ok(to) + let len = try!(cvt_n(ffi::RSA_public_decrypt(from.len() as c_int, + from.as_ptr(), + to.as_mut_ptr(), + self.0, + padding.0))); + Ok(len as usize) } } - /** - * Encrypts data with the public key, using provided padding, returning the encrypted data. - */ - pub fn public_encrypt(&self, from: &[u8], padding: Padding) -> Result, ErrorStack> { - let k_len = self.size().expect("RSA missing an n"); - let mut to:Vec = vec![0; k_len as usize]; + /// Encrypts data using the private key, returning the number of encrypted bytes. + /// + /// # Panics + /// + /// Panics if `to` is smaller than `self.size()`. + pub fn public_encrypt(&self, + from: &[u8], + to: &mut [u8], + padding: Padding) + -> Result { + assert!(from.len() <= i32::max_value() as usize); + assert!(to.len() >= self.size()); unsafe { - let enc_len = try_ssl_returns_size!(ffi::RSA_public_encrypt(from.len() as c_int, - from.as_ptr(), - to.as_mut_ptr(), - self.0, - padding.0)); - assert!(enc_len as u32 == k_len); - - Ok(to) + let len = try!(cvt_n(ffi::RSA_public_encrypt(from.len() as c_int, + from.as_ptr(), + to.as_mut_ptr(), + self.0, + padding.0))); + Ok(len as usize) } } @@ -424,55 +441,47 @@ mod test { let key = include_bytes!("../../test/rsa.pem.pub"); let public_key = RSA::public_key_from_pem(key).unwrap(); - let original_data: Vec = "This is test".to_string().into_bytes(); - let result = public_key.public_encrypt(&original_data, Padding::pkcs1()).unwrap(); - - assert_eq!(result.len(), 256); + let mut result = vec![0; public_key.size()]; + let original_data = b"This is test"; + let len = public_key.public_encrypt(original_data, &mut result, Padding::pkcs1()).unwrap(); + assert_eq!(len, 256); let pkey = include_bytes!("../../test/rsa.pem"); let private_key = RSA::private_key_from_pem(pkey).unwrap(); - let dec_result = private_key.private_decrypt(&result, Padding::pkcs1()).unwrap(); + let mut dec_result = vec![0; private_key.size()]; + let len = private_key.private_decrypt(&result, &mut dec_result, Padding::pkcs1()).unwrap(); - assert_eq!(dec_result, original_data); + assert_eq!(&dec_result[..len], original_data); } #[test] fn test_private_encrypt() { - let k0 = super::RSA::generate(512).unwrap(); - let k0pkey = k0.public_key_to_pem().unwrap(); - let k1 = super::RSA::public_key_from_pem(&k0pkey).unwrap(); + let k0 = super::RSA::generate(512).unwrap(); + let k0pkey = k0.public_key_to_pem().unwrap(); + let k1 = super::RSA::public_key_from_pem(&k0pkey).unwrap(); - let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); + let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; - let emsg = k0.private_encrypt(&msg, Padding::pkcs1()).unwrap(); - let dmsg = k1.public_decrypt(&emsg, Padding::pkcs1()).unwrap(); - assert!(msg == dmsg); + let mut emesg = vec![0; k0.size()]; + k0.private_encrypt(&msg, &mut emesg, Padding::pkcs1()).unwrap(); + let mut dmesg = vec![0; k1.size()]; + let len = k1.public_decrypt(&emesg, &mut dmesg, Padding::pkcs1()).unwrap(); + assert_eq!(msg, &dmesg[..len]); } #[test] fn test_public_encrypt() { let k0 = super::RSA::generate(512).unwrap(); - let k0pkey = k0.public_key_to_pem().unwrap(); - let k1 = super::RSA::public_key_from_pem(&k0pkey).unwrap(); + let k0pkey = k0.private_key_to_pem().unwrap(); + let k1 = super::RSA::private_key_from_pem(&k0pkey).unwrap(); - let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); + let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; - let emsg = k1.public_encrypt(&msg, Padding::pkcs1_oaep()).unwrap(); - let dmsg = k0.private_decrypt(&emsg, Padding::pkcs1_oaep()).unwrap(); - assert!(msg == dmsg); - } - - #[test] - fn test_public_encrypt_pkcs() { - let k0 = super::RSA::generate(512).unwrap(); - let k0pkey = k0.public_key_to_pem().unwrap(); - let k1 = super::RSA::public_key_from_pem(&k0pkey).unwrap(); - - let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); - - let emsg = k1.public_encrypt(&msg, super::Padding::pkcs1()).unwrap(); - let dmsg = k0.private_decrypt(&emsg, super::Padding::pkcs1()).unwrap(); - assert!(msg == dmsg); + let mut emesg = vec![0; k0.size()]; + k0.public_encrypt(&msg, &mut emesg, Padding::pkcs1()).unwrap(); + let mut dmesg = vec![0; k1.size()]; + let len = k1.private_decrypt(&emesg, &mut dmesg, Padding::pkcs1()).unwrap(); + assert_eq!(msg, &dmesg[..len]); } } From 89a366d9f7558489fe321fef81a88b1919d10032 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 16 Oct 2016 19:24:04 -0700 Subject: [PATCH 051/186] Finish crypto error cleanup --- openssl/src/crypto/sign.rs | 17 +++++++---------- openssl/src/crypto/symm.rs | 27 ++++++++++++++------------- 2 files changed, 21 insertions(+), 23 deletions(-) diff --git a/openssl/src/crypto/sign.rs b/openssl/src/crypto/sign.rs index fdedd4d5..41009149 100644 --- a/openssl/src/crypto/sign.rs +++ b/openssl/src/crypto/sign.rs @@ -59,6 +59,7 @@ use std::io::{self, Write}; use std::marker::PhantomData; use std::ptr; +use {cvt, cvt_p}; use crypto::hash::MessageDigest; use crypto::pkey::PKey; use error::ErrorStack; @@ -83,7 +84,7 @@ impl<'a> Signer<'a> { unsafe { ffi::init(); - let ctx = try_ssl_null!(EVP_MD_CTX_new()); + let ctx = try!(cvt_p(EVP_MD_CTX_new())); let r = ffi::EVP_DigestSignInit(ctx, ptr::null_mut(), type_.as_ptr(), @@ -93,25 +94,22 @@ impl<'a> Signer<'a> { EVP_MD_CTX_free(ctx); return Err(ErrorStack::get()); } - Ok(Signer(ctx, PhantomData)) } } pub fn update(&mut self, buf: &[u8]) -> Result<(), ErrorStack> { unsafe { - try_ssl_if!(ffi::EVP_DigestUpdate(self.0, buf.as_ptr() as *const _, buf.len()) != 1); - Ok(()) + cvt(ffi::EVP_DigestUpdate(self.0, buf.as_ptr() as *const _, buf.len())).map(|_| ()) } } pub fn finish(&self) -> Result, ErrorStack> { unsafe { let mut len = 0; - try_ssl_if!(ffi::EVP_DigestSignFinal(self.0, ptr::null_mut(), &mut len) != 1); + try!(cvt(ffi::EVP_DigestSignFinal(self.0, ptr::null_mut(), &mut len))); let mut buf = vec![0; len]; - try_ssl_if!(ffi::EVP_DigestSignFinal(self.0, buf.as_mut_ptr() as *mut _, &mut len) - != 1); + try!(cvt(ffi::EVP_DigestSignFinal(self.0, buf.as_mut_ptr() as *mut _, &mut len))); // The advertised length is not always equal to the real length for things like DSA buf.truncate(len); Ok(buf) @@ -145,7 +143,7 @@ impl<'a> Verifier<'a> { unsafe { ffi::init(); - let ctx = try_ssl_null!(EVP_MD_CTX_new()); + let ctx = try!(cvt_p(EVP_MD_CTX_new())); let r = ffi::EVP_DigestVerifyInit(ctx, ptr::null_mut(), type_.as_ptr(), @@ -162,8 +160,7 @@ impl<'a> Verifier<'a> { pub fn update(&mut self, buf: &[u8]) -> Result<(), ErrorStack> { unsafe { - try_ssl_if!(ffi::EVP_DigestUpdate(self.0, buf.as_ptr() as *const _, buf.len()) != 1); - Ok(()) + cvt(ffi::EVP_DigestUpdate(self.0, buf.as_ptr() as *const _, buf.len())).map(|_| ()) } } diff --git a/openssl/src/crypto/symm.rs b/openssl/src/crypto/symm.rs index 8ac6b7cf..65f0addb 100644 --- a/openssl/src/crypto/symm.rs +++ b/openssl/src/crypto/symm.rs @@ -3,6 +3,7 @@ use std::ptr; use libc::c_int; use ffi; +use {cvt, cvt_p}; use error::ErrorStack; #[derive(Copy, Clone)] @@ -170,7 +171,7 @@ impl Crypter { ffi::init(); unsafe { - let ctx = try_ssl_null!(ffi::EVP_CIPHER_CTX_new()); + let ctx = try!(cvt_p(ffi::EVP_CIPHER_CTX_new())); let crypter = Crypter { ctx: ctx, block_size: t.block_size(), @@ -181,15 +182,15 @@ impl Crypter { Mode::Decrypt => 0, }; - try_ssl!(ffi::EVP_CipherInit_ex(crypter.ctx, - t.as_ptr(), - ptr::null_mut(), - ptr::null_mut(), - ptr::null_mut(), - mode)); + try!(cvt(ffi::EVP_CipherInit_ex(crypter.ctx, + t.as_ptr(), + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + mode))); assert!(key.len() <= c_int::max_value() as usize); - try_ssl!(ffi::EVP_CIPHER_CTX_set_key_length(crypter.ctx, key.len() as c_int)); + try!(cvt(ffi::EVP_CIPHER_CTX_set_key_length(crypter.ctx, key.len() as c_int))); let key = key.as_ptr() as *mut _; let iv = match (iv, t.iv_len()) { @@ -200,12 +201,12 @@ impl Crypter { (Some(_), None) | (None, None) => ptr::null_mut(), (None, Some(_)) => panic!("an IV is required for this cipher"), }; - try_ssl!(ffi::EVP_CipherInit_ex(crypter.ctx, + try!(cvt(ffi::EVP_CipherInit_ex(crypter.ctx, ptr::null(), ptr::null_mut(), key, iv, - mode)); + mode))); Ok(crypter) } @@ -237,11 +238,11 @@ impl Crypter { let mut outl = output.len() as c_int; let inl = input.len() as c_int; - try_ssl!(ffi::EVP_CipherUpdate(self.ctx, + try!(cvt(ffi::EVP_CipherUpdate(self.ctx, output.as_mut_ptr(), &mut outl, input.as_ptr(), - inl)); + inl))); Ok(outl as usize) } @@ -262,7 +263,7 @@ impl Crypter { assert!(output.len() >= self.block_size); let mut outl = cmp::min(output.len(), c_int::max_value() as usize) as c_int; - try_ssl!(ffi::EVP_CipherFinal(self.ctx, output.as_mut_ptr(), &mut outl)); + try!(cvt(ffi::EVP_CipherFinal(self.ctx, output.as_mut_ptr(), &mut outl))); Ok(outl as usize) } From 78daed2d5875eee9807aaf5377b632a55f3f93a8 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 16 Oct 2016 20:14:04 -0700 Subject: [PATCH 052/186] ssl error handling cleanup --- openssl/src/ssl/bio.rs | 3 +- openssl/src/ssl/mod.rs | 170 +++++++++++++++++------------------ openssl/src/ssl/tests/mod.rs | 2 +- 3 files changed, 85 insertions(+), 90 deletions(-) diff --git a/openssl/src/ssl/bio.rs b/openssl/src/ssl/bio.rs index ccf3a472..968aad10 100644 --- a/openssl/src/ssl/bio.rs +++ b/openssl/src/ssl/bio.rs @@ -9,6 +9,7 @@ use std::ptr; use std::slice; use std::sync::Arc; +use cvt_p; use error::ErrorStack; pub struct StreamState { @@ -38,7 +39,7 @@ pub fn new(stream: S) -> Result<(*mut BIO, Arc), Err }); unsafe { - let bio = try_ssl_null!(BIO_new(method.0.get())); + let bio = try!(cvt_p(BIO_new(method.0.get()))); compat::BIO_set_data(bio, Box::into_raw(state) as *mut _); compat::BIO_set_init(bio, 1); diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 7b4f831b..55955753 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -19,7 +19,7 @@ use std::slice; use std::marker::PhantomData; use ffi; -use init; +use {init, cvt, cvt_p}; use dh::DH; use x509::{X509StoreContext, X509FileType, X509, X509Ref}; #[cfg(feature = "openssl-102")] @@ -341,16 +341,6 @@ pub enum SniError { NoAck, } -// FIXME: macro may be instead of inlining? -#[inline] -fn wrap_ssl_result(res: c_int) -> Result<(), ErrorStack> { - if res == 0 { - Err(ErrorStack::get()) - } else { - Ok(()) - } -} - /// A borrowed SSL context object. pub struct SslContextRef<'a>(*mut ffi::SSL_CTX, PhantomData<&'a ()>); @@ -414,11 +404,15 @@ impl<'a> SslContextRef<'a> { } fn set_mode(&mut self, mode: c_long) -> Result<(), ErrorStack> { - wrap_ssl_result(unsafe { ffi::SSL_CTX_set_mode(self.as_ptr(), mode) as c_int }) + unsafe { + cvt(ffi::SSL_CTX_set_mode(self.as_ptr(), mode) as c_int).map(|_| ()) + } } pub fn set_tmp_dh(&mut self, dh: &DH) -> Result<(), ErrorStack> { - wrap_ssl_result(unsafe { ffi::SSL_CTX_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as i32 }) + unsafe { + cvt(ffi::SSL_CTX_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as i32).map(|_| ()) + } } /// Use the default locations of trusted certificates for verification. @@ -427,16 +421,21 @@ impl<'a> SslContextRef<'a> { /// environment variables if present, or defaults specified at OpenSSL /// build time otherwise. pub fn set_default_verify_paths(&mut self) -> Result<(), ErrorStack> { - wrap_ssl_result(unsafe { ffi::SSL_CTX_set_default_verify_paths(self.as_ptr()) }) + unsafe{ + cvt(ffi::SSL_CTX_set_default_verify_paths(self.as_ptr())).map(|_| ()) + } } #[allow(non_snake_case)] /// Specifies the file that contains trusted CA certificates. pub fn set_CA_file>(&mut self, file: P) -> Result<(), ErrorStack> { - let file = CString::new(file.as_ref().as_os_str().to_str().expect("invalid utf8")).unwrap(); - wrap_ssl_result(unsafe { - ffi::SSL_CTX_load_verify_locations(self.as_ptr(), file.as_ptr() as *const _, ptr::null()) - }) + let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap(); + unsafe { + cvt(ffi::SSL_CTX_load_verify_locations(self.as_ptr(), + file.as_ptr() as *const _, + ptr::null())) + .map(|_| ()) + } } /// Set the context identifier for sessions @@ -448,9 +447,13 @@ impl<'a> SslContextRef<'a> { /// This value should be set when using client certificates, or each request will fail /// handshake and need to be restarted. pub fn set_session_id_context(&mut self, sid_ctx: &[u8]) -> Result<(), ErrorStack> { - wrap_ssl_result(unsafe { - ffi::SSL_CTX_set_session_id_context(self.as_ptr(), sid_ctx.as_ptr(), sid_ctx.len() as u32) - }) + unsafe { + assert!(sid_ctx.len() <= c_uint::max_value() as usize); + cvt(ffi::SSL_CTX_set_session_id_context(self.as_ptr(), + sid_ctx.as_ptr(), + sid_ctx.len() as c_uint)) + .map(|_| ()) + } } /// Specifies the file that contains certificate @@ -458,40 +461,41 @@ impl<'a> SslContextRef<'a> { file: P, file_type: X509FileType) -> Result<(), ErrorStack> { - let file = CString::new(file.as_ref().as_os_str().to_str().expect("invalid utf8")).unwrap(); - wrap_ssl_result(unsafe { - ffi::SSL_CTX_use_certificate_file(self.as_ptr(), - file.as_ptr() as *const _, - file_type as c_int) - }) + let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap(); + unsafe { + cvt(ffi::SSL_CTX_use_certificate_file(self.as_ptr(), + file.as_ptr() as *const _, + file_type as c_int)) + .map(|_| ()) + } } /// Specifies the file that contains certificate chain pub fn set_certificate_chain_file>(&mut self, file: P) -> Result<(), ErrorStack> { - let file = CString::new(file.as_ref().as_os_str().to_str().expect("invalid utf8")).unwrap(); - wrap_ssl_result(unsafe { - ffi::SSL_CTX_use_certificate_chain_file(self.as_ptr(), - file.as_ptr() as *const _) - }) + let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap(); + unsafe { + cvt(ffi::SSL_CTX_use_certificate_chain_file(self.as_ptr(), + file.as_ptr() as *const _)) + .map(|_| ()) + } } /// Specifies the certificate pub fn set_certificate(&mut self, cert: &X509Ref) -> Result<(), ErrorStack> { - wrap_ssl_result(unsafe { ffi::SSL_CTX_use_certificate(self.as_ptr(), cert.as_ptr()) }) + unsafe { + cvt(ffi::SSL_CTX_use_certificate(self.as_ptr(), cert.as_ptr())).map(|_| ()) + } } /// Adds a certificate to the certificate chain presented together with the /// certificate specified using set_certificate() - pub fn add_extra_chain_cert(&mut self, cert: &X509Ref) -> Result<(), ErrorStack> { - // FIXME this should really just take an X509 by value - let der = try!(cert.to_der()); - let cert = try!(X509::from_der(&der)); + pub fn add_extra_chain_cert(&mut self, cert: X509) -> Result<(), ErrorStack> { unsafe { - try_ssl!(ffi::SSL_CTX_add_extra_chain_cert(self.as_ptr(), cert.as_ptr())); + try!(cvt(ffi::SSL_CTX_add_extra_chain_cert(self.as_ptr(), cert.as_ptr()) as c_int)); + mem::forget(cert); + Ok(()) } - mem::forget(cert); - Ok(()) } /// Specifies the file that contains private key @@ -499,29 +503,35 @@ impl<'a> SslContextRef<'a> { file: P, file_type: X509FileType) -> Result<(), ErrorStack> { - let file = CString::new(file.as_ref().as_os_str().to_str().expect("invalid utf8")).unwrap(); - wrap_ssl_result(unsafe { - ffi::SSL_CTX_use_PrivateKey_file(self.as_ptr(), - file.as_ptr() as *const _, - file_type as c_int) - }) + let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap(); + unsafe { + cvt(ffi::SSL_CTX_use_PrivateKey_file(self.as_ptr(), + file.as_ptr() as *const _, + file_type as c_int)) + .map(|_| ()) + } } /// Specifies the private key pub fn set_private_key(&mut self, key: &PKey) -> Result<(), ErrorStack> { - wrap_ssl_result(unsafe { ffi::SSL_CTX_use_PrivateKey(self.as_ptr(), key.as_ptr()) }) + unsafe { + cvt(ffi::SSL_CTX_use_PrivateKey(self.as_ptr(), key.as_ptr())).map(|_| ()) + } } /// Check consistency of private key and certificate pub fn check_private_key(&mut self) -> Result<(), ErrorStack> { - wrap_ssl_result(unsafe { ffi::SSL_CTX_check_private_key(self.as_ptr()) }) + unsafe { + cvt(ffi::SSL_CTX_check_private_key(self.as_ptr())).map(|_| ()) + } } pub fn set_cipher_list(&mut self, cipher_list: &str) -> Result<(), ErrorStack> { - wrap_ssl_result(unsafe { - let cipher_list = CString::new(cipher_list).unwrap(); - ffi::SSL_CTX_set_cipher_list(self.as_ptr(), cipher_list.as_ptr() as *const _) - }) + let cipher_list = CString::new(cipher_list).unwrap(); + unsafe { + cvt(ffi::SSL_CTX_set_cipher_list(self.as_ptr(), cipher_list.as_ptr() as *const _)) + .map(|_| ()) + } } /// If `onoff` is set to `true`, enable ECDHE for key exchange with @@ -539,12 +549,13 @@ impl<'a> SslContextRef<'a> { #[cfg(all(feature = "openssl-102", ossl102))] fn _set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> { - wrap_ssl_result(unsafe { - ffi::SSL_CTX_ctrl(self.as_ptr(), - ffi::SSL_CTRL_SET_ECDH_AUTO, - onoff as c_long, - ptr::null_mut()) as c_int - }) + unsafe { + cvt(ffi::SSL_CTX_ctrl(self.as_ptr(), + ffi::SSL_CTRL_SET_ECDH_AUTO, + onoff as c_long, + ptr::null_mut()) as c_int) + .map(|_| ()) + } } #[cfg(all(feature = "openssl-102", ossl110))] @@ -669,11 +680,10 @@ impl SslContext { init(); let mut ctx = unsafe { - let ctx = try_ssl_null!(ffi::SSL_CTX_new(method.as_ptr())); + let ctx = try!(cvt_p(ffi::SSL_CTX_new(method.as_ptr()))); SslContext::from_ptr(ctx) }; - // this is a bit dubious (?) try!(ctx.set_mode(ffi::SSL_MODE_AUTO_RETRY | ffi::SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)); Ok(ctx) @@ -692,9 +702,9 @@ impl SslContext { pub struct CipherBits { /// The number of secret bits used for the cipher. pub secret: i32, - /// The number of bits processed by the chosen algorithm, if not None. + + /// The number of bits processed by the chosen algorithm. pub algorithm: Option, - _p: (), } @@ -727,20 +737,11 @@ impl<'a> SslCipher<'a> { /// Returns the number of bits used for the cipher. pub fn bits(&self) -> CipherBits { unsafe { - let algo_bits: *mut c_int = ptr::null_mut(); - let secret_bits = ffi::SSL_CIPHER_get_bits(self.cipher, algo_bits); - if !algo_bits.is_null() { - CipherBits { - secret: secret_bits, - algorithm: Some(*algo_bits), - _p: (), - } - } else { - CipherBits { - secret: secret_bits, - algorithm: None, - _p: (), - } + let mut algo_bits = 0; + let secret_bits = ffi::SSL_CIPHER_get_bits(self.cipher, &mut algo_bits); + CipherBits { + secret: secret_bits.into(), + algorithm: algo_bits.into(), } } } @@ -875,15 +876,9 @@ impl<'a> SslRef<'a> { /// Sets the host name to be used with SNI (Server Name Indication). pub fn set_hostname(&mut self, hostname: &str) -> Result<(), ErrorStack> { let cstr = CString::new(hostname).unwrap(); - let ret = unsafe { - ffi::SSL_set_tlsext_host_name(self.as_ptr(), cstr.as_ptr() as *mut _) - }; - - // For this case, 0 indicates failure. - if ret == 0 { - Err(ErrorStack::get()) - } else { - Ok(()) + unsafe { + cvt(ffi::SSL_set_tlsext_host_name(self.as_ptr(), cstr.as_ptr() as *mut _) as c_int) + .map(|_| ()) } } @@ -999,9 +994,8 @@ impl<'a> SslRef<'a> { /// Changes the context corresponding to the current connection. pub fn set_ssl_context(&mut self, ctx: &SslContextRef) -> Result<(), ErrorStack> { unsafe { - try_ssl_null!(ffi::SSL_set_SSL_CTX(self.as_ptr(), ctx.as_ptr())); + cvt_p(ffi::SSL_set_SSL_CTX(self.as_ptr(), ctx.as_ptr())).map(|_| ()) } - Ok(()) } /// Returns the context corresponding to the current connection @@ -1056,7 +1050,7 @@ impl DerefMut for Ssl { impl Ssl { pub fn new(ctx: &SslContext) -> Result { unsafe { - let ssl = try_ssl_null!(ffi::SSL_new(ctx.as_ptr())); + let ssl = try!(cvt_p(ffi::SSL_new(ctx.as_ptr()))); Ok(Ssl::from_ptr(ssl)) } } diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index ac7505f8..2dd49cb0 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -1061,7 +1061,7 @@ fn add_extra_chain_cert() { let cert = include_bytes!("../../../test/cert.pem"); let cert = X509::from_pem(cert).unwrap(); let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); - ctx.add_extra_chain_cert(&cert).unwrap(); + ctx.add_extra_chain_cert(cert).unwrap(); } #[test] From 7ec015325b0d900ddaf375b62f5a52d4231dc9a2 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 16 Oct 2016 21:07:17 -0700 Subject: [PATCH 053/186] Finish error overhaul --- openssl/src/bio.rs | 5 +- openssl/src/bn.rs | 35 ++++++----- openssl/src/dh.rs | 37 +++++++----- openssl/src/macros.rs | 81 ------------------------- openssl/src/x509/mod.rs | 119 +++++++++++++++++-------------------- openssl/src/x509/verify.rs | 9 ++- 6 files changed, 101 insertions(+), 185 deletions(-) diff --git a/openssl/src/bio.rs b/openssl/src/bio.rs index 22d2cee3..199fc0c8 100644 --- a/openssl/src/bio.rs +++ b/openssl/src/bio.rs @@ -4,6 +4,7 @@ use std::slice; use libc::c_int; use ffi; +use cvt_p; use error::ErrorStack; pub struct MemBioSlice<'a>(*mut ffi::BIO, PhantomData<&'a [u8]>); @@ -22,7 +23,7 @@ impl<'a> MemBioSlice<'a> { assert!(buf.len() <= c_int::max_value() as usize); let bio = unsafe { - try_ssl_null!(BIO_new_mem_buf(buf.as_ptr() as *const _, buf.len() as c_int)) + try!(cvt_p(BIO_new_mem_buf(buf.as_ptr() as *const _, buf.len() as c_int))) }; Ok(MemBioSlice(bio, PhantomData)) @@ -48,7 +49,7 @@ impl MemBio { ffi::init(); let bio = unsafe { - try_ssl_null!(ffi::BIO_new(ffi::BIO_s_mem())) + try!(cvt_p(ffi::BIO_new(ffi::BIO_s_mem()))) }; Ok(MemBio(bio)) } diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs index 22924e67..62b30d96 100644 --- a/openssl/src/bn.rs +++ b/openssl/src/bn.rs @@ -408,7 +408,7 @@ impl<'a> BigNumRef<'a> { pub fn to_owned(&self) -> Result { unsafe { - let r = try_ssl_null!(ffi::BN_dup(self.as_ptr())); + let r = try!(cvt_p(ffi::BN_dup(self.as_ptr()))); Ok(BigNum::from_ptr(r)) } } @@ -553,7 +553,7 @@ impl BigNum { pub fn new() -> Result { unsafe { ffi::init(); - let v = try_ssl_null!(ffi::BN_new()); + let v = try!(cvt_p(ffi::BN_new())); Ok(BigNum::from_ptr(v)) } } @@ -561,27 +561,28 @@ impl BigNum { /// Creates a new `BigNum` with the given value. pub fn new_from(n: u32) -> Result { BigNum::new().and_then(|v| unsafe { - try_ssl!(ffi::BN_set_word(v.as_ptr(), n as ffi::BN_ULONG)); - Ok(v) + cvt(ffi::BN_set_word(v.as_ptr(), n as ffi::BN_ULONG)).map(|_| v) }) } /// Creates a `BigNum` from a decimal string. pub fn from_dec_str(s: &str) -> Result { - BigNum::new().and_then(|mut v| unsafe { + unsafe { let c_str = CString::new(s.as_bytes()).unwrap(); - try_ssl!(ffi::BN_dec2bn(&mut (v.0).0, c_str.as_ptr() as *const _)); - Ok(v) - }) + let mut bn = ptr::null_mut(); + try!(cvt(ffi::BN_dec2bn(&mut bn, c_str.as_ptr() as *const _))); + Ok(BigNum::from_ptr(bn)) + } } /// Creates a `BigNum` from a hexadecimal string. pub fn from_hex_str(s: &str) -> Result { - BigNum::new().and_then(|mut v| unsafe { + unsafe { let c_str = CString::new(s.as_bytes()).unwrap(); - try_ssl!(ffi::BN_hex2bn(&mut (v.0).0, c_str.as_ptr() as *const _)); - Ok(v) - }) + let mut bn = ptr::null_mut(); + try!(cvt(ffi::BN_hex2bn(&mut bn, c_str.as_ptr() as *const _))); + Ok(BigNum::from_ptr(bn)) + } } pub unsafe fn from_ptr(handle: *mut ffi::BIGNUM) -> BigNum { @@ -597,11 +598,13 @@ impl BigNum { /// assert_eq!(bignum, BigNum::new_from(0x120034).unwrap()); /// ``` pub fn new_from_slice(n: &[u8]) -> Result { - BigNum::new().and_then(|v| unsafe { - try_ssl_null!(ffi::BN_bin2bn(n.as_ptr(), n.len() as c_int, v.as_ptr())); - Ok(v) - }) + unsafe { + assert!(n.len() <= c_int::max_value() as usize); + cvt_p(ffi::BN_bin2bn(n.as_ptr(), n.len() as c_int, ptr::null_mut())) + .map(|p| BigNum::from_ptr(p)) + } } + /// Generates a prime number. /// /// # Parameters diff --git a/openssl/src/dh.rs b/openssl/src/dh.rs index 6d0800a1..fec6bd98 100644 --- a/openssl/src/dh.rs +++ b/openssl/src/dh.rs @@ -3,6 +3,7 @@ use error::ErrorStack; use bio::MemBioSlice; use std::ptr; +use {cvt, cvt_p}; use bn::BigNum; use std::mem; @@ -11,11 +12,11 @@ pub struct DH(*mut ffi::DH); impl DH { pub fn from_params(p: BigNum, g: BigNum, q: BigNum) -> Result { unsafe { - let dh = DH(try_ssl_null!(ffi::DH_new())); - try_ssl!(compat::DH_set0_pqg(dh.0, + let dh = DH(try!(cvt_p(ffi::DH_new()))); + try!(cvt(compat::DH_set0_pqg(dh.0, p.as_ptr(), q.as_ptr(), - g.as_ptr())); + g.as_ptr()))); mem::forget((p, g, q)); Ok(dh) } @@ -23,34 +24,38 @@ impl DH { pub fn from_pem(buf: &[u8]) -> Result { let mem_bio = try!(MemBioSlice::new(buf)); - let dh = unsafe { - ffi::PEM_read_bio_DHparams(mem_bio.as_ptr(), ptr::null_mut(), None, ptr::null_mut()) - }; - try_ssl_null!(dh); - Ok(DH(dh)) + unsafe { + cvt_p(ffi::PEM_read_bio_DHparams(mem_bio.as_ptr(), + ptr::null_mut(), + None, + ptr::null_mut())) + .map(DH) + } } #[cfg(feature = "openssl-102")] pub fn get_1024_160() -> Result { - let dh = try_ssl_null!(unsafe { ffi::DH_get_1024_160() }); - Ok(DH(dh)) + unsafe { + cvt_p(ffi::DH_get_1024_160()).map(DH) + } } #[cfg(feature = "openssl-102")] pub fn get_2048_224() -> Result { - let dh = try_ssl_null!(unsafe { ffi::DH_get_2048_224() }); - Ok(DH(dh)) + unsafe { + cvt_p(ffi::DH_get_2048_224()).map(DH) + } } #[cfg(feature = "openssl-102")] pub fn get_2048_256() -> Result { - let dh = try_ssl_null!(unsafe { ffi::DH_get_2048_256() }); - Ok(DH(dh)) + unsafe { + cvt_p(ffi::DH_get_2048_256()).map(DH) + } } pub unsafe fn as_ptr(&self) -> *mut ffi::DH { - let DH(n) = *self; - n + self.0 } } diff --git a/openssl/src/macros.rs b/openssl/src/macros.rs index 31c298fa..85175445 100644 --- a/openssl/src/macros.rs +++ b/openssl/src/macros.rs @@ -1,86 +1,5 @@ #![macro_use] -macro_rules! try_ssl_stream { - ($e:expr) => ( - match $e { - Ok(ok) => ok, - Err(err) => return Err(StreamError(err)) - } - ) -} - -/// Shortcut return with SSL error if something went wrong -macro_rules! try_ssl_if { - ($e:expr) => ( - if $e { - return Err(::error::ErrorStack::get().into()) - } - ) -} - -/// Shortcut return with SSL error if last error result is 0 -/// (default) -macro_rules! try_ssl{ - ($e:expr) => (try_ssl_if!($e == 0)) -} - -/// Shortcut return with SSL if got a null result -macro_rules! try_ssl_null{ - ($e:expr) => ({ - let t = $e; - try_ssl_if!(t == ptr::null_mut()); - t - }) -} - -/// Shortcut return with SSL error if last error result is -1 -/// (default for size) -macro_rules! try_ssl_returns_size{ - ($e:expr) => ( - if $e == -1 { - return Err(::error::ErrorStack::get().into()) - } else { - $e - } - ) -} - -/// Lifts current SSL error code into Result<(), Error> -/// if expression is true -/// Lifting is actually a shortcut of the following form: -/// -/// ```ignore -/// let _ = try!(something) -/// Ok(()) -/// ``` -macro_rules! lift_ssl_if{ - ($e:expr) => ( { - if $e { - Err(::error::ErrorStack::get().into()) - } else { - Ok(()) - } - }) -} - -/// Lifts current SSL error code into Result<(), Error> -/// if SSL returned 0 (default error indication) -macro_rules! lift_ssl { - ($e:expr) => (lift_ssl_if!($e == 0)) -} - -/// Lifts current SSL error code into Result<(), Error> -/// if SSL returned -1 (default size error indication) -macro_rules! lift_ssl_returns_size { - ($e:expr) => ( { - if $e == -1 { - Err(::error::ErrorStack::get().into()) - } else { - Ok($e) - } - }) -} - #[cfg(ossl10x)] macro_rules! CRYPTO_free { ($e:expr) => (::ffi::CRYPTO_free($e)) diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index c429b486..1cd7471f 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -10,6 +10,7 @@ use std::slice; use std::collections::HashMap; use std::marker::PhantomData; +use {cvt, cvt_p}; use asn1::Asn1Time; use asn1::Asn1TimeRef; use bio::{MemBio, MemBioSlice}; @@ -251,25 +252,25 @@ impl X509Generator { let value = CString::new(value.as_bytes()).unwrap(); let ext = match exttype.get_nid() { Some(nid) => { - ffi::X509V3_EXT_conf_nid(ptr::null_mut(), - mem::transmute(&ctx), - nid as c_int, - value.as_ptr() as *mut c_char) + try!(cvt_p(ffi::X509V3_EXT_conf_nid(ptr::null_mut(), + mem::transmute(&ctx), + nid as c_int, + value.as_ptr() as *mut c_char))) } None => { let name = CString::new(exttype.get_name().unwrap().as_bytes()).unwrap(); - ffi::X509V3_EXT_conf(ptr::null_mut(), - mem::transmute(&ctx), - name.as_ptr() as *mut c_char, - value.as_ptr() as *mut c_char) + try!(cvt_p(ffi::X509V3_EXT_conf(ptr::null_mut(), + mem::transmute(&ctx), + name.as_ptr() as *mut c_char, + value.as_ptr() as *mut c_char))) } }; - let mut success = false; - if ext != ptr::null_mut() { - success = ffi::X509_add_ext(x509, ext, -1) != 0; + if ffi::X509_add_ext(x509, ext, -1) != 1 { ffi::X509_EXTENSION_free(ext); + Err(ErrorStack::get()) + } else { + Ok(()) } - lift_ssl_if!(!success) } } @@ -278,17 +279,18 @@ impl X509Generator { value: &str) -> Result<(), ErrorStack> { let value_len = value.len() as c_int; - lift_ssl!(unsafe { + unsafe { let key = CString::new(key.as_bytes()).unwrap(); let value = CString::new(value.as_bytes()).unwrap(); - 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) - }) + 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 { @@ -308,32 +310,30 @@ impl X509Generator { } /// Sets the certificate public-key, then self-sign and return it - /// Note: That the bit-length of the private key is used (set_bitlength is ignored) pub fn sign(&self, p_key: &PKey) -> Result { ffi::init(); unsafe { - let x509 = try_ssl_null!(ffi::X509_new()); - let x509 = X509::from_ptr(x509); + let x509 = X509::from_ptr(try!(cvt_p(ffi::X509_new()))); - try_ssl!(ffi::X509_set_version(x509.as_ptr(), 2)); - try_ssl!(ffi::ASN1_INTEGER_set(ffi::X509_get_serialNumber(x509.as_ptr()), - try!(X509Generator::random_serial()))); + 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_ssl!(X509_set_notBefore(x509.as_ptr(), not_before.as_ptr() as *const _)); + 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); - try_ssl!(X509_set_notAfter(x509.as_ptr(), not_after.as_ptr() as *const _)); + 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); - try_ssl!(ffi::X509_set_pubkey(x509.as_ptr(), p_key.as_ptr())); + try!(cvt(ffi::X509_set_pubkey(x509.as_ptr(), p_key.as_ptr()))); - let name = try_ssl_null!(ffi::X509_get_subject_name(x509.as_ptr())); + let name = try!(cvt_p(ffi::X509_get_subject_name(x509.as_ptr()))); let default = [("CN", "rust-openssl")]; let default_iter = &mut default.iter().map(|&(k, v)| (k, v)); @@ -347,7 +347,7 @@ impl X509Generator { for (key, val) in iter { try!(X509Generator::add_name_internal(name, &key, &val)); } - try_ssl!(ffi::X509_set_issuer_name(x509.as_ptr(), name)); + try!(cvt(ffi::X509_set_issuer_name(x509.as_ptr(), name))); for (exttype, ext) in self.extensions.iter() { try!(X509Generator::add_extension_internal(x509.as_ptr(), @@ -356,7 +356,7 @@ impl X509Generator { } let hash_fn = self.hash_type.as_ptr(); - try_ssl!(ffi::X509_sign(x509.as_ptr(), p_key.as_ptr(), hash_fn)); + try!(cvt(ffi::X509_sign(x509.as_ptr(), p_key.as_ptr(), hash_fn))); Ok(x509) } } @@ -369,18 +369,20 @@ impl X509Generator { }; unsafe { - let req = ffi::X509_to_X509_REQ(cert.as_ptr(), ptr::null_mut(), ptr::null()); - try_ssl_null!(req); + let req = try!(cvt_p(ffi::X509_to_X509_REQ(cert.as_ptr(), + ptr::null_mut(), + ptr::null()))); + let req = X509Req::from_ptr(req); let exts = compat::X509_get0_extensions(cert.as_ptr()); if exts != ptr::null_mut() { - try_ssl!(ffi::X509_REQ_add_extensions(req, exts as *mut _)); + try!(cvt(ffi::X509_REQ_add_extensions(req.as_ptr(), exts as *mut _))); } let hash_fn = self.hash_type.as_ptr(); - try_ssl!(ffi::X509_REQ_sign(req, p_key.as_ptr(), hash_fn)); + try!(cvt(ffi::X509_REQ_sign(req.as_ptr(), p_key.as_ptr(), hash_fn))); - Ok(X509Req::new(req)) + Ok(req) } } } @@ -394,12 +396,6 @@ impl<'a> X509Ref<'a> { X509Ref(x509, PhantomData) } - /// - #[deprecated(note = "renamed to `X509::from_ptr`", since = "0.8.1")] - pub unsafe fn new(x509: *mut ffi::X509) -> X509Ref<'a> { - X509Ref::from_ptr(x509) - } - pub fn as_ptr(&self) -> *mut ffi::X509 { self.0 } @@ -429,7 +425,7 @@ impl<'a> X509Ref<'a> { pub fn public_key(&self) -> Result { unsafe { - let pkey = try_ssl_null!(ffi::X509_get_pubkey(self.0)); + let pkey = try!(cvt_p(ffi::X509_get_pubkey(self.0))); Ok(PKey::from_ptr(pkey)) } } @@ -440,7 +436,7 @@ impl<'a> X509Ref<'a> { let evp = hash_type.as_ptr(); let mut len = ffi::EVP_MAX_MD_SIZE; let mut buf = vec![0u8; len as usize]; - try_ssl!(ffi::X509_digest(self.0, evp, buf.as_mut_ptr() as *mut _, &mut len)); + try!(cvt(ffi::X509_digest(self.0, evp, buf.as_mut_ptr() as *mut _, &mut len))); buf.truncate(len as usize); Ok(buf) } @@ -468,7 +464,7 @@ impl<'a> X509Ref<'a> { pub fn to_pem(&self) -> Result, ErrorStack> { let mem_bio = try!(MemBio::new()); unsafe { - try_ssl!(ffi::PEM_write_bio_X509(mem_bio.as_ptr(), self.0)); + try!(cvt(ffi::PEM_write_bio_X509(mem_bio.as_ptr(), self.0))); } Ok(mem_bio.get_buf().to_owned()) } @@ -492,18 +488,12 @@ impl X509 { X509(X509Ref::from_ptr(x509)) } - /// - #[deprecated(note = "renamed to `X509::from_ptr`", since = "0.8.1")] - pub unsafe fn new(x509: *mut ffi::X509) -> X509 { - X509::from_ptr(x509) - } - /// Reads a certificate from DER. pub fn from_der(buf: &[u8]) -> Result { unsafe { let mut ptr = buf.as_ptr(); let len = cmp::min(buf.len(), c_long::max_value() as usize) as c_long; - let x509 = try_ssl_null!(ffi::d2i_X509(ptr::null_mut(), &mut ptr, len)); + let x509 = try!(cvt_p(ffi::d2i_X509(ptr::null_mut(), &mut ptr, len))); Ok(X509::from_ptr(x509)) } } @@ -512,10 +502,10 @@ impl X509 { pub fn from_pem(buf: &[u8]) -> Result { let mem_bio = try!(MemBioSlice::new(buf)); unsafe { - let handle = try_ssl_null!(ffi::PEM_read_bio_X509(mem_bio.as_ptr(), - ptr::null_mut(), - None, - ptr::null_mut())); + let handle = try!(cvt_p(ffi::PEM_read_bio_X509(mem_bio.as_ptr(), + ptr::null_mut(), + None, + ptr::null_mut()))); Ok(X509::from_ptr(handle)) } } @@ -582,8 +572,7 @@ impl<'x> X509Name<'x> { pub struct X509Req(*mut ffi::X509_REQ); impl X509Req { - /// Creates new from handle - pub unsafe fn new(handle: *mut ffi::X509_REQ) -> X509Req { + pub unsafe fn from_ptr(handle: *mut ffi::X509_REQ) -> X509Req { X509Req(handle) } @@ -595,11 +584,11 @@ impl X509Req { pub fn from_pem(buf: &[u8]) -> Result { let mem_bio = try!(MemBioSlice::new(buf)); unsafe { - let handle = try_ssl_null!(ffi::PEM_read_bio_X509_REQ(mem_bio.as_ptr(), - ptr::null_mut(), - None, - ptr::null_mut())); - Ok(X509Req::new(handle)) + let handle = try!(cvt_p(ffi::PEM_read_bio_X509_REQ(mem_bio.as_ptr(), + ptr::null_mut(), + None, + ptr::null_mut()))); + Ok(X509Req::from_ptr(handle)) } } diff --git a/openssl/src/x509/verify.rs b/openssl/src/x509/verify.rs index 0fc1df3a..87287875 100644 --- a/openssl/src/x509/verify.rs +++ b/openssl/src/x509/verify.rs @@ -32,11 +32,10 @@ impl<'a> X509VerifyParamRef<'a> { pub fn set_host(&mut self, host: &str) -> Result<(), ErrorStack> { unsafe { - try_ssl!(ffi::X509_VERIFY_PARAM_set1_host(self.0, - host.as_ptr() as *const _, - host.len())) + cvt(ffi::X509_VERIFY_PARAM_set1_host(self.0, + host.as_ptr() as *const _, + host.len())) + .map(|_| ()) } - - Ok(()) } } From 68954cfc51fac79d71ab9a3c2de5de23616f5626 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 16 Oct 2016 23:13:00 -0700 Subject: [PATCH 054/186] Finish BN overhaul --- openssl/src/bn.rs | 488 +++++++++++++++----------------------- openssl/src/crypto/rsa.rs | 2 +- 2 files changed, 196 insertions(+), 294 deletions(-) diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs index 62b30d96..512c58d3 100644 --- a/openssl/src/bn.rs +++ b/openssl/src/bn.rs @@ -22,59 +22,6 @@ pub enum RNGProperty { TwoMsbOne = 1, } -macro_rules! with_ctx( - ($name:ident, $action:block) => ({ - let $name = ffi::BN_CTX_new(); - if ($name).is_null() { - Err(ErrorStack::get()) - } else { - let r = $action; - ffi::BN_CTX_free($name); - r - } - }); -); - -macro_rules! with_bn( - ($name:ident, $action:block) => ({ - let tmp = BigNum::new(); - match tmp { - Ok($name) => { - if $action { - Ok($name) - } else { - Err(ErrorStack::get()) - } - }, - Err(err) => Err(err), - } - }); -); - -macro_rules! with_bn_in_ctx( - ($name:ident, $ctx_name:ident, $action:block) => ({ - let tmp = BigNum::new(); - match tmp { - Ok($name) => { - let $ctx_name = ffi::BN_CTX_new(); - if ($ctx_name).is_null() { - Err(ErrorStack::get()) - } else { - let r = - if $action { - Ok($name) - } else { - Err(ErrorStack::get()) - }; - ffi::BN_CTX_free($ctx_name); - r - } - }, - Err(err) => Err(err), - } - }); -); - /// A context object for `BigNum` operations. pub struct BnCtx(*mut ffi::BN_CTX); @@ -94,6 +41,34 @@ impl BnCtx { } } + /// Places the result of `a * b` in `r`. + pub fn mul(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + b: &BigNumRef) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mul(r.0, a.0, b.0, self.0)).map(|_| ()) + } + } + + /// Places the result of `a / b` in `dv` and `a mod b` in `rem`. + pub fn div(&mut self, + dv: Option<&mut BigNumRef>, + rem: Option<&mut BigNumRef>, + a: &BigNumRef, + b: &BigNumRef) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_div(dv.map(|b| b.0).unwrap_or(ptr::null_mut()), + rem.map(|b| b.0).unwrap_or(ptr::null_mut()), + a.0, + b.0, + self.0)) + .map(|_| ()) + } + } + /// Places the result of `a²` in `r`. pub fn sqr(&mut self, r: &mut BigNumRef, a: &BigNumRef) -> Result<(), ErrorStack> { unsafe { @@ -231,6 +206,34 @@ impl BnCtx { .map(|r| r != 0) } } + + /// Generates a cryptographically strong pseudo-random `BigNum`, placing it in `r`. + /// + /// # Parameters + /// + /// * `bits`: Length of the number in bits. + /// * `prop`: The desired properties of the number. + /// * `odd`: If `true`, the generated number will be odd. + pub fn rand(r: &mut BigNumRef, + bits: i32, + prop: RNGProperty, + odd: bool) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_rand(r.0, bits.into(), prop as c_int, odd as c_int)).map(|_| ()) + } + } + + /// The cryptographically weak counterpart to `checked_new_random`. + pub fn pseudo_rand(r: &mut BigNumRef, + bits: i32, + prop: RNGProperty, + odd: bool) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_pseudo_rand(r.0, bits.into(), prop as c_int, odd as c_int)).map(|_| ()) + } + } } /// A borrowed, signed, arbitrary-precision integer. @@ -350,82 +353,45 @@ impl<'a> BigNumRef<'a> { } } - pub fn checked_add(&self, a: &BigNumRef) -> Result { + /// Places `self + b` in `r`. + pub fn add(&self, r: &mut BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { unsafe { - with_bn!(r, { - ffi::BN_add(r.as_ptr(), self.as_ptr(), a.as_ptr()) == 1 - }) + cvt(ffi::BN_add(r.0, self.0, b.0)).map(|_| ()) } } - pub fn checked_sub(&self, a: &BigNumRef) -> Result { + /// Places `self - b` in `r`. + pub fn sub(&self, r: &mut BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { unsafe { - with_bn!(r, { - ffi::BN_sub(r.as_ptr(), self.as_ptr(), a.as_ptr()) == 1 - }) + cvt(ffi::BN_sub(r.0, self.0, b.0)).map(|_| ()) } } - pub fn checked_mul(&self, a: &BigNumRef) -> Result { + /// Places `self << n` in `r`. + pub fn lshift(&self, r: &mut BigNumRef, b: i32) -> Result<(), ErrorStack> { unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_mul(r.as_ptr(), self.as_ptr(), a.as_ptr(), ctx) == 1 - }) + cvt(ffi::BN_lshift(r.0, self.0, b.into())).map(|_| ()) } } - pub fn checked_div(&self, a: &BigNumRef) -> Result { + /// Places `self >> n` in `r`. + pub fn rshift(&self, r: &mut BigNumRef, n: i32) -> Result<(), ErrorStack> { unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_div(r.as_ptr(), ptr::null_mut(), self.as_ptr(), a.as_ptr(), ctx) == 1 - }) - } - } - - pub fn checked_mod(&self, a: &BigNumRef) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_div(ptr::null_mut(), r.as_ptr(), self.as_ptr(), a.as_ptr(), ctx) == 1 - }) - } - } - - pub fn checked_shl(&self, a: &i32) -> Result { - unsafe { - with_bn!(r, { - ffi::BN_lshift(r.as_ptr(), self.as_ptr(), *a as c_int) == 1 - }) - } - } - - pub fn checked_shr(&self, a: &i32) -> Result { - unsafe { - with_bn!(r, { - ffi::BN_rshift(r.as_ptr(), self.as_ptr(), *a as c_int) == 1 - }) + cvt(ffi::BN_rshift(r.0, self.0, n.into())).map(|_| ()) } } pub fn to_owned(&self) -> Result { unsafe { - let r = try!(cvt_p(ffi::BN_dup(self.as_ptr()))); - Ok(BigNum::from_ptr(r)) + cvt_p(ffi::BN_dup(self.0)).map(|b| BigNum::from_ptr(b)) } } - /// Inverts the sign of `self`. - /// - /// ``` - /// # use openssl::bn::BigNum; - /// let mut s = BigNum::new_from(8).unwrap(); - /// - /// s.negate(); - /// assert_eq!(s, -BigNum::new_from(8).unwrap()); - /// s.negate(); - /// assert_eq!(s, BigNum::new_from(8).unwrap()); - /// ``` - pub fn negate(&mut self) { - unsafe { ffi::BN_set_negative(self.as_ptr(), !self.is_negative() as c_int) } + /// Sets the sign of `self`. + pub fn set_negative(&mut self, negative: bool) { + unsafe { + ffi::BN_set_negative(self.0, negative as c_int) + } } /// Compare the absolute values of `self` and `oth`. @@ -433,14 +399,14 @@ impl<'a> BigNumRef<'a> { /// ``` /// # use openssl::bn::BigNum; /// # use std::cmp::Ordering; - /// let s = -BigNum::new_from(8).unwrap(); - /// let o = BigNum::new_from(8).unwrap(); + /// let s = -BigNum::from_u32(8).unwrap(); + /// let o = BigNum::from_u32(8).unwrap(); /// - /// assert_eq!(s.abs_cmp(&o), Ordering::Equal); + /// assert_eq!(s.ucmp(&o), Ordering::Equal); /// ``` - pub fn abs_cmp(&self, oth: &BigNumRef) -> Ordering { + pub fn ucmp(&self, oth: &BigNumRef) -> Ordering { unsafe { - let res = ffi::BN_ucmp(self.as_ptr(), oth.as_ptr()) as i32; + let res = ffi::BN_ucmp(self.as_ptr(), oth.as_ptr()); if res < 0 { Ordering::Less } else if res > 0 { @@ -485,11 +451,11 @@ impl<'a> BigNumRef<'a> { /// /// ``` /// # use openssl::bn::BigNum; - /// let s = -BigNum::new_from(4543).unwrap(); - /// let r = BigNum::new_from(4543).unwrap(); + /// let s = -BigNum::from_u32(4543).unwrap(); + /// let r = BigNum::from_u32(4543).unwrap(); /// /// let s_vec = s.to_vec(); - /// assert_eq!(BigNum::new_from_slice(&s_vec).unwrap(), r); + /// assert_eq!(BigNum::from_slice(&s_vec).unwrap(), r); /// ``` pub fn to_vec(&self) -> Vec { let size = self.num_bytes() as usize; @@ -505,18 +471,17 @@ impl<'a> BigNumRef<'a> { /// /// ``` /// # use openssl::bn::BigNum; - /// let s = -BigNum::new_from(12345).unwrap(); + /// let s = -BigNum::from_u32(12345).unwrap(); /// - /// assert_eq!(s.to_dec_str(), "-12345"); + /// assert_eq!(s.to_dec_str().unwrap(), "-12345"); /// ``` - pub fn to_dec_str(&self) -> String { + pub fn to_dec_str(&self) -> Result { unsafe { - let buf = ffi::BN_bn2dec(self.as_ptr()); - assert!(!buf.is_null()); + let buf = try!(cvt_p(ffi::BN_bn2dec(self.as_ptr()))); let str = String::from_utf8(CStr::from_ptr(buf as *const _).to_bytes().to_vec()) .unwrap(); CRYPTO_free!(buf as *mut c_void); - str + Ok(str) } } @@ -524,18 +489,17 @@ impl<'a> BigNumRef<'a> { /// /// ``` /// # use openssl::bn::BigNum; - /// let s = -BigNum::new_from(0x99ff).unwrap(); + /// let s = -BigNum::from_u32(0x99ff).unwrap(); /// - /// assert_eq!(s.to_hex_str(), "-99FF"); + /// assert_eq!(s.to_hex_str().unwrap(), "-99FF"); /// ``` - pub fn to_hex_str(&self) -> String { + pub fn to_hex_str(&self) -> Result { unsafe { - let buf = ffi::BN_bn2hex(self.as_ptr()); - assert!(!buf.is_null()); + let buf = try!(cvt_p(ffi::BN_bn2hex(self.as_ptr()))); let str = String::from_utf8(CStr::from_ptr(buf as *const _).to_bytes().to_vec()) .unwrap(); CRYPTO_free!(buf as *mut c_void); - str + Ok(str) } } } @@ -559,7 +523,7 @@ impl BigNum { } /// Creates a new `BigNum` with the given value. - pub fn new_from(n: u32) -> Result { + pub fn from_u32(n: u32) -> Result { BigNum::new().and_then(|v| unsafe { cvt(ffi::BN_set_word(v.as_ptr(), n as ffi::BN_ULONG)).map(|_| v) }) @@ -593,11 +557,11 @@ impl BigNum { /// /// ``` /// # use openssl::bn::BigNum; - /// let bignum = BigNum::new_from_slice(&[0x12, 0x00, 0x34]).unwrap(); + /// let bignum = BigNum::from_slice(&[0x12, 0x00, 0x34]).unwrap(); /// - /// assert_eq!(bignum, BigNum::new_from(0x120034).unwrap()); + /// assert_eq!(bignum, BigNum::from_u32(0x120034).unwrap()); /// ``` - pub fn new_from_slice(n: &[u8]) -> Result { + pub fn from_slice(n: &[u8]) -> Result { unsafe { assert!(n.len() <= c_int::max_value() as usize); cvt_p(ffi::BN_bin2bn(n.as_ptr(), n.len() as c_int, ptr::null_mut())) @@ -605,7 +569,7 @@ impl BigNum { } } - /// Generates a prime number. + /// Generates a prime number, placing it in `r`. /// /// # Parameters /// @@ -613,50 +577,20 @@ impl BigNum { /// * `safe`: If true, returns a "safe" prime `p` so that `(p-1)/2` is also prime. /// * `add`/`rem`: If `add` is set to `Some(add)`, `p % add == rem` will hold, where `p` is the /// generated prime and `rem` is `1` if not specified (`None`). - pub fn checked_generate_prime(bits: i32, - safe: bool, - add: Option<&BigNum>, - rem: Option<&BigNum>) - -> Result { + pub fn generate_prime(r: &mut BigNumRef, + bits: i32, + safe: bool, + add: Option<&BigNumRef>, + rem: Option<&BigNumRef>) + -> Result<(), ErrorStack> { unsafe { - with_bn_in_ctx!(r, ctx, { - let add_arg = add.map(|a| a.as_ptr()).unwrap_or(ptr::null_mut()); - let rem_arg = rem.map(|r| r.as_ptr()).unwrap_or(ptr::null_mut()); - - ffi::BN_generate_prime_ex(r.as_ptr(), + cvt(ffi::BN_generate_prime_ex(r.0, bits as c_int, safe as c_int, - add_arg, - rem_arg, - ptr::null_mut()) == 1 - }) - } - } - - /// Generates a cryptographically strong pseudo-random `BigNum`. - /// - /// # Parameters - /// - /// * `bits`: Length of the number in bits. - /// * `prop`: The desired properties of the number. - /// * `odd`: If `true`, the generated number will be odd. - pub fn checked_new_random(bits: i32, prop: RNGProperty, odd: bool) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_rand(r.as_ptr(), bits as c_int, prop as c_int, odd as c_int) == 1 - }) - } - } - - /// The cryptographically weak counterpart to `checked_new_random`. - pub fn checked_new_pseudo_random(bits: i32, - prop: RNGProperty, - odd: bool) - -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_pseudo_rand(r.as_ptr(), bits as c_int, prop as c_int, odd as c_int) == 1 - }) + add.map(|n| n.0).unwrap_or(ptr::null_mut()), + rem.map(|n| n.0).unwrap_or(ptr::null_mut()), + ptr::null_mut())) + .map(|_| ()) } } } @@ -689,31 +623,43 @@ impl AsRef> for BigNum { impl<'a> fmt::Debug for BigNumRef<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.to_dec_str()) + match self.to_dec_str() { + Ok(s) => f.write_str(&s), + Err(e) => Err(e.into()), + } } } impl fmt::Debug for BigNum { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.to_dec_str()) + match self.to_dec_str() { + Ok(s) => f.write_str(&s), + Err(e) => Err(e.into()), + } } } impl<'a> fmt::Display for BigNumRef<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.to_dec_str()) + match self.to_dec_str() { + Ok(s) => f.write_str(&s), + Err(e) => Err(e.into()), + } } } impl fmt::Display for BigNum { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.to_dec_str()) + match self.to_dec_str() { + Ok(s) => f.write_str(&s), + Err(e) => Err(e.into()), + } } } impl<'a, 'b> PartialEq> for BigNumRef<'a> { fn eq(&self, oth: &BigNumRef) -> bool { - unsafe { ffi::BN_cmp(self.as_ptr(), oth.as_ptr()) == 0 } + self.cmp(oth) == Ordering::Equal } } @@ -775,147 +721,104 @@ impl Ord for BigNum { } } +macro_rules! delegate { + ($t:ident, $m:ident) => { + impl<'a, 'b> $t<&'b BigNum> for &'a BigNumRef<'a> { + type Output = BigNum; + + fn $m(self, oth: &BigNum) -> BigNum { + $t::$m(self, oth.deref()) + } + } + + impl<'a, 'b> $t<&'b BigNumRef<'b>> for &'a BigNum { + type Output = BigNum; + + fn $m(self, oth: &BigNumRef) -> BigNum { + $t::$m(self.deref(), oth) + } + } + + impl<'a, 'b> $t<&'b BigNum> for &'a BigNum { + type Output = BigNum; + + fn $m(self, oth: &BigNum) -> BigNum { + $t::$m(self.deref(), oth.deref()) + } + } + } +} + impl<'a, 'b> Add<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { type Output = BigNum; fn add(self, oth: &BigNumRef) -> BigNum { - self.checked_add(oth).unwrap() + let mut r = BigNum::new().unwrap(); + self.add(&mut r, oth).unwrap(); + r } } +delegate!(Add, add); + impl<'a, 'b> Sub<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { type Output = BigNum; fn sub(self, oth: &BigNumRef) -> BigNum { - self.checked_sub(oth).unwrap() + let mut r = BigNum::new().unwrap(); + self.sub(&mut r, oth).unwrap(); + r } } -impl<'a, 'b> Sub<&'b BigNum> for &'a BigNumRef<'a> { - type Output = BigNum; - - fn sub(self, oth: &BigNum) -> BigNum { - self.checked_sub(oth).unwrap() - } -} - -impl<'a, 'b> Sub<&'b BigNum> for &'a BigNum { - type Output = BigNum; - - fn sub(self, oth: &BigNum) -> BigNum { - self.checked_sub(oth).unwrap() - } -} - -impl<'a, 'b> Sub<&'b BigNumRef<'b>> for &'a BigNum { - type Output = BigNum; - - fn sub(self, oth: &BigNumRef) -> BigNum { - self.checked_sub(oth).unwrap() - } -} +delegate!(Sub, sub); impl<'a, 'b> Mul<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { type Output = BigNum; fn mul(self, oth: &BigNumRef) -> BigNum { - self.checked_mul(oth).unwrap() + let mut ctx = BnCtx::new().unwrap(); + let mut r = BigNum::new().unwrap(); + ctx.mul(&mut r, self, oth).unwrap(); + r } } -impl<'a, 'b> Mul<&'b BigNum> for &'a BigNumRef<'a> { - type Output = BigNum; - - fn mul(self, oth: &BigNum) -> BigNum { - self.checked_mul(oth).unwrap() - } -} - -impl<'a, 'b> Mul<&'b BigNum> for &'a BigNum { - type Output = BigNum; - - fn mul(self, oth: &BigNum) -> BigNum { - self.checked_mul(oth).unwrap() - } -} - -impl<'a, 'b> Mul<&'b BigNumRef<'b>> for &'a BigNum { - type Output = BigNum; - - fn mul(self, oth: &BigNumRef) -> BigNum { - self.checked_mul(oth).unwrap() - } -} +delegate!(Mul, mul); impl<'a, 'b> Div<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { type Output = BigNum; fn div(self, oth: &'b BigNumRef<'b>) -> BigNum { - self.checked_div(oth).unwrap() + let mut ctx = BnCtx::new().unwrap(); + let mut dv = BigNum::new().unwrap(); + ctx.div(Some(&mut dv), None, self, oth).unwrap(); + dv } } -impl<'a, 'b> Div<&'b BigNum> for &'a BigNumRef<'a> { - type Output = BigNum; - - fn div(self, oth: &'b BigNum) -> BigNum { - self.checked_div(oth).unwrap() - } -} - -impl<'a, 'b> Div<&'b BigNum> for &'a BigNum { - type Output = BigNum; - - fn div(self, oth: &'b BigNum) -> BigNum { - self.checked_div(oth).unwrap() - } -} - -impl<'a, 'b> Div<&'b BigNumRef<'b>> for &'a BigNum { - type Output = BigNum; - - fn div(self, oth: &'b BigNumRef<'b>) -> BigNum { - self.checked_div(oth).unwrap() - } -} +delegate!(Div, div); impl<'a, 'b> Rem<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { type Output = BigNum; fn rem(self, oth: &'b BigNumRef<'b>) -> BigNum { - self.checked_mod(oth).unwrap() + let mut ctx = BnCtx::new().unwrap(); + let mut rem = BigNum::new().unwrap(); + ctx.div(None, Some(&mut rem), self, oth).unwrap(); + rem } } -impl<'a, 'b> Rem<&'b BigNum> for &'a BigNumRef<'a> { - type Output = BigNum; - - fn rem(self, oth: &'b BigNum) -> BigNum { - self.checked_mod(oth).unwrap() - } -} - -impl<'a, 'b> Rem<&'b BigNumRef<'b>> for &'a BigNum { - type Output = BigNum; - - fn rem(self, oth: &'b BigNumRef<'b>) -> BigNum { - self.checked_mod(oth).unwrap() - } -} - -impl<'a, 'b> Rem<&'b BigNum> for &'a BigNum { - type Output = BigNum; - - fn rem(self, oth: &'b BigNum) -> BigNum { - self.checked_mod(oth).unwrap() - } -} +delegate!(Rem, rem); impl<'a> Shl for &'a BigNumRef<'a> { type Output = BigNum; fn shl(self, n: i32) -> BigNum { - self.checked_shl(&n).unwrap() + let mut r = BigNum::new().unwrap(); + self.lshift(&mut r, n).unwrap(); + r } } @@ -923,7 +826,7 @@ impl<'a> Shl for &'a BigNum { type Output = BigNum; fn shl(self, n: i32) -> BigNum { - self.checked_shl(&n).unwrap() + self.deref().shl(n) } } @@ -931,7 +834,9 @@ impl<'a> Shr for &'a BigNumRef<'a> { type Output = BigNum; fn shr(self, n: i32) -> BigNum { - self.checked_shr(&n).unwrap() + let mut r = BigNum::new().unwrap(); + self.rshift(&mut r, n).unwrap(); + r } } @@ -939,7 +844,7 @@ impl<'a> Shr for &'a BigNum { type Output = BigNum; fn shr(self, n: i32) -> BigNum { - self.checked_shr(&n).unwrap() + self.deref().shl(n) } } @@ -947,9 +852,7 @@ impl<'a> Neg for &'a BigNumRef<'a> { type Output = BigNum; fn neg(self) -> BigNum { - let mut n = self.to_owned().unwrap(); - n.negate(); - n + self.to_owned().unwrap().neg() } } @@ -957,9 +860,7 @@ impl<'a> Neg for &'a BigNum { type Output = BigNum; fn neg(self) -> BigNum { - let mut n = self.deref().to_owned().unwrap(); - n.negate(); - n + self.deref().neg() } } @@ -967,7 +868,8 @@ impl Neg for BigNum { type Output = BigNum; fn neg(mut self) -> BigNum { - self.negate(); + let negative = self.is_negative(); + self.set_negative(!negative); self } } @@ -978,26 +880,26 @@ mod tests { #[test] fn test_to_from_slice() { - let v0 = BigNum::new_from(10203004).unwrap(); + let v0 = BigNum::from_u32(10203004).unwrap(); let vec = v0.to_vec(); - let v1 = BigNum::new_from_slice(&vec).unwrap(); + let v1 = BigNum::from_slice(&vec).unwrap(); assert!(v0 == v1); } #[test] fn test_negation() { - let a = BigNum::new_from(909829283).unwrap(); + let a = BigNum::from_u32(909829283).unwrap(); assert!(!a.is_negative()); assert!((-a).is_negative()); } - #[test] fn test_prime_numbers() { - let a = BigNum::new_from(19029017).unwrap(); - let p = BigNum::checked_generate_prime(128, true, None, Some(&a)).unwrap(); + let a = BigNum::from_u32(19029017).unwrap(); + let mut p = BigNum::new().unwrap(); + BigNum::generate_prime(&mut p, 128, true, None, Some(&a)).unwrap(); let mut ctx = BnCtx::new().unwrap(); assert!(ctx.is_prime(&p, 100).unwrap()); diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index 95675abe..a6a4f2b7 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -85,7 +85,7 @@ impl RSA { pub fn generate(bits: u32) -> Result { unsafe { let rsa = RSA(try!(cvt_p(ffi::RSA_new()))); - let e = try!(BigNum::new_from(ffi::RSA_F4 as u32)); + let e = try!(BigNum::from_u32(ffi::RSA_F4 as u32)); try!(cvt(ffi::RSA_generate_key_ex(rsa.0, bits as c_int, e.as_ptr(), ptr::null_mut()))); Ok(rsa) } From b7400d56e885d61e33da31f0d11286615692ca21 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 16 Oct 2016 23:22:00 -0700 Subject: [PATCH 055/186] Fix algorithm field --- openssl/src/ssl/mod.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 55955753..ad21e563 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -704,10 +704,9 @@ pub struct CipherBits { pub secret: i32, /// The number of bits processed by the chosen algorithm. - pub algorithm: Option, + pub algorithm: i32, } - pub struct SslCipher<'a> { cipher: *const ffi::SSL_CIPHER, ph: PhantomData<&'a ()>, From a938a001a7f64a9934b88e24f9c4115b1d0bebf6 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 16 Oct 2016 23:26:38 -0700 Subject: [PATCH 056/186] Fix missing import --- openssl/src/x509/verify.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/openssl/src/x509/verify.rs b/openssl/src/x509/verify.rs index 87287875..5cce9bd7 100644 --- a/openssl/src/x509/verify.rs +++ b/openssl/src/x509/verify.rs @@ -2,6 +2,7 @@ use std::marker::PhantomData; use libc::c_uint; use ffi; +use cvt; use error::ErrorStack; bitflags! { From 194298a057bad2b79e45ef346a0e6f37f8bc0716 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 17 Oct 2016 21:21:09 -0700 Subject: [PATCH 057/186] Implement new feature setup The basic idea here is that there is a feature for each supported OpenSSL version. Enabling multiple features represents support for multiple OpenSSL versions, but it's then up to you to check which version you link against (probably by depending on openssl-sys and making a build script similar to what openssl does). --- openssl/Cargo.toml | 5 ++-- openssl/build.rs | 13 ++++------- openssl/src/dh.rs | 11 +++++---- openssl/src/ssl/mod.rs | 45 +++++++++++++++--------------------- openssl/src/ssl/tests/mod.rs | 24 +++++++++---------- openssl/src/x509/mod.rs | 2 +- openssl/src/x509/verify.rs | 7 +++++- openssl/test/run.sh | 4 ++-- 8 files changed, 54 insertions(+), 57 deletions(-) diff --git a/openssl/Cargo.toml b/openssl/Cargo.toml index 3845c51d..4891d79b 100644 --- a/openssl/Cargo.toml +++ b/openssl/Cargo.toml @@ -12,8 +12,9 @@ build = "build.rs" exclude = ["test/*"] [features] -openssl-102 = [] -openssl-110 = ["openssl-102"] +v101 = [] +v102 = [] +v110 = [] [dependencies] bitflags = "0.7" diff --git a/openssl/build.rs b/openssl/build.rs index 8bb113ac..cd1dc3ec 100644 --- a/openssl/build.rs +++ b/openssl/build.rs @@ -4,20 +4,17 @@ fn main() { if env::var("DEP_OPENSSL_IS_110").is_ok() { println!("cargo:rustc-cfg=ossl110"); return; - } else if cfg!(feature = "openssl-110") { - panic!("the openssl-110 feature is enabled but OpenSSL 1.1.0+ is not being linked against"); - } - if env::var("DEP_OPENSSL_IS_102").is_ok() { + } else if env::var("DEP_OPENSSL_IS_102").is_ok() { println!("cargo:rustc-cfg=ossl102"); println!("cargo:rustc-cfg=ossl10x"); return; - } else if cfg!(feature = "openssl-102") { - panic!("the openssl-102 feature is enabled but OpenSSL 1.0.2+") - } - if env::var("DEP_OPENSSL_IS_101").is_ok() { + } else if env::var("DEP_OPENSSL_IS_101").is_ok() { println!("cargo:rustc-cfg=ossl101"); println!("cargo:rustc-cfg=ossl10x"); + } else { + panic!("Unable to detect OpenSSL version"); } + if let Ok(vars) = env::var("DEP_OPENSSL_OSSLCONF") { for var in vars.split(",") { println!("cargo:rustc-cfg=osslconf=\"{}\"", var); diff --git a/openssl/src/dh.rs b/openssl/src/dh.rs index fec6bd98..3b06951e 100644 --- a/openssl/src/dh.rs +++ b/openssl/src/dh.rs @@ -33,21 +33,24 @@ impl DH { } } - #[cfg(feature = "openssl-102")] + /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] pub fn get_1024_160() -> Result { unsafe { cvt_p(ffi::DH_get_1024_160()).map(DH) } } - #[cfg(feature = "openssl-102")] + /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] pub fn get_2048_224() -> Result { unsafe { cvt_p(ffi::DH_get_2048_224()).map(DH) } } - #[cfg(feature = "openssl-102")] + /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] pub fn get_2048_256() -> Result { unsafe { cvt_p(ffi::DH_get_2048_256()).map(DH) @@ -96,7 +99,7 @@ mod tests { use ssl::{SslMethod, SslContext}; #[test] - #[cfg(feature = "openssl-102")] + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn test_dh_rfc5114() { let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); let dh1 = DH::get_1024_160().unwrap(); diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index ad21e563..11ecd32d 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -22,7 +22,7 @@ use ffi; use {init, cvt, cvt_p}; use dh::DH; use x509::{X509StoreContext, X509FileType, X509, X509Ref}; -#[cfg(feature = "openssl-102")] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] use x509::verify::X509VerifyParamRef; use crypto::pkey::PKey; use error::ErrorStack; @@ -67,11 +67,14 @@ bitflags! { const SSL_OP_NO_TLSV1 = ffi::SSL_OP_NO_TLSv1, const SSL_OP_NO_TLSV1_2 = ffi::SSL_OP_NO_TLSv1_2, const SSL_OP_NO_TLSV1_1 = ffi::SSL_OP_NO_TLSv1_1, - #[cfg(feature = "openssl-102")] + /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] const SSL_OP_NO_DTLSV1 = ffi::SSL_OP_NO_DTLSv1, - #[cfg(feature = "openssl-102")] + /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] const SSL_OP_NO_DTLSV1_2 = ffi::SSL_OP_NO_DTLSv1_2, - #[cfg(feature = "openssl-102")] + /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] const SSL_OP_NO_SSL_MASK = ffi::SSL_OP_NO_SSL_MASK, } } @@ -133,7 +136,8 @@ fn get_ssl_verify_data_idx() -> c_int { lazy_static! { static ref NPN_PROTOS_IDX: c_int = get_new_idx::>(); } -#[cfg(feature = "openssl-102")] + +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] lazy_static! { static ref ALPN_PROTOS_IDX: c_int = get_new_idx::>(); } @@ -276,7 +280,7 @@ extern fn raw_next_proto_select_cb(ssl: *mut ffi::SSL, unsafe { select_proto_using(ssl, out, outlen, inbuf, inlen, *NPN_PROTOS_IDX) } } -#[cfg(feature = "openssl-102")] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] extern fn raw_alpn_select_cb(ssl: *mut ffi::SSL, out: *mut *const c_uchar, outlen: *mut c_uchar, @@ -538,17 +542,9 @@ impl<'a> SslContextRef<'a> { /// compatible clients, and automatically select an appropriate elliptic /// curve. /// - /// This feature is always enabled on OpenSSL 1.1.0, and calling this - /// method does nothing. - /// - /// This method requires the `openssl-102` feature. - #[cfg(feature = "openssl-102")] + /// Requires the `v102` feature and OpenSSL 1.0.2. + #[cfg(all(feature = "v102", ossl102))] pub fn set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> { - self._set_ecdh_auto(onoff) - } - - #[cfg(all(feature = "openssl-102", ossl102))] - fn _set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> { unsafe { cvt(ffi::SSL_CTX_ctrl(self.as_ptr(), ffi::SSL_CTRL_SET_ECDH_AUTO, @@ -558,11 +554,6 @@ impl<'a> SslContextRef<'a> { } } - #[cfg(all(feature = "openssl-102", ossl110))] - fn _set_ecdh_auto(&mut self, _onoff: bool) -> Result<(), ErrorStack> { - Ok(()) - } - pub fn set_options(&mut self, option: SslContextOptions) -> SslContextOptions { let ret = unsafe { compat::SSL_CTX_set_options(self.as_ptr(), option.bits()) }; SslContextOptions::from_bits(ret).unwrap() @@ -610,8 +601,8 @@ impl<'a> SslContextRef<'a> { /// /// Note that ordering of the protocols controls the priority with which they are chosen. /// - /// This method needs the `openssl-102` feature. - #[cfg(feature = "openssl-102")] + /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] pub fn set_alpn_protocols(&mut self, protocols: &[&[u8]]) { let protocols: Box> = Box::new(ssl_encode_byte_strings(protocols)); unsafe { @@ -928,8 +919,8 @@ impl<'a> SslRef<'a> { /// The protocol's name is returned is an opaque sequence of bytes. It is up to the client /// to interpret it. /// - /// This method needs the `alpn` feature. - #[cfg(feature = "openssl-102")] + /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] pub fn selected_alpn_protocol(&self) -> Option<&[u8]> { unsafe { let mut data: *const c_uchar = ptr::null(); @@ -1007,8 +998,8 @@ impl<'a> SslRef<'a> { /// Returns the X509 verification configuration. /// - /// Requires the `openssl-102` feature. - #[cfg(feature = "openssl-102")] + /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or 1.1.0. + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] pub fn param(&mut self) -> X509VerifyParamRef<'a> { unsafe { X509VerifyParamRef::from_ptr(ffi::SSL_get0_param(self.as_ptr())) diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 2dd49cb0..051a12f5 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -20,12 +20,12 @@ use ssl::SSL_VERIFY_PEER; use ssl::{SslMethod, HandshakeError}; use ssl::error::Error; use ssl::{SslContext, SslStream}; -#[cfg(feature = "openssl-102")] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] use ssl::IntoSsl; use x509::X509StoreContext; use x509::X509FileType; use x509::X509; -#[cfg(feature = "openssl-102")] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] use x509::verify::X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS; use crypto::pkey::PKey; @@ -509,7 +509,7 @@ fn test_state() { /// Tests that connecting with the client using ALPN, but the server not does not /// break the existing connection behavior. #[test] -#[cfg(feature = "openssl-102")] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn test_connect_with_unilateral_alpn() { let (_s, stream) = Server::new(); let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); @@ -552,7 +552,7 @@ fn test_connect_with_unilateral_npn() { /// Tests that when both the client as well as the server use ALPN and their /// lists of supported protocols have an overlap, the correct protocol is chosen. #[test] -#[cfg(feature = "openssl-102")] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn test_connect_with_alpn_successful_multiple_matching() { let (_s, stream) = Server::new_alpn(); let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); @@ -574,7 +574,7 @@ fn test_connect_with_alpn_successful_multiple_matching() { /// Tests that when both the client as well as the server use NPN and their /// lists of supported protocols have an overlap, the correct protocol is chosen. #[test] -#[cfg(feature = "openssl-102")] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn test_connect_with_npn_successful_multiple_matching() { let (_s, stream) = Server::new_alpn(); let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); @@ -597,7 +597,7 @@ fn test_connect_with_npn_successful_multiple_matching() { /// lists of supported protocols have an overlap -- with only ONE protocol /// being valid for both. #[test] -#[cfg(feature = "openssl-102")] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn test_connect_with_alpn_successful_single_match() { let (_s, stream) = Server::new_alpn(); let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); @@ -621,7 +621,7 @@ fn test_connect_with_alpn_successful_single_match() { /// lists of supported protocols have an overlap -- with only ONE protocol /// being valid for both. #[test] -#[cfg(feature = "openssl-102")] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn test_connect_with_npn_successful_single_match() { let (_s, stream) = Server::new_alpn(); let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); @@ -683,7 +683,7 @@ fn test_npn_server_advertise_multiple() { /// Tests that when the `SslStream` is created as a server stream, the protocols /// are correctly advertised to the client. #[test] -#[cfg(feature = "openssl-102")] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn test_alpn_server_advertise_multiple() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let localhost = listener.local_addr().unwrap(); @@ -724,7 +724,7 @@ fn test_alpn_server_advertise_multiple() { /// Test that Servers supporting ALPN don't report a protocol when none of their protocols match /// the client's reported protocol. #[test] -#[cfg(all(feature = "openssl-102", ossl102))] +#[cfg(all(feature = "v102", ossl102))] fn test_alpn_server_select_none() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let localhost = listener.local_addr().unwrap(); @@ -759,7 +759,7 @@ fn test_alpn_server_select_none() { // In 1.1.0, ALPN negotiation failure is a fatal error #[test] -#[cfg(all(feature = "openssl-102", ossl110))] +#[cfg(all(feature = "v110", ossl110))] fn test_alpn_server_select_none() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let localhost = listener.local_addr().unwrap(); @@ -1066,7 +1066,7 @@ fn add_extra_chain_cert() { #[test] #[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( -#[cfg(feature = "openssl-102")] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn valid_hostname() { let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_default_verify_paths().unwrap(); @@ -1090,7 +1090,7 @@ fn valid_hostname() { #[test] #[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( -#[cfg(feature = "openssl-102")] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn invalid_hostname() { let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_default_verify_paths().unwrap(); diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 1cd7471f..e801b1da 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -36,7 +36,7 @@ use ffi::{ pub mod extension; -#[cfg(feature = "openssl-102")] +#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] pub mod verify; use self::extension::{ExtensionType, Extension}; diff --git a/openssl/src/x509/verify.rs b/openssl/src/x509/verify.rs index 5cce9bd7..be8d3d7e 100644 --- a/openssl/src/x509/verify.rs +++ b/openssl/src/x509/verify.rs @@ -1,3 +1,7 @@ +//! X509 certificate verification +//! +//! Requires the `v102` or `v110` features and OpenSSL 1.0.2 or 1.1.0. + use std::marker::PhantomData; use libc::c_uint; use ffi; @@ -13,7 +17,8 @@ bitflags! { const X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS = ffi::X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS, const X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS = ffi::X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS, - #[cfg(feature = "openssl-110")] + /// Requires the `v110` feature and OpenSSL 1.1.0. + #[cfg(all(feature = "v110", ossl110))] const X509_CHECK_FLAG_NEVER_CHECK_SUBJECT = ffi::X509_CHECK_FLAG_NEVER_CHECK_SUBJECT, } } diff --git a/openssl/test/run.sh b/openssl/test/run.sh index cd422db7..4d3397a6 100755 --- a/openssl/test/run.sh +++ b/openssl/test/run.sh @@ -3,10 +3,10 @@ set -e case "$BUILD_OPENSSL_VERSION" in 1.0.2*) - FEATURES="openssl-102" + FEATURES="v102" ;; 1.1.0*) - FEATURES="openssl-110" + FEATURES="v110" ;; esac From f7e6d7fce60baa8cb4f1b3351f0b3fee40c42eab Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 18 Oct 2016 21:05:37 -0700 Subject: [PATCH 058/186] Don't ignore errors in NPN/ALPN logic Closes #479 --- openssl/src/ssl/mod.rs | 23 ++++++++++++++++++----- openssl/src/ssl/tests/mod.rs | 28 ++++++++++++++-------------- 2 files changed, 32 insertions(+), 19 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 11ecd32d..cd7fe7b9 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -571,7 +571,7 @@ impl<'a> SslContextRef<'a> { /// Set the protocols to be used during Next Protocol Negotiation (the protocols /// supported by the application). - pub fn set_npn_protocols(&mut self, protocols: &[&[u8]]) { + pub fn set_npn_protocols(&mut self, protocols: &[&[u8]]) -> Result<(), ErrorStack> { // Firstly, convert the list of protocols to a byte-array that can be passed to OpenSSL // APIs -- a list of length-prefixed strings. let protocols: Box> = Box::new(ssl_encode_byte_strings(protocols)); @@ -579,7 +579,9 @@ impl<'a> SslContextRef<'a> { unsafe { // Attach the protocol list to the OpenSSL context structure, // so that we can refer to it within the callback. - ffi::SSL_CTX_set_ex_data(self.as_ptr(), *NPN_PROTOS_IDX, mem::transmute(protocols)); + try!(cvt(ffi::SSL_CTX_set_ex_data(self.as_ptr(), + *NPN_PROTOS_IDX, + Box::into_raw(protocols) as *mut c_void))); // Now register the callback that performs the default protocol // matching based on the client-supported list of protocols that // has been saved. @@ -591,6 +593,7 @@ impl<'a> SslContextRef<'a> { ffi::SSL_CTX_set_next_protos_advertised_cb(self.as_ptr(), raw_next_protos_advertise_cb, ptr::null_mut()); + Ok(()) } } @@ -603,22 +606,32 @@ impl<'a> SslContextRef<'a> { /// /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - pub fn set_alpn_protocols(&mut self, protocols: &[&[u8]]) { + pub fn set_alpn_protocols(&mut self, protocols: &[&[u8]]) -> Result<(), ErrorStack> { let protocols: Box> = Box::new(ssl_encode_byte_strings(protocols)); unsafe { // Set the context's internal protocol list for use if we are a server - ffi::SSL_CTX_set_alpn_protos(self.as_ptr(), protocols.as_ptr(), protocols.len() as c_uint); + let r = ffi::SSL_CTX_set_alpn_protos(self.as_ptr(), + protocols.as_ptr(), + protocols.len() as c_uint); + // fun fact, SSL_CTX_set_alpn_protos has a reversed return code D: + if r != 0 { + return Err(ErrorStack::get()); + } // Rather than use the argument to the callback to contain our data, store it in the // ssl ctx's ex_data so that we can configure a function to free it later. In the // future, it might make sense to pull this into our internal struct Ssl instead of // leaning on openssl and using function pointers. - ffi::SSL_CTX_set_ex_data(self.as_ptr(), *ALPN_PROTOS_IDX, mem::transmute(protocols)); + try!(cvt(ffi::SSL_CTX_set_ex_data(self.as_ptr(), + *ALPN_PROTOS_IDX, + Box::into_raw(protocols) as *mut c_void))); // Now register the callback that performs the default protocol // matching based on the client-supported list of protocols that // has been saved. ffi::SSL_CTX_set_alpn_select_cb(self.as_ptr(), raw_alpn_select_cb, ptr::null_mut()); + + Ok(()) } } } diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 051a12f5..966df3c5 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -514,7 +514,7 @@ fn test_connect_with_unilateral_alpn() { let (_s, stream) = Server::new(); let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]); + ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), @@ -535,7 +535,7 @@ fn test_connect_with_unilateral_npn() { let (_s, stream) = Server::new(); let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]); + ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), @@ -557,7 +557,7 @@ fn test_connect_with_alpn_successful_multiple_matching() { let (_s, stream) = Server::new_alpn(); let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_alpn_protocols(&[b"spdy/3.1", b"http/1.1"]); + ctx.set_alpn_protocols(&[b"spdy/3.1", b"http/1.1"]).unwrap(); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), @@ -579,7 +579,7 @@ fn test_connect_with_npn_successful_multiple_matching() { let (_s, stream) = Server::new_alpn(); let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_npn_protocols(&[b"spdy/3.1", b"http/1.1"]); + ctx.set_npn_protocols(&[b"spdy/3.1", b"http/1.1"]).unwrap(); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), @@ -602,7 +602,7 @@ fn test_connect_with_alpn_successful_single_match() { let (_s, stream) = Server::new_alpn(); let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_alpn_protocols(&[b"spdy/3.1"]); + ctx.set_alpn_protocols(&[b"spdy/3.1"]).unwrap(); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), @@ -626,7 +626,7 @@ fn test_connect_with_npn_successful_single_match() { let (_s, stream) = Server::new_alpn(); let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_npn_protocols(&[b"spdy/3.1"]); + ctx.set_npn_protocols(&[b"spdy/3.1"]).unwrap(); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), @@ -650,7 +650,7 @@ fn test_npn_server_advertise_multiple() { let listener_ctx = { let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]); + ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) .is_ok()); ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM) @@ -665,7 +665,7 @@ fn test_npn_server_advertise_multiple() { let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_npn_protocols(&[b"spdy/3.1"]); + ctx.set_npn_protocols(&[b"spdy/3.1"]).unwrap(); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), @@ -691,7 +691,7 @@ fn test_alpn_server_advertise_multiple() { let listener_ctx = { let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]); + ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) .is_ok()); ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM) @@ -706,7 +706,7 @@ fn test_alpn_server_advertise_multiple() { let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_alpn_protocols(&[b"spdy/3.1"]); + ctx.set_alpn_protocols(&[b"spdy/3.1"]).unwrap(); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), @@ -732,7 +732,7 @@ fn test_alpn_server_select_none() { let listener_ctx = { let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]); + ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) .is_ok()); ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM) @@ -747,7 +747,7 @@ fn test_alpn_server_select_none() { let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_alpn_protocols(&[b"http/2"]); + ctx.set_alpn_protocols(&[b"http/2"]).unwrap(); ctx.set_CA_file(&Path::new("test/root-ca.pem")).unwrap(); // Now connect to the socket and make sure the protocol negotiation works... let stream = TcpStream::connect(localhost).unwrap(); @@ -767,7 +767,7 @@ fn test_alpn_server_select_none() { let listener_ctx = { let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]); + ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) .is_ok()); ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM) @@ -782,7 +782,7 @@ fn test_alpn_server_select_none() { let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_alpn_protocols(&[b"http/2"]); + ctx.set_alpn_protocols(&[b"http/2"]).unwrap(); ctx.set_CA_file(&Path::new("test/root-ca.pem")).unwrap(); // Now connect to the socket and make sure the protocol negotiation works... let stream = TcpStream::connect(localhost).unwrap(); From c4459c37d98b3a56723e6698852698fb2f354d47 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 18 Oct 2016 21:11:23 -0700 Subject: [PATCH 059/186] Callback cleanup --- openssl-sys/src/lib.rs | 24 ++++++++++----------- openssl/src/crypto/util.rs | 16 +++++++------- openssl/src/ssl/mod.rs | 43 ++++++++++++++------------------------ 3 files changed, 36 insertions(+), 47 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index ae38d1b3..aae2540c 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -78,19 +78,19 @@ pub type BN_ULONG = libc::c_ulonglong; #[cfg(target_pointer_width = "32")] pub type BN_ULONG = c_uint; -pub type CRYPTO_EX_new = extern "C" fn(parent: *mut c_void, ptr: *mut c_void, - ad: *const CRYPTO_EX_DATA, idx: c_int, - argl: c_long, argp: *const c_void) -> c_int; -pub type CRYPTO_EX_dup = extern "C" fn(to: *mut CRYPTO_EX_DATA, - from: *mut CRYPTO_EX_DATA, from_d: *mut c_void, - idx: c_int, argl: c_long, argp: *mut c_void) - -> c_int; -pub type CRYPTO_EX_free = extern "C" fn(parent: *mut c_void, ptr: *mut c_void, - ad: *mut CRYPTO_EX_DATA, idx: c_int, - argl: c_long, argp: *mut c_void); -pub type PasswordCallback = extern "C" fn(buf: *mut c_char, size: c_int, - rwflag: c_int, user_data: *mut c_void) +pub type CRYPTO_EX_new = unsafe extern fn(parent: *mut c_void, ptr: *mut c_void, + ad: *const CRYPTO_EX_DATA, idx: c_int, + argl: c_long, argp: *const c_void) -> c_int; +pub type CRYPTO_EX_dup = unsafe extern fn(to: *mut CRYPTO_EX_DATA, + from: *mut CRYPTO_EX_DATA, from_d: *mut c_void, + idx: c_int, argl: c_long, argp: *mut c_void) -> c_int; +pub type CRYPTO_EX_free = unsafe extern fn(parent: *mut c_void, ptr: *mut c_void, + ad: *mut CRYPTO_EX_DATA, idx: c_int, + argl: c_long, argp: *mut c_void); +pub type PasswordCallback = unsafe extern fn(buf: *mut c_char, size: c_int, + rwflag: c_int, user_data: *mut c_void) + -> c_int; pub const BIO_TYPE_NONE: c_int = 0; diff --git a/openssl/src/crypto/util.rs b/openssl/src/crypto/util.rs index c11285f8..07099b7c 100644 --- a/openssl/src/crypto/util.rs +++ b/openssl/src/crypto/util.rs @@ -36,16 +36,16 @@ impl Drop for CallbackState { /// Password callback function, passed to private key loading functions. /// /// `cb_state` is expected to be a pointer to a `CallbackState`. -pub extern "C" fn invoke_passwd_cb(buf: *mut c_char, - size: c_int, - _rwflag: c_int, - cb_state: *mut c_void) - -> c_int - where F: FnOnce(&mut [c_char]) -> usize { +pub unsafe extern fn invoke_passwd_cb(buf: *mut c_char, + size: c_int, + _rwflag: c_int, + cb_state: *mut c_void) + -> c_int + where F: FnOnce(&mut [c_char]) -> usize { let result = panic::catch_unwind(|| { // build a `i8` slice to pass to the user callback - let pass_slice = unsafe { slice::from_raw_parts_mut(buf, size as usize) }; - let callback = unsafe { &mut *(cb_state as *mut CallbackState) }; + let pass_slice = slice::from_raw_parts_mut(buf, size as usize); + let callback = &mut *(cb_state as *mut CallbackState); callback.cb.take().unwrap()(pass_slice) }); diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index cd7fe7b9..fafac45c 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -142,20 +142,20 @@ lazy_static! { static ref ALPN_PROTOS_IDX: c_int = get_new_idx::>(); } +unsafe extern fn free_data_box(_parent: *mut c_void, + ptr: *mut c_void, + _ad: *mut ffi::CRYPTO_EX_DATA, + _idx: c_int, + _argl: c_long, + _argp: *mut c_void) { + if !ptr.is_null() { + Box::::from_raw(ptr as *mut T); + } +} + /// Determine a new index to use for SSL CTX ex data. /// Registers a destruct for the data which will be called by openssl when the context is freed. fn get_new_idx() -> c_int { - extern fn free_data_box(_parent: *mut c_void, - ptr: *mut c_void, - _ad: *mut ffi::CRYPTO_EX_DATA, - _idx: c_int, - _argl: c_long, - _argp: *mut c_void) { - if !ptr.is_null() { - let _: Box = unsafe { mem::transmute(ptr) }; - } - } - unsafe { let idx = compat::get_new_idx(free_data_box::); assert!(idx >= 0); @@ -164,17 +164,6 @@ fn get_new_idx() -> c_int { } fn get_new_ssl_idx() -> c_int { - extern fn free_data_box(_parent: *mut c_void, - ptr: *mut c_void, - _ad: *mut ffi::CRYPTO_EX_DATA, - _idx: c_int, - _argl: c_long, - _argp: *mut c_void) { - if !ptr.is_null() { - let _: Box = unsafe { mem::transmute(ptr) }; - } - } - unsafe { let idx = compat::get_new_ssl_idx(free_data_box::); assert!(idx >= 0); @@ -190,7 +179,7 @@ extern fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) let ssl = ffi::X509_STORE_CTX_get_ex_data(x509_ctx, idx); let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); let verify = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_verify_data_idx::()); - let verify: &F = mem::transmute(verify); + let verify: &F = &*(verify as *mut F); let ctx = X509StoreContext::new(x509_ctx); @@ -206,7 +195,7 @@ extern fn ssl_raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_ let ssl = ffi::X509_STORE_CTX_get_ex_data(x509_ctx, idx); let verify = ffi::SSL_get_ex_data(ssl as *const _, get_ssl_verify_data_idx::()); - let verify: &F = mem::transmute(verify); + let verify: &F = &*(verify as *mut F); let ctx = X509StoreContext::new(x509_ctx); @@ -220,7 +209,7 @@ extern fn raw_sni(ssl: *mut ffi::SSL, al: *mut c_int, _arg: *mut c_void) -> c unsafe { let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_verify_data_idx::()); - let callback: &F = mem::transmute(callback); + let callback: &F = &*(callback as *mut F); let mut ssl = SslRef::from_ptr(ssl); match callback(&mut ssl) { @@ -250,7 +239,7 @@ unsafe fn select_proto_using(ssl: *mut ffi::SSL, // extra data. let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); let protocols = ffi::SSL_CTX_get_ex_data(ssl_ctx, ex_data); - let protocols: &Vec = mem::transmute(protocols); + let protocols: &Vec = &*(protocols as *mut Vec); // Prepare the client list parameters to be passed to the OpenSSL function... let client = protocols.as_ptr(); let client_len = protocols.len() as c_uint; @@ -313,7 +302,7 @@ extern fn raw_next_protos_advertise_cb(ssl: *mut ffi::SSL, } else { // If the pointer is valid, put the pointer to the actual byte array into the // output parameter `out`, as well as its length into `outlen`. - let protocols: &Vec = mem::transmute(protocols); + let protocols: &Vec = &*(protocols as *mut Vec); *out = protocols.as_ptr(); *outlen = protocols.len() as c_uint; } From 080050e10d7f1b00e164e4cb047ffc323f5d6fc9 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 18 Oct 2016 21:52:49 -0700 Subject: [PATCH 060/186] Drop lifetime on GeneralNames --- openssl/src/x509/mod.rs | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index e801b1da..de74a236 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -406,7 +406,7 @@ impl<'a> X509Ref<'a> { } /// Returns this certificate's SAN entries, if they exist. - pub fn subject_alt_names<'b>(&'b self) -> Option> { + pub fn subject_alt_names(&self) -> Option { unsafe { let stack = ffi::X509_get_ext_d2i(self.0, Nid::SubjectAltName as c_int, @@ -418,7 +418,6 @@ impl<'a> X509Ref<'a> { Some(GeneralNames { stack: stack as *mut _, - m: PhantomData, }) } } @@ -763,14 +762,12 @@ make_validation_error!(X509_V_OK, X509ApplicationVerification = X509_V_ERR_APPLICATION_VERIFICATION, ); -// FIXME remove lifetime param for 0.9 /// A collection of OpenSSL `GENERAL_NAME`s. -pub struct GeneralNames<'a> { +pub struct GeneralNames { stack: *mut ffi::stack_st_GENERAL_NAME, - m: PhantomData<&'a ()>, } -impl<'a> Drop for GeneralNames<'a> { +impl Drop for GeneralNames { #[cfg(ossl10x)] fn drop(&mut self) { unsafe { @@ -792,7 +789,7 @@ impl<'a> Drop for GeneralNames<'a> { } } -impl<'a> GeneralNames<'a> { +impl GeneralNames { /// Returns the number of `GeneralName`s in this structure. pub fn len(&self) -> usize { self._len() @@ -813,7 +810,7 @@ impl<'a> GeneralNames<'a> { /// # Panics /// /// Panics if `idx` is not less than `len()`. - pub fn get(&self, idx: usize) -> GeneralName<'a> { + pub fn get<'a>(&'a self, idx: usize) -> GeneralName<'a> { unsafe { assert!(idx < self.len()); GeneralName { @@ -842,7 +839,7 @@ impl<'a> GeneralNames<'a> { } } -impl<'a> IntoIterator for &'a GeneralNames<'a> { +impl<'a> IntoIterator for &'a GeneralNames { type Item = GeneralName<'a>; type IntoIter = GeneralNamesIter<'a>; @@ -853,7 +850,7 @@ impl<'a> IntoIterator for &'a GeneralNames<'a> { /// An iterator over OpenSSL `GENERAL_NAME`s. pub struct GeneralNamesIter<'a> { - names: &'a GeneralNames<'a>, + names: &'a GeneralNames, idx: usize, } From cfd5192a7d44b8d6c77e57f091887a6a00a166db Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 18 Oct 2016 22:10:37 -0700 Subject: [PATCH 061/186] De-enumify X509ValidationError Also make it an Error. Closes #352. --- openssl-sys/src/lib.rs | 1 + openssl/src/x509/mod.rs | 145 +++++++++++++++++----------------------- 2 files changed, 62 insertions(+), 84 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index aae2540c..33abad21 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -731,6 +731,7 @@ extern { pub fn X509_sign(x: *mut X509, pkey: *mut EVP_PKEY, md: *const EVP_MD) -> c_int; pub fn X509_get_pubkey(x: *mut X509) -> *mut EVP_PKEY; pub fn X509_to_X509_REQ(x: *mut X509, pkey: *mut EVP_PKEY, md: *const EVP_MD) -> *mut X509_REQ; + pub fn X509_verify_cert_error_string(n: c_long) -> *const c_char; pub fn X509_EXTENSION_free(ext: *mut X509_EXTENSION); diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index de74a236..50d75d63 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -1,14 +1,15 @@ use libc::{c_char, c_int, c_long, c_ulong, c_void}; use std::cmp; -use std::ffi::CString; -use std::mem; -use std::ptr; -use std::ops::Deref; -use std::fmt; -use std::str; -use std::slice; 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::ops::Deref; +use std::ptr; +use std::slice; +use std::str; use {cvt, cvt_p}; use asn1::Asn1Time; @@ -100,14 +101,19 @@ impl X509StoreContext { } pub fn error(&self) -> Option { - let err = unsafe { ffi::X509_STORE_CTX_get_error(self.ctx) }; - X509ValidationError::from_raw(err) + unsafe { + let err = ffi::X509_STORE_CTX_get_error(self.ctx) as c_long; + if err == ffi::X509_V_OK as c_long { + None + } else { + Some(X509ValidationError::from_raw(err)) + } + } } pub fn current_cert<'a>(&'a self) -> Option> { unsafe { let ptr = ffi::X509_STORE_CTX_get_current_cert(self.ctx); - if ptr.is_null() { None } else { @@ -685,82 +691,53 @@ impl<'a> Iterator for ExtensionsIter<'a> { } } -macro_rules! make_validation_error( - ($ok_val:ident, $($name:ident = $val:ident,)+) => ( - #[derive(Copy, Clone)] - pub enum X509ValidationError { - $($name,)+ - X509UnknownError(c_int) - } +pub struct X509ValidationError(c_long); - impl X509ValidationError { - #[doc(hidden)] - pub fn from_raw(err: c_int) -> Option { - match err { - ffi::$ok_val => None, - $(ffi::$val => Some(X509ValidationError::$name),)+ - err => Some(X509ValidationError::X509UnknownError(err)) - } - } - } - ) -); +impl fmt::Debug for X509ValidationError { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("X509ValidationError") + .field("code", &self.0) + .field("error", &self.error_string()) + .finish() + } +} -make_validation_error!(X509_V_OK, - X509UnableToGetIssuerCert = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, - X509UnableToGetCrl = X509_V_ERR_UNABLE_TO_GET_CRL, - X509UnableToDecryptCertSignature = X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, - X509UnableToDecryptCrlSignature = X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, - X509UnableToDecodeIssuerPublicKey = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, - X509CertSignatureFailure = X509_V_ERR_CERT_SIGNATURE_FAILURE, - X509CrlSignatureFailure = X509_V_ERR_CRL_SIGNATURE_FAILURE, - X509CertNotYetValid = X509_V_ERR_CERT_NOT_YET_VALID, - X509CertHasExpired = X509_V_ERR_CERT_HAS_EXPIRED, - X509CrlNotYetValid = X509_V_ERR_CRL_NOT_YET_VALID, - X509CrlHasExpired = X509_V_ERR_CRL_HAS_EXPIRED, - X509ErrorInCertNotBeforeField = X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, - X509ErrorInCertNotAfterField = X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, - X509ErrorInCrlLastUpdateField = X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, - X509ErrorInCrlNextUpdateField = X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, - X509OutOfMem = X509_V_ERR_OUT_OF_MEM, - X509DepthZeroSelfSignedCert = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, - X509SelfSignedCertInChain = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, - X509UnableToGetIssuerCertLocally = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, - X509UnableToVerifyLeafSignature = X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, - X509CertChainTooLong = X509_V_ERR_CERT_CHAIN_TOO_LONG, - X509CertRevoked = X509_V_ERR_CERT_REVOKED, - X509InvalidCA = X509_V_ERR_INVALID_CA, - X509PathLengthExceeded = X509_V_ERR_PATH_LENGTH_EXCEEDED, - X509InvalidPurpose = X509_V_ERR_INVALID_PURPOSE, - X509CertUntrusted = X509_V_ERR_CERT_UNTRUSTED, - X509CertRejected = X509_V_ERR_CERT_REJECTED, - X509SubjectIssuerMismatch = X509_V_ERR_SUBJECT_ISSUER_MISMATCH, - X509AkidSkidMismatch = X509_V_ERR_AKID_SKID_MISMATCH, - X509AkidIssuerSerialMismatch = X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH, - X509KeyusageNoCertsign = X509_V_ERR_KEYUSAGE_NO_CERTSIGN, - X509UnableToGetCrlIssuer = X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, - X509UnhandledCriticalExtension = X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION, - X509KeyusageNoCrlSign = X509_V_ERR_KEYUSAGE_NO_CRL_SIGN, - X509UnhandledCriticalCrlExtension = X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION, - X509InvalidNonCA = X509_V_ERR_INVALID_NON_CA, - X509ProxyPathLengthExceeded = X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED, - X509KeyusageNoDigitalSignature = X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE, - X509ProxyCertificatesNotAllowed = X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED, - X509InvalidExtension = X509_V_ERR_INVALID_EXTENSION, - X509InavlidPolicyExtension = X509_V_ERR_INVALID_POLICY_EXTENSION, - X509NoExplicitPolicy = X509_V_ERR_NO_EXPLICIT_POLICY, - X509DifferentCrlScope = X509_V_ERR_DIFFERENT_CRL_SCOPE, - X509UnsupportedExtensionFeature = X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE, - X509UnnestedResource = X509_V_ERR_UNNESTED_RESOURCE, - X509PermittedVolation = X509_V_ERR_PERMITTED_VIOLATION, - X509ExcludedViolation = X509_V_ERR_EXCLUDED_VIOLATION, - X509SubtreeMinmax = X509_V_ERR_SUBTREE_MINMAX, - X509UnsupportedConstraintType = X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE, - X509UnsupportedConstraintSyntax = X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX, - X509UnsupportedNameSyntax = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX, - X509CrlPathValidationError= X509_V_ERR_CRL_PATH_VALIDATION_ERROR, - X509ApplicationVerification = X509_V_ERR_APPLICATION_VERIFICATION, -); +impl fmt::Display for X509ValidationError { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.write_str(self.error_string()) + } +} + +impl Error for X509ValidationError { + fn description(&self) -> &str { + "an X509 validation error" + } +} + +impl X509ValidationError { + /// Creates an `X509ValidationError` from a raw error number. + /// + /// # Safety + /// + /// Some methods on `X509ValidationError` are not thread safe if the error + /// number is invalid. + pub unsafe fn from_raw(err: c_long) -> X509ValidationError { + X509ValidationError(err) + } + + pub fn as_raw(&self) -> c_long { + self.0 + } + + pub fn error_string(&self) -> &'static str { + ffi::init(); + + unsafe { + let s = ffi::X509_verify_cert_error_string(self.0); + str::from_utf8(CStr::from_ptr(s).to_bytes()).unwrap() + } + } +} /// A collection of OpenSSL `GENERAL_NAME`s. pub struct GeneralNames { From 5ab037f056174b4d69024f58fe42cf0c41a34db6 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 18 Oct 2016 22:18:09 -0700 Subject: [PATCH 062/186] Allow the X509 verify error to be read from an SslRef --- openssl-sys/src/lib.rs | 3 ++- openssl/src/ssl/mod.rs | 9 ++++++++- openssl/src/x509/mod.rs | 35 ++++++++++++++++++----------------- 3 files changed, 28 insertions(+), 19 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 33abad21..4c8d63ca 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -647,7 +647,8 @@ extern { pub fn SSL_get_servername(ssl: *const SSL, name_type: c_int) -> *const c_char; pub fn SSL_get_current_cipher(ssl: *const SSL) -> *const SSL_CIPHER; #[cfg(not(ossl101))] - pub fn SSL_get0_param(ssl: *mut ::SSL) -> *mut X509_VERIFY_PARAM; + pub fn SSL_get0_param(ssl: *mut SSL) -> *mut X509_VERIFY_PARAM; + pub fn SSL_get_verify_result(ssl: *const SSL) -> c_long; #[cfg(not(osslconf = "OPENSSL_NO_COMP"))] pub fn SSL_COMP_get_name(comp: *const COMP_METHOD) -> *const c_char; diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index fafac45c..d7adb43f 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -21,7 +21,7 @@ use ffi; use {init, cvt, cvt_p}; use dh::DH; -use x509::{X509StoreContext, X509FileType, X509, X509Ref}; +use x509::{X509StoreContext, X509FileType, X509, X509Ref, X509VerifyError}; #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] use x509::verify::X509VerifyParamRef; use crypto::pkey::PKey; @@ -1007,6 +1007,13 @@ impl<'a> SslRef<'a> { X509VerifyParamRef::from_ptr(ffi::SSL_get0_param(self.as_ptr())) } } + + /// Returns the result of X509 certificate verification. + pub fn verify_result(&self) -> Option { + unsafe { + X509VerifyError::from_raw(ffi::SSL_get_verify_result(self.0)) + } + } } pub struct Ssl(SslRef<'static>); diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 50d75d63..7f891231 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -100,14 +100,9 @@ impl X509StoreContext { X509StoreContext { ctx: ctx } } - pub fn error(&self) -> Option { + pub fn error(&self) -> Option { unsafe { - let err = ffi::X509_STORE_CTX_get_error(self.ctx) as c_long; - if err == ffi::X509_V_OK as c_long { - None - } else { - Some(X509ValidationError::from_raw(err)) - } + X509VerifyError::from_raw(ffi::X509_STORE_CTX_get_error(self.ctx) as c_long) } } @@ -691,38 +686,44 @@ impl<'a> Iterator for ExtensionsIter<'a> { } } -pub struct X509ValidationError(c_long); +pub struct X509VerifyError(c_long); -impl fmt::Debug for X509ValidationError { +impl fmt::Debug for X509VerifyError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("X509ValidationError") + fmt.debug_struct("X509VerifyError") .field("code", &self.0) .field("error", &self.error_string()) .finish() } } -impl fmt::Display for X509ValidationError { +impl fmt::Display for X509VerifyError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.write_str(self.error_string()) } } -impl Error for X509ValidationError { +impl Error for X509VerifyError { fn description(&self) -> &str { "an X509 validation error" } } -impl X509ValidationError { - /// Creates an `X509ValidationError` from a raw error number. +impl X509VerifyError { + /// Creates an `X509VerifyError` from a raw error number. + /// + /// `None` will be returned if `err` is `X509_V_OK`. /// /// # Safety /// - /// Some methods on `X509ValidationError` are not thread safe if the error + /// Some methods on `X509VerifyError` are not thread safe if the error /// number is invalid. - pub unsafe fn from_raw(err: c_long) -> X509ValidationError { - X509ValidationError(err) + pub unsafe fn from_raw(err: c_long) -> Option { + if err == ffi::X509_V_OK as c_long { + None + } else { + Some(X509VerifyError(err)) + } } pub fn as_raw(&self) -> c_long { From 8f3511c0cdf3b5f1ea3407f82ba3851be2c1301e Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 20 Oct 2016 19:35:49 -0700 Subject: [PATCH 063/186] Redo SslStream construction SslStream is now constructed via methods on Ssl. You realistically want to create an Ssl for SNI and hostname verification so making it harder to construct a stream directly from an SslContext is a good thing. --- openssl/src/ssl/mod.rs | 122 +++++++++++++-------------------- openssl/src/ssl/tests/mod.rs | 126 +++++++++++++++-------------------- 2 files changed, 98 insertions(+), 150 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index d7adb43f..3e05a5c9 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -780,18 +780,6 @@ impl<'a> SslRef<'a> { unsafe { ffi::SSL_get_rbio(self.as_ptr()) } } - fn connect(&mut self) -> c_int { - unsafe { ffi::SSL_connect(self.as_ptr()) } - } - - fn accept(&mut self) -> c_int { - unsafe { ffi::SSL_accept(self.as_ptr()) } - } - - fn handshake(&mut self) -> c_int { - unsafe { ffi::SSL_do_handshake(self.as_ptr()) } - } - fn read(&mut self, buf: &mut [u8]) -> c_int { let len = cmp::min(c_int::max_value() as usize, buf.len()) as c_int; unsafe { ffi::SSL_read(self.as_ptr(), buf.as_ptr() as *mut c_void, len) } @@ -1057,6 +1045,50 @@ impl Ssl { pub unsafe fn from_ptr(ssl: *mut ffi::SSL) -> Ssl { Ssl(SslRef::from_ptr(ssl)) } + + /// Creates an SSL/TLS client operating over the provided stream. + pub fn connect(self, stream: S) -> Result, HandshakeError> + where S: Read + Write + { + let mut stream = SslStream::new_base(self, stream); + let ret = unsafe { ffi::SSL_connect(stream.ssl.as_ptr()) }; + if ret > 0 { + Ok(stream) + } else { + match stream.make_error(ret) { + e @ Error::WantWrite(_) | + e @ Error::WantRead(_) => { + Err(HandshakeError::Interrupted(MidHandshakeSslStream { + stream: stream, + error: e, + })) + } + err => Err(HandshakeError::Failure(err)), + } + } + } + + /// Creates an SSL/TLS server operating over the provided stream. + pub fn accept(self, stream: S) -> Result, HandshakeError> + where S: Read + Write + { + let mut stream = SslStream::new_base(self, stream); + let ret = unsafe { ffi::SSL_accept(stream.ssl.as_ptr()) }; + if ret > 0 { + Ok(stream) + } else { + match stream.make_error(ret) { + e @ Error::WantWrite(_) | + e @ Error::WantRead(_) => { + Err(HandshakeError::Interrupted(MidHandshakeSslStream { + stream: stream, + error: e, + })) + } + err => Err(HandshakeError::Failure(err)), + } + } + } } /// A stream wrapper which handles SSL encryption for an underlying stream. @@ -1093,54 +1125,6 @@ impl SslStream { } } - /// Creates an SSL/TLS client operating over the provided stream. - pub fn connect(ssl: T, stream: S) - -> Result>{ - let ssl = try!(ssl.into_ssl().map_err(|e| { - HandshakeError::Failure(Error::Ssl(e)) - })); - let mut stream = Self::new_base(ssl, stream); - let ret = stream.ssl.connect(); - if ret > 0 { - Ok(stream) - } else { - match stream.make_error(ret) { - e @ Error::WantWrite(_) | - e @ Error::WantRead(_) => { - Err(HandshakeError::Interrupted(MidHandshakeSslStream { - stream: stream, - error: e, - })) - } - err => Err(HandshakeError::Failure(err)), - } - } - } - - /// Creates an SSL/TLS server operating over the provided stream. - pub fn accept(ssl: T, stream: S) - -> Result> { - let ssl = try!(ssl.into_ssl().map_err(|e| { - HandshakeError::Failure(Error::Ssl(e)) - })); - let mut stream = Self::new_base(ssl, stream); - let ret = stream.ssl.accept(); - if ret > 0 { - Ok(stream) - } else { - match stream.make_error(ret) { - e @ Error::WantWrite(_) | - e @ Error::WantRead(_) => { - Err(HandshakeError::Interrupted(MidHandshakeSslStream { - stream: stream, - error: e, - })) - } - err => Err(HandshakeError::Failure(err)), - } - } - } - /// Like `read`, but returns an `ssl::Error` rather than an `io::Error`. /// /// This is particularly useful with a nonblocking socket, where the error @@ -1233,7 +1217,7 @@ impl MidHandshakeSslStream { /// Restarts the handshake process. pub fn handshake(mut self) -> Result, HandshakeError> { - let ret = self.stream.ssl.handshake(); + let ret = unsafe { ffi::SSL_do_handshake(self.stream.ssl.as_ptr()) }; if ret > 0 { Ok(self.stream) } else { @@ -1352,22 +1336,6 @@ impl Write for SslStream { } } -pub trait IntoSsl { - fn into_ssl(self) -> Result; -} - -impl IntoSsl for Ssl { - fn into_ssl(self) -> Result { - Ok(self) - } -} - -impl<'a> IntoSsl for &'a SslContext { - fn into_ssl(self) -> Result { - Ssl::new(self) - } -} - #[cfg(ossl110)] mod compat { use std::ptr; diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 966df3c5..94cea935 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -19,9 +19,7 @@ use ssl; use ssl::SSL_VERIFY_PEER; use ssl::{SslMethod, HandshakeError}; use ssl::error::Error; -use ssl::{SslContext, SslStream}; -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -use ssl::IntoSsl; +use ssl::{SslContext, SslStream, Ssl}; use x509::X509StoreContext; use x509::X509FileType; use x509::X509; @@ -194,15 +192,11 @@ run_test!(new_ctx, |method, _| { SslContext::new(method).unwrap(); }); -run_test!(new_sslstream, |method, stream| { - SslStream::connect(&SslContext::new(method).unwrap(), stream).unwrap(); -}); - run_test!(verify_untrusted, |method, stream| { let mut ctx = SslContext::new(method).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - match SslStream::connect(&ctx, stream) { + match Ssl::new(&ctx).unwrap().connect(stream) { Ok(_) => panic!("expected failure"), Err(err) => println!("error {:?}", err), } @@ -216,7 +210,7 @@ run_test!(verify_trusted, |method, stream| { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - match SslStream::connect(&ctx, stream) { + match Ssl::new(&ctx).unwrap().connect(stream) { Ok(_) => (), Err(err) => panic!("Expected success, got {:?}", err), } @@ -226,7 +220,7 @@ run_test!(verify_untrusted_callback_override_ok, |method, stream| { let mut ctx = SslContext::new(method).unwrap(); ctx.set_verify_callback(SSL_VERIFY_PEER, |_, _| true); - match SslStream::connect(&ctx, stream) { + match Ssl::new(&ctx).unwrap().connect(stream) { Ok(_) => (), Err(err) => panic!("Expected success, got {:?}", err), } @@ -236,7 +230,7 @@ run_test!(verify_untrusted_callback_override_bad, |method, stream| { let mut ctx = SslContext::new(method).unwrap(); ctx.set_verify_callback(SSL_VERIFY_PEER, |_, _| false); - assert!(SslStream::connect(&ctx, stream).is_err()); + assert!(Ssl::new(&ctx).unwrap().connect(stream).is_err()); }); run_test!(verify_trusted_callback_override_ok, |method, stream| { @@ -247,7 +241,7 @@ run_test!(verify_trusted_callback_override_ok, |method, stream| { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - match SslStream::connect(&ctx, stream) { + match Ssl::new(&ctx).unwrap().connect(stream) { Ok(_) => (), Err(err) => panic!("Expected success, got {:?}", err), } @@ -261,7 +255,7 @@ run_test!(verify_trusted_callback_override_bad, |method, stream| { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - assert!(SslStream::connect(&ctx, stream).is_err()); + assert!(Ssl::new(&ctx).unwrap().connect(stream).is_err()); }); run_test!(verify_callback_load_certs, |method, stream| { @@ -271,7 +265,7 @@ run_test!(verify_callback_load_certs, |method, stream| { true }); - assert!(SslStream::connect(&ctx, stream).is_ok()); + assert!(Ssl::new(&ctx).unwrap().connect(stream).is_ok()); }); run_test!(verify_trusted_get_error_ok, |method, stream| { @@ -285,7 +279,7 @@ run_test!(verify_trusted_get_error_ok, |method, stream| { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - assert!(SslStream::connect(&ctx, stream).is_ok()); + assert!(Ssl::new(&ctx).unwrap().connect(stream).is_ok()); }); run_test!(verify_trusted_get_error_err, |method, stream| { @@ -295,7 +289,7 @@ run_test!(verify_trusted_get_error_err, |method, stream| { false }); - assert!(SslStream::connect(&ctx, stream).is_err()); + assert!(Ssl::new(&ctx).unwrap().connect(stream).is_err()); }); run_test!(verify_callback_data, |method, stream| { @@ -319,7 +313,7 @@ run_test!(verify_callback_data, |method, stream| { }); ctx.set_verify_depth(1); - match SslStream::connect(&ctx, stream) { + match Ssl::new(&ctx).unwrap().connect(stream) { Ok(_) => (), Err(err) => panic!("Expected success, got {:?}", err), } @@ -327,12 +321,11 @@ run_test!(verify_callback_data, |method, stream| { run_test!(ssl_verify_callback, |method, stream| { use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; - use ssl::IntoSsl; static CHECKED: AtomicUsize = ATOMIC_USIZE_INIT; let ctx = SslContext::new(method).unwrap(); - let mut ssl = ctx.into_ssl().unwrap(); + let mut ssl = Ssl::new(&ctx).unwrap(); let node_hash_str = "59172d9313e84459bcff27f967e79e6e9217e584"; let node_id = node_hash_str.from_hex().unwrap(); @@ -347,7 +340,7 @@ run_test!(ssl_verify_callback, |method, stream| { } }); - match SslStream::connect(ssl, stream) { + match ssl.connect(stream) { Ok(_) => (), Err(err) => panic!("Expected success, got {:?}", err), } @@ -364,7 +357,7 @@ fn test_write_hits_stream() { let guard = thread::spawn(move || { let ctx = SslContext::new(SslMethod::tls()).unwrap(); let stream = TcpStream::connect(addr).unwrap(); - let mut stream = SslStream::connect(&ctx, stream).unwrap(); + let mut stream = Ssl::new(&ctx).unwrap().connect(stream).unwrap(); stream.write_all(b"hello").unwrap(); stream @@ -375,7 +368,7 @@ fn test_write_hits_stream() { ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM).unwrap(); ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM).unwrap(); let stream = listener.accept().unwrap().0; - let mut stream = SslStream::accept(&ctx, stream).unwrap(); + let mut stream = Ssl::new(&ctx).unwrap().accept(stream).unwrap(); let mut buf = [0; 5]; assert_eq!(5, stream.read(&mut buf).unwrap()); @@ -418,17 +411,8 @@ run_test!(clear_ctx_options, |method, _| { #[test] fn test_write() { let (_s, stream) = Server::new(); - let mut stream = SslStream::connect(&SslContext::new(SslMethod::tls()).unwrap(), stream).unwrap(); - stream.write_all("hello".as_bytes()).unwrap(); - stream.flush().unwrap(); - stream.write_all(" there".as_bytes()).unwrap(); - stream.flush().unwrap(); -} - -#[test] -fn test_write_direct() { - let (_s, stream) = Server::new(); - let mut stream = SslStream::connect(&SslContext::new(SslMethod::tls()).unwrap(), stream).unwrap(); + let ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut stream = Ssl::new(&ctx).unwrap().connect(stream).unwrap(); stream.write_all("hello".as_bytes()).unwrap(); stream.flush().unwrap(); stream.write_all(" there".as_bytes()).unwrap(); @@ -436,7 +420,8 @@ fn test_write_direct() { } run_test!(get_peer_certificate, |method, stream| { - let stream = SslStream::connect(&SslContext::new(method).unwrap(), stream).unwrap(); + let ctx = SslContext::new(method).unwrap(); + let stream = Ssl::new(&ctx).unwrap().connect(stream).unwrap(); let cert = stream.ssl().peer_certificate().unwrap(); let fingerprint = cert.fingerprint(MessageDigest::sha1()).unwrap(); let node_hash_str = "59172d9313e84459bcff27f967e79e6e9217e584"; @@ -448,8 +433,8 @@ run_test!(get_peer_certificate, |method, stream| { #[cfg_attr(any(windows, target_arch = "arm"), ignore)] // FIXME(#467) fn test_write_dtlsv1() { let (_s, stream) = Server::new_dtlsv1(iter::repeat("y\n")); - - let mut stream = SslStream::connect(&SslContext::new(SslMethod::dtls()).unwrap(), stream).unwrap(); + let ctx = SslContext::new(SslMethod::dtls()).unwrap(); + let mut stream = Ssl::new(&ctx).unwrap().connect(stream).unwrap(); stream.write_all(b"hello").unwrap(); stream.flush().unwrap(); stream.write_all(b" there").unwrap(); @@ -459,16 +444,8 @@ fn test_write_dtlsv1() { #[test] fn test_read() { let (_s, tcp) = Server::new(); - let mut stream = SslStream::connect(&SslContext::new(SslMethod::tls()).unwrap(), tcp).unwrap(); - stream.write_all("GET /\r\n\r\n".as_bytes()).unwrap(); - stream.flush().unwrap(); - io::copy(&mut stream, &mut io::sink()).ok().expect("read error"); -} - -#[test] -fn test_read_direct() { - let (_s, tcp) = Server::new(); - let mut stream = SslStream::connect(&SslContext::new(SslMethod::tls()).unwrap(), tcp).unwrap(); + let ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut stream = Ssl::new(&ctx).unwrap().connect(tcp).unwrap(); stream.write_all("GET /\r\n\r\n".as_bytes()).unwrap(); stream.flush().unwrap(); io::copy(&mut stream, &mut io::sink()).ok().expect("read error"); @@ -477,7 +454,8 @@ fn test_read_direct() { #[test] fn test_pending() { let (_s, tcp) = Server::new(); - let mut stream = SslStream::connect(&SslContext::new(SslMethod::tls()).unwrap(), tcp).unwrap(); + let ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut stream = Ssl::new(&ctx).unwrap().connect(tcp).unwrap(); stream.write_all("GET /\r\n\r\n".as_bytes()).unwrap(); stream.flush().unwrap(); @@ -500,7 +478,8 @@ fn test_pending() { #[test] fn test_state() { let (_s, tcp) = Server::new(); - let stream = SslStream::connect(&SslContext::new(SslMethod::tls()).unwrap(), tcp).unwrap(); + let ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut stream = Ssl::new(&ctx).unwrap().connect(tcp).unwrap(); assert_eq!(stream.ssl().state_string(), "SSLOK "); assert_eq!(stream.ssl().state_string_long(), "SSL negotiation finished successfully"); @@ -519,7 +498,7 @@ fn test_connect_with_unilateral_alpn() { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - let stream = match SslStream::connect(&ctx, stream) { + let stream = match Ssl::new(&ctx).unwrap().connect(stream) { Ok(stream) => stream, Err(err) => panic!("Expected success, got {:?}", err), }; @@ -540,7 +519,7 @@ fn test_connect_with_unilateral_npn() { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - let stream = match SslStream::connect(&ctx, stream) { + let stream = match Ssl::new(&ctx).unwrap().connect(stream) { Ok(stream) => stream, Err(err) => panic!("Expected success, got {:?}", err), }; @@ -562,7 +541,7 @@ fn test_connect_with_alpn_successful_multiple_matching() { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - let stream = match SslStream::connect(&ctx, stream) { + let stream = match Ssl::new(&ctx).unwrap().connect(stream) { Ok(stream) => stream, Err(err) => panic!("Expected success, got {:?}", err), }; @@ -584,7 +563,7 @@ fn test_connect_with_npn_successful_multiple_matching() { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - let stream = match SslStream::connect(&ctx, stream) { + let stream = match Ssl::new(&ctx).unwrap().connect(stream) { Ok(stream) => stream, Err(err) => panic!("Expected success, got {:?}", err), }; @@ -607,7 +586,7 @@ fn test_connect_with_alpn_successful_single_match() { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - let stream = match SslStream::connect(&ctx, stream) { + let stream = match Ssl::new(&ctx).unwrap().connect(stream) { Ok(stream) => stream, Err(err) => panic!("Expected success, got {:?}", err), }; @@ -631,7 +610,7 @@ fn test_connect_with_npn_successful_single_match() { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - let stream = match SslStream::connect(&ctx, stream) { + let stream = match Ssl::new(&ctx).unwrap().connect(stream) { Ok(stream) => stream, Err(err) => panic!("Expected success, got {:?}", err), }; @@ -660,7 +639,7 @@ fn test_npn_server_advertise_multiple() { // Have the listener wait on the connection in a different thread. thread::spawn(move || { let (stream, _) = listener.accept().unwrap(); - let _ = SslStream::accept(&listener_ctx, stream).unwrap(); + Ssl::new(&listener_ctx).unwrap().accept(stream).unwrap(); }); let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); @@ -672,7 +651,7 @@ fn test_npn_server_advertise_multiple() { } // Now connect to the socket and make sure the protocol negotiation works... let stream = TcpStream::connect(localhost).unwrap(); - let stream = match SslStream::connect(&ctx, stream) { + let stream = match Ssl::new(&ctx).unwrap().connect(stream) { Ok(stream) => stream, Err(err) => panic!("Expected success, got {:?}", err), }; @@ -701,7 +680,7 @@ fn test_alpn_server_advertise_multiple() { // Have the listener wait on the connection in a different thread. thread::spawn(move || { let (stream, _) = listener.accept().unwrap(); - let _ = SslStream::accept(&listener_ctx, stream).unwrap(); + Ssl::new(&listener_ctx).unwrap().accept(stream).unwrap(); }); let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); @@ -713,7 +692,7 @@ fn test_alpn_server_advertise_multiple() { } // Now connect to the socket and make sure the protocol negotiation works... let stream = TcpStream::connect(localhost).unwrap(); - let stream = match SslStream::connect(&ctx, stream) { + let stream = match Ssl::new(&ctx).unwrap().connect(stream) { Ok(stream) => stream, Err(err) => panic!("Expected success, got {:?}", err), }; @@ -742,7 +721,7 @@ fn test_alpn_server_select_none() { // Have the listener wait on the connection in a different thread. thread::spawn(move || { let (stream, _) = listener.accept().unwrap(); - let _ = SslStream::accept(&listener_ctx, stream).unwrap(); + Ssl::new(&listener_ctx).unwrap().accept(stream).unwrap(); }); let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); @@ -751,7 +730,7 @@ fn test_alpn_server_select_none() { ctx.set_CA_file(&Path::new("test/root-ca.pem")).unwrap(); // Now connect to the socket and make sure the protocol negotiation works... let stream = TcpStream::connect(localhost).unwrap(); - let stream = SslStream::connect(&ctx, stream).unwrap(); + let stream = Ssl::new(&ctx).unwrap().connect(stream).unwrap(); // Since the protocols from the server and client don't overlap at all, no protocol is selected assert_eq!(None, stream.ssl().selected_alpn_protocol()); @@ -777,7 +756,7 @@ fn test_alpn_server_select_none() { // Have the listener wait on the connection in a different thread. thread::spawn(move || { let (stream, _) = listener.accept().unwrap(); - assert!(SslStream::accept(&listener_ctx, stream).is_err()); + assert!(Ssl::new(&listener_ctx).unwrap().accept(stream).is_err()); }); let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); @@ -786,7 +765,7 @@ fn test_alpn_server_select_none() { ctx.set_CA_file(&Path::new("test/root-ca.pem")).unwrap(); // Now connect to the socket and make sure the protocol negotiation works... let stream = TcpStream::connect(localhost).unwrap(); - assert!(SslStream::connect(&ctx, stream).is_err()); + assert!(Ssl::new(&ctx).unwrap().connect(stream).is_err()); } #[cfg(test)] @@ -812,7 +791,8 @@ mod dtlsv1 { fn test_read_dtlsv1() { let (_s, stream) = Server::new_dtlsv1(Some("hello")); - let mut stream = SslStream::connect(&SslContext::new(SslMethod::dtls()).unwrap(), stream).unwrap(); + let ctx = SslContext::new(SslMethod::dtls()).unwrap(); + let mut stream = Ssl::new(&ctx).unwrap().connect(stream).unwrap(); let mut buf = [0u8; 100]; assert!(stream.read(&mut buf).is_ok()); } @@ -853,7 +833,7 @@ fn test_write_nonblocking() { let (_s, stream) = Server::new(); stream.set_nonblocking(true).unwrap(); let cx = SslContext::new(SslMethod::tls()).unwrap(); - let mut stream = handshake(SslStream::connect(&cx, stream)); + let mut stream = handshake(Ssl::new(&cx).unwrap().connect(stream)); let mut iterations = 0; loop { @@ -891,7 +871,7 @@ fn test_read_nonblocking() { let (_s, stream) = Server::new(); stream.set_nonblocking(true).unwrap(); let cx = SslContext::new(SslMethod::tls()).unwrap(); - let mut stream = handshake(SslStream::connect(&cx, stream)); + let mut stream = handshake(Ssl::new(&cx).unwrap().connect(stream)); let mut iterations = 0; loop { @@ -965,7 +945,7 @@ fn write_panic() { let stream = ExplodingStream(stream); let ctx = SslContext::new(SslMethod::tls()).unwrap(); - let _ = SslStream::connect(&ctx, stream); + let _ = Ssl::new(&ctx).unwrap().connect(stream); } #[test] @@ -993,7 +973,7 @@ fn read_panic() { let stream = ExplodingStream(stream); let ctx = SslContext::new(SslMethod::tls()).unwrap(); - let _ = SslStream::connect(&ctx, stream); + let _ = Ssl::new(&ctx).unwrap().connect(stream); } #[test] @@ -1021,7 +1001,7 @@ fn flush_panic() { let stream = ExplodingStream(stream); let ctx = SslContext::new(SslMethod::tls()).unwrap(); - let mut stream = SslStream::connect(&ctx, stream).ok().unwrap(); + let mut stream = Ssl::new(&ctx).unwrap().connect(stream).ok().unwrap(); let _ = stream.flush(); } @@ -1045,7 +1025,7 @@ fn default_verify_paths() { ctx.set_default_verify_paths().unwrap(); ctx.set_verify(SSL_VERIFY_PEER); let s = TcpStream::connect("google.com:443").unwrap(); - let mut socket = SslStream::connect(&ctx, s).unwrap(); + let mut socket = Ssl::new(&ctx).unwrap().connect(s).unwrap(); socket.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); let mut result = vec![]; @@ -1072,12 +1052,12 @@ fn valid_hostname() { ctx.set_default_verify_paths().unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - let mut ssl = ctx.into_ssl().unwrap(); + let mut ssl = Ssl::new(&ctx).unwrap(); ssl.param().set_hostflags(X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); ssl.param().set_host("google.com").unwrap(); let s = TcpStream::connect("google.com:443").unwrap(); - let mut socket = SslStream::connect(ssl, s).unwrap(); + let mut socket = ssl.connect(s).unwrap(); socket.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); let mut result = vec![]; @@ -1096,10 +1076,10 @@ fn invalid_hostname() { ctx.set_default_verify_paths().unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - let mut ssl = ctx.into_ssl().unwrap(); + let mut ssl = Ssl::new(&ctx).unwrap(); ssl.param().set_hostflags(X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); ssl.param().set_host("foobar.com").unwrap(); let s = TcpStream::connect("google.com:443").unwrap(); - assert!(SslStream::connect(ssl, s).is_err()); + assert!(ssl.connect(s).is_err()); } From bd0c0c60bd5aed184a2b915dfb0d4a85f8a09cd1 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 20 Oct 2016 20:57:53 -0700 Subject: [PATCH 064/186] Store a MidHandshakeSslStream in fatal errors This in particular allows the X509 verification error to be retrieved, as well as the stream itself. --- openssl/src/ssl/mod.rs | 55 ++++++++++++++++++++++++++++++------------ 1 file changed, 39 insertions(+), 16 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 3e05a5c9..83c7b7a1 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -761,9 +761,12 @@ unsafe impl<'a> Sync for SslRef<'a> {} impl<'a> fmt::Debug for SslRef<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("SslRef") - .field("state", &self.state_string_long()) - .finish() + let mut builder = fmt.debug_struct("SslRef"); + builder.field("state", &self.state_string_long()); + if let Some(err) = self.verify_result() { + builder.field("verify_result", &err); + } + builder.finish() } } @@ -1008,9 +1011,12 @@ pub struct Ssl(SslRef<'static>); impl fmt::Debug for Ssl { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("Ssl") - .field("state", &self.state_string_long()) - .finish() + let mut builder = fmt.debug_struct("Ssl"); + builder.field("state", &self.state_string_long()); + if let Some(err) = self.verify_result() { + builder.field("verify_result", &err); + } + builder.finish() } } @@ -1063,7 +1069,12 @@ impl Ssl { error: e, })) } - err => Err(HandshakeError::Failure(err)), + err => { + Err(HandshakeError::Failure(MidHandshakeSslStream { + stream: stream, + error: err, + })) + } } } } @@ -1085,7 +1096,12 @@ impl Ssl { error: e, })) } - err => Err(HandshakeError::Failure(err)), + err => { + Err(HandshakeError::Failure(MidHandshakeSslStream { + stream: stream, + error: err, + })) + } } } } @@ -1156,7 +1172,7 @@ impl SslStream { #[derive(Debug)] pub enum HandshakeError { /// The handshake failed. - Failure(Error), + Failure(MidHandshakeSslStream), /// The handshake was interrupted midway through. Interrupted(MidHandshakeSslStream), } @@ -1164,15 +1180,14 @@ pub enum HandshakeError { impl stderror::Error for HandshakeError { fn description(&self) -> &str { match *self { - HandshakeError::Failure(ref e) => e.description(), - HandshakeError::Interrupted(ref e) => e.error.description(), + HandshakeError::Failure(_) => "the handshake failed", + HandshakeError::Interrupted(_) => "the handshake was interrupted", } } fn cause(&self) -> Option<&stderror::Error> { match *self { - HandshakeError::Failure(ref e) => Some(e), - HandshakeError::Interrupted(ref e) => Some(&e.error), + HandshakeError::Failure(ref s) | HandshakeError::Interrupted(ref s) => Some(s.error()), } } } @@ -1180,8 +1195,13 @@ impl stderror::Error for HandshakeError { impl fmt::Display for HandshakeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(f.write_str(stderror::Error::description(self))); - if let Some(e) = stderror::Error::cause(self) { - try!(write!(f, ": {}", e)); + match *self { + HandshakeError::Failure(ref s) | HandshakeError::Interrupted(ref s) => { + try!(write!(f, ": {}", s.error())); + if let Some(err) = s.ssl().verify_result() { + try!(write!(f, ": {}", err)); + } + } } Ok(()) } @@ -1227,7 +1247,10 @@ impl MidHandshakeSslStream { self.error = e; Err(HandshakeError::Interrupted(self)) } - err => Err(HandshakeError::Failure(err)), + err => { + self.error = err; + Err(HandshakeError::Failure(self)) + } } } } From b3eb8d516ca1f112fec37436bab56a061a934244 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 20 Oct 2016 22:41:42 -0700 Subject: [PATCH 065/186] Switch X509Name over to new borrow setup The use of actual references enables us to be correct with respect to mutability without needing two structs for the mutable and immutable cases and more deref impls. --- openssl/src/lib.rs | 1 + openssl/src/opaque.rs | 6 ++++++ openssl/src/x509/mod.rs | 27 +++++++++++++++++++-------- 3 files changed, 26 insertions(+), 8 deletions(-) create mode 100644 openssl/src/opaque.rs diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index 39c9fffe..10f450dd 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -32,6 +32,7 @@ pub mod nid; pub mod ssl; pub mod version; pub mod x509; +mod opaque; pub fn cvt_p(r: *mut T) -> Result<*mut T, ErrorStack> { if r.is_null() { diff --git a/openssl/src/opaque.rs b/openssl/src/opaque.rs new file mode 100644 index 00000000..9545471c --- /dev/null +++ b/openssl/src/opaque.rs @@ -0,0 +1,6 @@ +use std::cell::UnsafeCell; + +/// This is intended to be used as the inner type for types designed to be pointed to by references +/// converted from raw C pointers. It has an `UnsafeCell` internally to inform the compiler about +/// aliasability and doesn't implement `Copy`, so it can't be dereferenced. +pub struct Opaque(UnsafeCell<()>); diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 7f891231..51c1ab29 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -18,9 +18,10 @@ use bio::{MemBio, MemBioSlice}; use crypto::hash::MessageDigest; use crypto::pkey::PKey; use crypto::rand::rand_bytes; +use error::ErrorStack; use ffi; use nid::Nid; -use error::ErrorStack; +use opaque::Opaque; #[cfg(ossl10x)] use ffi::{ @@ -401,9 +402,11 @@ impl<'a> X509Ref<'a> { self.0 } - pub fn subject_name<'b>(&'b self) -> X509Name<'b> { - let name = unsafe { ffi::X509_get_subject_name(self.0) }; - X509Name(name, PhantomData) + pub fn subject_name(&self) -> &X509NameRef { + unsafe { + let name = ffi::X509_get_subject_name(self.0); + X509NameRef::from_ptr(name) + } } /// Returns this certificate's SAN entries, if they exist. @@ -534,17 +537,25 @@ impl Drop for X509 { } } -pub struct X509Name<'x>(*mut ffi::X509_NAME, PhantomData<&'x ()>); +pub struct X509NameRef(Opaque); + +impl X509NameRef { + pub unsafe fn from_ptr<'a>(ptr: *mut ffi::X509_NAME) -> &'a X509NameRef { + &*(ptr as *mut _) + } + + pub fn as_ptr(&self) -> *mut ffi::X509_NAME { + self as *const _ as *mut _ + } -impl<'x> X509Name<'x> { pub fn text_by_nid(&self, nid: Nid) -> Option { unsafe { - let loc = ffi::X509_NAME_get_index_by_NID(self.0, nid as c_int, -1); + let loc = ffi::X509_NAME_get_index_by_NID(self.as_ptr(), nid as c_int, -1); if loc == -1 { return None; } - let ne = ffi::X509_NAME_get_entry(self.0, loc); + let ne = ffi::X509_NAME_get_entry(self.as_ptr(), loc); if ne.is_null() { return None; } From 23fc6c828bdfc7322d6e4c9a0ac8b4047f69df0f Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 21 Oct 2016 17:01:13 -0700 Subject: [PATCH 066/186] Convert X509Ref --- openssl/src/x509/mod.rs | 44 +++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 51c1ab29..99710fc4 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -107,7 +107,7 @@ impl X509StoreContext { } } - pub fn current_cert<'a>(&'a self) -> Option> { + pub fn current_cert<'a>(&'a self) -> Option<&'a X509Ref> { unsafe { let ptr = ffi::X509_STORE_CTX_get_current_cert(self.ctx); if ptr.is_null() { @@ -390,21 +390,21 @@ impl X509Generator { } /// A borrowed public key certificate. -pub struct X509Ref<'a>(*mut ffi::X509, PhantomData<&'a ()>); +pub struct X509Ref(Opaque); -impl<'a> X509Ref<'a> { +impl X509Ref { /// Creates a new `X509Ref` wrapping the provided handle. - pub unsafe fn from_ptr(x509: *mut ffi::X509) -> X509Ref<'a> { - X509Ref(x509, PhantomData) + pub unsafe fn from_ptr<'a>(x509: *mut ffi::X509) -> &'a X509Ref { + &*(x509 as *mut _) } pub fn as_ptr(&self) -> *mut ffi::X509 { - self.0 + self as *const _ as *mut _ } pub fn subject_name(&self) -> &X509NameRef { unsafe { - let name = ffi::X509_get_subject_name(self.0); + let name = ffi::X509_get_subject_name(self.as_ptr()); X509NameRef::from_ptr(name) } } @@ -412,7 +412,7 @@ impl<'a> X509Ref<'a> { /// Returns this certificate's SAN entries, if they exist. pub fn subject_alt_names(&self) -> Option { unsafe { - let stack = ffi::X509_get_ext_d2i(self.0, + let stack = ffi::X509_get_ext_d2i(self.as_ptr(), Nid::SubjectAltName as c_int, ptr::null_mut(), ptr::null_mut()); @@ -428,7 +428,7 @@ impl<'a> X509Ref<'a> { pub fn public_key(&self) -> Result { unsafe { - let pkey = try!(cvt_p(ffi::X509_get_pubkey(self.0))); + let pkey = try!(cvt_p(ffi::X509_get_pubkey(self.as_ptr()))); Ok(PKey::from_ptr(pkey)) } } @@ -439,25 +439,25 @@ impl<'a> X509Ref<'a> { let evp = hash_type.as_ptr(); let mut len = ffi::EVP_MAX_MD_SIZE; let mut buf = vec![0u8; len as usize]; - try!(cvt(ffi::X509_digest(self.0, evp, buf.as_mut_ptr() as *mut _, &mut len))); + try!(cvt(ffi::X509_digest(self.as_ptr(), evp, buf.as_mut_ptr() as *mut _, &mut len))); buf.truncate(len as usize); Ok(buf) } } /// Returns certificate Not After validity period. - pub fn not_after<'b>(&'b self) -> Asn1TimeRef<'b> { + pub fn not_after<'a>(&'a self) -> Asn1TimeRef<'a> { unsafe { - let date = compat::X509_get_notAfter(self.0); + let date = compat::X509_get_notAfter(self.as_ptr()); assert!(!date.is_null()); Asn1TimeRef::from_ptr(date) } } /// Returns certificate Not Before validity period. - pub fn not_before<'b>(&'b self) -> Asn1TimeRef<'b> { + pub fn not_before<'a>(&'a self) -> Asn1TimeRef<'a> { unsafe { - let date = compat::X509_get_notBefore(self.0); + let date = compat::X509_get_notBefore(self.as_ptr()); assert!(!date.is_null()); Asn1TimeRef::from_ptr(date) } @@ -467,7 +467,7 @@ impl<'a> X509Ref<'a> { pub fn to_pem(&self) -> Result, ErrorStack> { let mem_bio = try!(MemBio::new()); unsafe { - try!(cvt(ffi::PEM_write_bio_X509(mem_bio.as_ptr(), self.0))); + try!(cvt(ffi::PEM_write_bio_X509(mem_bio.as_ptr(), self.as_ptr()))); } Ok(mem_bio.get_buf().to_owned()) } @@ -476,19 +476,19 @@ impl<'a> X509Ref<'a> { pub fn to_der(&self) -> Result, ErrorStack> { let mem_bio = try!(MemBio::new()); unsafe { - ffi::i2d_X509_bio(mem_bio.as_ptr(), self.0); + ffi::i2d_X509_bio(mem_bio.as_ptr(), self.as_ptr()); } Ok(mem_bio.get_buf().to_owned()) } } /// An owned public key certificate. -pub struct X509(X509Ref<'static>); +pub struct X509(*mut ffi::X509); impl X509 { /// Returns a new `X509`, taking ownership of the handle. pub unsafe fn from_ptr(x509: *mut ffi::X509) -> X509 { - X509(X509Ref::from_ptr(x509)) + X509(x509) } /// Reads a certificate from DER. @@ -515,10 +515,12 @@ impl X509 { } impl Deref for X509 { - type Target = X509Ref<'static>; + type Target = X509Ref; - fn deref(&self) -> &X509Ref<'static> { - &self.0 + fn deref(&self) -> &X509Ref { + unsafe { + X509Ref::from_ptr(self.0) + } } } From b7017a7eecf57aa6f1ab18ea1da771bafcab2ea9 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 21 Oct 2016 17:13:30 -0700 Subject: [PATCH 067/186] Update Asn1TimeRef --- openssl/src/asn1.rs | 67 ++++++++++++++++++++++------------------- openssl/src/x509/mod.rs | 4 +-- 2 files changed, 38 insertions(+), 33 deletions(-) diff --git a/openssl/src/asn1.rs b/openssl/src/asn1.rs index 91f920a3..7e7cb3df 100644 --- a/openssl/src/asn1.rs +++ b/openssl/src/asn1.rs @@ -2,19 +2,48 @@ use libc::c_long; use std::{ptr, fmt}; use std::marker::PhantomData; use std::ops::Deref; + use ffi; +use opaque::Opaque; use {cvt, cvt_p}; use bio::MemBio; use error::ErrorStack; +/// A borrowed Asn1Time +pub struct Asn1TimeRef(Opaque); + +impl Asn1TimeRef { + /// Creates a new `Asn1TimeRef` wrapping the provided handle. + pub unsafe fn from_ptr<'a>(handle: *mut ffi::ASN1_TIME) -> &'a Asn1TimeRef { + &*(handle as *mut _) + } + + /// Returns the raw handle + pub fn as_ptr(&self) -> *mut ffi::ASN1_TIME { + self as *const _ as *mut _ + } +} + +impl fmt::Display for Asn1TimeRef { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mem_bio = try!(MemBio::new()); + let as_str = unsafe { + try!(cvt(ffi::ASN1_TIME_print(mem_bio.as_ptr(), self.as_ptr()))); + String::from_utf8_unchecked(mem_bio.get_buf().to_owned()) + }; + write!(f, "{}", as_str) + } +} + + /// Corresponds to the ASN.1 structure Time defined in RFC5280 -pub struct Asn1Time(Asn1TimeRef<'static>); +pub struct Asn1Time(*mut ffi::ASN1_TIME); impl Asn1Time { /// Wraps existing ASN1_TIME and takes ownership pub unsafe fn from_ptr(handle: *mut ffi::ASN1_TIME) -> Asn1Time { - Asn1Time(Asn1TimeRef::from_ptr(handle)) + Asn1Time(handle) } fn from_period(period: c_long) -> Result { @@ -33,36 +62,12 @@ impl Asn1Time { } impl Deref for Asn1Time { - type Target = Asn1TimeRef<'static>; + type Target = Asn1TimeRef; - fn deref(&self) -> &Asn1TimeRef<'static> { - &self.0 - } -} - -/// A borrowed Asn1Time -pub struct Asn1TimeRef<'a>(*mut ffi::ASN1_TIME, PhantomData<&'a ()>); - -impl<'a> Asn1TimeRef<'a> { - /// Creates a new `Asn1TimeRef` wrapping the provided handle. - pub unsafe fn from_ptr(handle: *mut ffi::ASN1_TIME) -> Asn1TimeRef<'a> { - Asn1TimeRef(handle, PhantomData) - } - - /// Returns the raw handle - pub fn as_ptr(&self) -> *mut ffi::ASN1_TIME { - self.0 - } -} - -impl<'a> fmt::Display for Asn1TimeRef<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mem_bio = try!(MemBio::new()); - let as_str = unsafe { - try!(cvt(ffi::ASN1_TIME_print(mem_bio.as_ptr(), self.0))); - String::from_utf8_unchecked(mem_bio.get_buf().to_owned()) - }; - write!(f, "{}", as_str) + fn deref(&self) -> &Asn1TimeRef { + unsafe { + Asn1TimeRef::from_ptr(self.0) + } } } diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 99710fc4..9c91bfc1 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -446,7 +446,7 @@ impl X509Ref { } /// Returns certificate Not After validity period. - pub fn not_after<'a>(&'a self) -> Asn1TimeRef<'a> { + pub fn not_after<'a>(&'a self) -> &'a Asn1TimeRef { unsafe { let date = compat::X509_get_notAfter(self.as_ptr()); assert!(!date.is_null()); @@ -455,7 +455,7 @@ impl X509Ref { } /// Returns certificate Not Before validity period. - pub fn not_before<'a>(&'a self) -> Asn1TimeRef<'a> { + pub fn not_before<'a>(&'a self) -> &'a Asn1TimeRef { unsafe { let date = compat::X509_get_notBefore(self.as_ptr()); assert!(!date.is_null()); From fe98a90719802d1503637f081c7b2a13f909483e Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 21 Oct 2016 19:15:09 -0700 Subject: [PATCH 068/186] Convert SslContextRef --- openssl/src/asn1.rs | 1 - openssl/src/ssl/mod.rs | 37 +++++++++++++++++++++++-------------- 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/openssl/src/asn1.rs b/openssl/src/asn1.rs index 7e7cb3df..e9c58e76 100644 --- a/openssl/src/asn1.rs +++ b/openssl/src/asn1.rs @@ -1,6 +1,5 @@ use libc::c_long; use std::{ptr, fmt}; -use std::marker::PhantomData; use std::ops::Deref; use ffi; diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 83c7b7a1..5218ac64 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -26,6 +26,7 @@ use x509::{X509StoreContext, X509FileType, X509, X509Ref, X509VerifyError}; use x509::verify::X509VerifyParamRef; use crypto::pkey::PKey; use error::ErrorStack; +use opaque::Opaque; pub mod error; mod bio; @@ -335,15 +336,19 @@ pub enum SniError { } /// A borrowed SSL context object. -pub struct SslContextRef<'a>(*mut ffi::SSL_CTX, PhantomData<&'a ()>); +pub struct SslContextRef(Opaque); -impl<'a> SslContextRef<'a> { - pub unsafe fn from_ptr(ctx: *mut ffi::SSL_CTX) -> SslContextRef<'a> { - SslContextRef(ctx, PhantomData) +impl SslContextRef { + pub unsafe fn from_ptr<'a>(ctx: *mut ffi::SSL_CTX) -> &'a SslContextRef { + &*(ctx as *mut _) + } + + pub unsafe fn from_ptr_mut<'a>(ctx: *mut ffi::SSL_CTX) -> &'a mut SslContextRef { + &mut *(ctx as *mut _) } pub fn as_ptr(&self) -> *mut ffi::SSL_CTX { - self.0 + self as *const _ as *mut _ } /// Configures the certificate verification method for new connections. @@ -626,7 +631,7 @@ impl<'a> SslContextRef<'a> { } /// An owned SSL context object. -pub struct SslContext(SslContextRef<'static>); +pub struct SslContext(*mut ffi::SSL_CTX); unsafe impl Send for SslContext {} unsafe impl Sync for SslContext {} @@ -654,16 +659,20 @@ impl Drop for SslContext { } impl Deref for SslContext { - type Target = SslContextRef<'static>; + type Target = SslContextRef; - fn deref(&self) -> &SslContextRef<'static> { - &self.0 + fn deref(&self) -> &SslContextRef { + unsafe { + SslContextRef::from_ptr(self.0) + } } } impl DerefMut for SslContext { - fn deref_mut(&mut self) -> &mut SslContextRef<'static> { - &mut self.0 + fn deref_mut(&mut self) -> &mut SslContextRef { + unsafe { + SslContextRef::from_ptr_mut(self.0) + } } } @@ -683,11 +692,11 @@ impl SslContext { } pub unsafe fn from_ptr(ctx: *mut ffi::SSL_CTX) -> SslContext { - SslContext(SslContextRef::from_ptr(ctx)) + SslContext(ctx) } pub fn as_ptr(&self) -> *mut ffi::SSL_CTX { - (**self).as_ptr() + self.0 } } @@ -982,7 +991,7 @@ impl<'a> SslRef<'a> { } /// Returns the context corresponding to the current connection - pub fn ssl_context(&self) -> SslContextRef<'a> { + pub fn ssl_context(&self) -> &SslContextRef { unsafe { let ssl_ctx = ffi::SSL_get_SSL_CTX(self.as_ptr()); SslContextRef::from_ptr(ssl_ctx) From 2bbeddd14a8050d4e03c08ffe60707a3ae21d5e0 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 21 Oct 2016 19:33:56 -0700 Subject: [PATCH 069/186] Convert SslRef --- openssl/src/ssl/mod.rs | 48 +++++++++++++++++++++--------------- openssl/src/ssl/tests/mod.rs | 2 +- 2 files changed, 29 insertions(+), 21 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 5218ac64..ce36b97d 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -211,9 +211,9 @@ extern fn raw_sni(ssl: *mut ffi::SSL, al: *mut c_int, _arg: *mut c_void) -> c let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_verify_data_idx::()); let callback: &F = &*(callback as *mut F); - let mut ssl = SslRef::from_ptr(ssl); + let ssl = SslRef::from_ptr_mut(ssl); - match callback(&mut ssl) { + match callback(ssl) { Ok(()) => ffi::SSL_TLSEXT_ERR_OK, Err(SniError::Fatal(e)) => { *al = e; @@ -763,12 +763,12 @@ impl<'a> SslCipher<'a> { } } -pub struct SslRef<'a>(*mut ffi::SSL, PhantomData<&'a ()>); +pub struct SslRef(Opaque); -unsafe impl<'a> Send for SslRef<'a> {} -unsafe impl<'a> Sync for SslRef<'a> {} +unsafe impl Send for SslRef {} +unsafe impl Sync for SslRef {} -impl<'a> fmt::Debug for SslRef<'a> { +impl fmt::Debug for SslRef { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let mut builder = fmt.debug_struct("SslRef"); builder.field("state", &self.state_string_long()); @@ -779,13 +779,17 @@ impl<'a> fmt::Debug for SslRef<'a> { } } -impl<'a> SslRef<'a> { - pub unsafe fn from_ptr(ssl: *mut ffi::SSL) -> SslRef<'a> { - SslRef(ssl, PhantomData) +impl SslRef { + pub unsafe fn from_ptr<'a>(ssl: *mut ffi::SSL) -> &'a SslRef { + &*(ssl as *mut _) + } + + pub unsafe fn from_ptr_mut<'a>(ssl: *mut ffi::SSL) -> &'a mut SslRef { + &mut *(ssl as *mut _) } pub fn as_ptr(&self) -> *mut ffi::SSL { - self.0 + self as *const _ as *mut _ } fn get_raw_rbio(&self) -> *mut ffi::BIO { @@ -832,7 +836,7 @@ impl<'a> SslRef<'a> { } } - pub fn current_cipher(&self) -> Option> { + pub fn current_cipher<'a>(&'a self) -> Option> { unsafe { let ptr = ffi::SSL_get_current_cipher(self.as_ptr()); @@ -1002,7 +1006,7 @@ impl<'a> SslRef<'a> { /// /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or 1.1.0. #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - pub fn param(&mut self) -> X509VerifyParamRef<'a> { + pub fn param<'a>(&'a mut self) -> X509VerifyParamRef<'a> { unsafe { X509VerifyParamRef::from_ptr(ffi::SSL_get0_param(self.as_ptr())) } @@ -1011,12 +1015,12 @@ impl<'a> SslRef<'a> { /// Returns the result of X509 certificate verification. pub fn verify_result(&self) -> Option { unsafe { - X509VerifyError::from_raw(ffi::SSL_get_verify_result(self.0)) + X509VerifyError::from_raw(ffi::SSL_get_verify_result(self.as_ptr())) } } } -pub struct Ssl(SslRef<'static>); +pub struct Ssl(*mut ffi::SSL); impl fmt::Debug for Ssl { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { @@ -1036,16 +1040,20 @@ impl Drop for Ssl { } impl Deref for Ssl { - type Target = SslRef<'static>; + type Target = SslRef; - fn deref(&self) -> &SslRef<'static> { - &self.0 + fn deref(&self) -> &SslRef { + unsafe { + SslRef::from_ptr(self.0) + } } } impl DerefMut for Ssl { - fn deref_mut(&mut self) -> &mut SslRef<'static> { - &mut self.0 + fn deref_mut(&mut self) -> &mut SslRef { + unsafe { + SslRef::from_ptr_mut(self.0) + } } } @@ -1058,7 +1066,7 @@ impl Ssl { } pub unsafe fn from_ptr(ssl: *mut ffi::SSL) -> Ssl { - Ssl(SslRef::from_ptr(ssl)) + Ssl(ssl) } /// Creates an SSL/TLS client operating over the provided stream. diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 94cea935..b255d01d 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -479,7 +479,7 @@ fn test_pending() { fn test_state() { let (_s, tcp) = Server::new(); let ctx = SslContext::new(SslMethod::tls()).unwrap(); - let mut stream = Ssl::new(&ctx).unwrap().connect(tcp).unwrap(); + let stream = Ssl::new(&ctx).unwrap().connect(tcp).unwrap(); assert_eq!(stream.ssl().state_string(), "SSLOK "); assert_eq!(stream.ssl().state_string_long(), "SSL negotiation finished successfully"); From fcb86b839456a2f925a663d55f95b75db6f36721 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 21 Oct 2016 19:45:46 -0700 Subject: [PATCH 070/186] Convert SslCipherRef --- openssl/src/ssl/mod.rs | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index ce36b97d..fbb03104 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -709,16 +709,21 @@ pub struct CipherBits { pub algorithm: i32, } -pub struct SslCipher<'a> { - cipher: *const ffi::SSL_CIPHER, - ph: PhantomData<&'a ()>, -} +pub struct SslCipherRef(Opaque); + +impl SslCipherRef { + pub unsafe fn from_ptr<'a>(ptr: *const ffi::SSL_CIPHER) -> &'a SslCipherRef { + &*(ptr as *const _) + } + + pub fn as_ptr(&self) -> *const ffi::SSL_CIPHER { + self as *const _ as *const _ + } -impl<'a> SslCipher<'a> { /// Returns the name of cipher. pub fn name(&self) -> &'static str { let name = unsafe { - let ptr = ffi::SSL_CIPHER_get_name(self.cipher); + let ptr = ffi::SSL_CIPHER_get_name(self.as_ptr()); CStr::from_ptr(ptr as *const _) }; @@ -728,7 +733,7 @@ impl<'a> SslCipher<'a> { /// Returns the SSL/TLS protocol version that first defined the cipher. pub fn version(&self) -> &'static str { let version = unsafe { - let ptr = ffi::SSL_CIPHER_get_version(self.cipher); + let ptr = ffi::SSL_CIPHER_get_version(self.as_ptr()); CStr::from_ptr(ptr as *const _) }; @@ -739,7 +744,7 @@ impl<'a> SslCipher<'a> { pub fn bits(&self) -> CipherBits { unsafe { let mut algo_bits = 0; - let secret_bits = ffi::SSL_CIPHER_get_bits(self.cipher, &mut algo_bits); + let secret_bits = ffi::SSL_CIPHER_get_bits(self.as_ptr(), &mut algo_bits); CipherBits { secret: secret_bits.into(), algorithm: algo_bits.into(), @@ -752,7 +757,7 @@ impl<'a> SslCipher<'a> { unsafe { // SSL_CIPHER_description requires a buffer of at least 128 bytes. let mut buf = [0; 128]; - let desc_ptr = ffi::SSL_CIPHER_description(self.cipher, buf.as_mut_ptr(), 128); + let desc_ptr = ffi::SSL_CIPHER_description(self.as_ptr(), buf.as_mut_ptr(), 128); if !desc_ptr.is_null() { String::from_utf8(CStr::from_ptr(desc_ptr as *const _).to_bytes().to_vec()).ok() @@ -836,17 +841,14 @@ impl SslRef { } } - pub fn current_cipher<'a>(&'a self) -> Option> { + pub fn current_cipher(&self) -> Option<&SslCipherRef> { unsafe { let ptr = ffi::SSL_get_current_cipher(self.as_ptr()); if ptr.is_null() { None } else { - Some(SslCipher { - cipher: ptr, - ph: PhantomData, - }) + Some(SslCipherRef::from_ptr(ptr)) } } } From f0cde389290d7ec20a9650a09096b742c6b9aa1f Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 21 Oct 2016 19:54:30 -0700 Subject: [PATCH 071/186] Borrowed servername --- openssl/src/ssl/mod.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index fbb03104..d03b495f 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -980,13 +980,15 @@ impl SslRef { } /// Returns the server's name for the current connection - pub fn servername(&self) -> Option { - let name = unsafe { ffi::SSL_get_servername(self.as_ptr(), ffi::TLSEXT_NAMETYPE_host_name) }; - if name == ptr::null() { - return None; - } + pub fn servername(&self) -> Option<&str> { + unsafe { + let name = ffi::SSL_get_servername(self.as_ptr(), ffi::TLSEXT_NAMETYPE_host_name); + if name == ptr::null() { + return None; + } - unsafe { String::from_utf8(CStr::from_ptr(name as *const _).to_bytes().to_vec()).ok() } + Some(str::from_utf8(CStr::from_ptr(name as *const _).to_bytes()).unwrap()) + } } /// Changes the context corresponding to the current connection. From 02b4385c5d18534d7b02a3ebc3323b662251c36e Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 21 Oct 2016 19:58:06 -0700 Subject: [PATCH 072/186] Convert X509VerifyParamRef --- openssl/src/ssl/mod.rs | 4 ++-- openssl/src/ssl/tests/mod.rs | 8 ++++---- openssl/src/x509/verify.rs | 17 +++++++++++------ 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index d03b495f..26cafa9a 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -1010,9 +1010,9 @@ impl SslRef { /// /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or 1.1.0. #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - pub fn param<'a>(&'a mut self) -> X509VerifyParamRef<'a> { + pub fn param_mut(&mut self) -> &mut X509VerifyParamRef { unsafe { - X509VerifyParamRef::from_ptr(ffi::SSL_get0_param(self.as_ptr())) + X509VerifyParamRef::from_ptr_mut(ffi::SSL_get0_param(self.as_ptr())) } } diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index b255d01d..684f77ac 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -1053,8 +1053,8 @@ fn valid_hostname() { ctx.set_verify(SSL_VERIFY_PEER); let mut ssl = Ssl::new(&ctx).unwrap(); - ssl.param().set_hostflags(X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); - ssl.param().set_host("google.com").unwrap(); + ssl.param_mut().set_hostflags(X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); + ssl.param_mut().set_host("google.com").unwrap(); let s = TcpStream::connect("google.com:443").unwrap(); let mut socket = ssl.connect(s).unwrap(); @@ -1077,8 +1077,8 @@ fn invalid_hostname() { ctx.set_verify(SSL_VERIFY_PEER); let mut ssl = Ssl::new(&ctx).unwrap(); - ssl.param().set_hostflags(X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); - ssl.param().set_host("foobar.com").unwrap(); + ssl.param_mut().set_hostflags(X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); + ssl.param_mut().set_host("foobar.com").unwrap(); let s = TcpStream::connect("google.com:443").unwrap(); assert!(ssl.connect(s).is_err()); diff --git a/openssl/src/x509/verify.rs b/openssl/src/x509/verify.rs index be8d3d7e..11c65dca 100644 --- a/openssl/src/x509/verify.rs +++ b/openssl/src/x509/verify.rs @@ -8,6 +8,7 @@ use ffi; use cvt; use error::ErrorStack; +use opaque::Opaque; bitflags! { pub flags X509CheckFlags: c_uint { @@ -23,22 +24,26 @@ bitflags! { } } -pub struct X509VerifyParamRef<'a>(*mut ffi::X509_VERIFY_PARAM, PhantomData<&'a mut ()>); +pub struct X509VerifyParamRef(Opaque); -impl<'a> X509VerifyParamRef<'a> { - pub unsafe fn from_ptr(ptr: *mut ffi::X509_VERIFY_PARAM) -> X509VerifyParamRef<'a> { - X509VerifyParamRef(ptr, PhantomData) +impl X509VerifyParamRef { + pub unsafe fn from_ptr_mut<'a>(ptr: *mut ffi::X509_VERIFY_PARAM) -> &'a mut X509VerifyParamRef { + &mut *(ptr as *mut _) + } + + pub fn as_ptr(&self) -> *mut ffi::X509_VERIFY_PARAM { + self as *const _ as *mut _ } pub fn set_hostflags(&mut self, hostflags: X509CheckFlags) { unsafe { - ffi::X509_VERIFY_PARAM_set_hostflags(self.0, hostflags.bits); + ffi::X509_VERIFY_PARAM_set_hostflags(self.as_ptr(), hostflags.bits); } } pub fn set_host(&mut self, host: &str) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::X509_VERIFY_PARAM_set1_host(self.0, + cvt(ffi::X509_VERIFY_PARAM_set1_host(self.as_ptr(), host.as_ptr() as *const _, host.len())) .map(|_| ()) From 6f1a3f2834b45a546edd0a3e736b498599c996bb Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 21 Oct 2016 20:26:53 -0700 Subject: [PATCH 073/186] Update BigNumRef --- openssl/src/bn.rs | 174 +++++++++++++++++++------------------ openssl/src/crypto/dsa.rs | 6 +- openssl/src/crypto/rsa.rs | 10 +-- openssl/src/x509/verify.rs | 1 - 4 files changed, 97 insertions(+), 94 deletions(-) diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs index 512c58d3..700367bd 100644 --- a/openssl/src/bn.rs +++ b/openssl/src/bn.rs @@ -3,11 +3,11 @@ use libc::{c_int, c_void}; use std::cmp::Ordering; use std::ffi::{CStr, CString}; use std::{fmt, ptr}; -use std::marker::PhantomData; use std::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub, Deref, DerefMut}; use {cvt, cvt_p, cvt_n}; use error::ErrorStack; +use opaque::Opaque; /// Specifies the desired properties of a randomly generated `BigNum`. #[derive(Copy, Clone)] @@ -41,6 +41,10 @@ impl BnCtx { } } + pub fn as_ptr(&self) -> *mut ffi::BN_CTX { + self.0 + } + /// Places the result of `a * b` in `r`. pub fn mul(&mut self, r: &mut BigNumRef, @@ -48,7 +52,7 @@ impl BnCtx { b: &BigNumRef) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_mul(r.0, a.0, b.0, self.0)).map(|_| ()) + cvt(ffi::BN_mul(r.as_ptr(), a.as_ptr(), b.as_ptr(), self.as_ptr())).map(|_| ()) } } @@ -60,11 +64,11 @@ impl BnCtx { b: &BigNumRef) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_div(dv.map(|b| b.0).unwrap_or(ptr::null_mut()), - rem.map(|b| b.0).unwrap_or(ptr::null_mut()), - a.0, - b.0, - self.0)) + cvt(ffi::BN_div(dv.map(|b| b.as_ptr()).unwrap_or(ptr::null_mut()), + rem.map(|b| b.as_ptr()).unwrap_or(ptr::null_mut()), + a.as_ptr(), + b.as_ptr(), + self.as_ptr())) .map(|_| ()) } } @@ -72,7 +76,7 @@ impl BnCtx { /// Places the result of `a²` in `r`. pub fn sqr(&mut self, r: &mut BigNumRef, a: &BigNumRef) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_sqr(r.as_ptr(), a.as_ptr(), self.0)).map(|_| ()) + cvt(ffi::BN_sqr(r.as_ptr(), a.as_ptr(), self.as_ptr())).map(|_| ()) } } @@ -159,7 +163,7 @@ impl BnCtx { a: &BigNumRef, n: &BigNumRef) -> Result<(), ErrorStack> { unsafe { - cvt_p(ffi::BN_mod_inverse(r.0, a.0, n.0, self.0)).map(|_| ()) + cvt_p(ffi::BN_mod_inverse(r.as_ptr(), a.as_ptr(), n.as_ptr(), self.as_ptr())).map(|_| ()) } } @@ -169,7 +173,7 @@ impl BnCtx { a: &BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_gcd(r.0, a.0, b.0, self.0)).map(|_| ()) + cvt(ffi::BN_gcd(r.as_ptr(), a.as_ptr(), b.as_ptr(), self.as_ptr())).map(|_| ()) } } @@ -180,7 +184,7 @@ impl BnCtx { /// Returns `true` if `p` is prime with an error probability of less than `0.25 ^ checks`. pub fn is_prime(&mut self, p: &BigNumRef, checks: i32) -> Result { unsafe { - cvt_n(ffi::BN_is_prime_ex(p.0, checks.into(), self.0, ptr::null_mut())).map(|r| r != 0) + cvt_n(ffi::BN_is_prime_ex(p.as_ptr(), checks.into(), self.as_ptr(), ptr::null_mut())).map(|r| r != 0) } } @@ -198,9 +202,9 @@ impl BnCtx { checks: i32, do_trial_division: bool) -> Result { unsafe { - cvt_n(ffi::BN_is_prime_fasttest_ex(p.0, + cvt_n(ffi::BN_is_prime_fasttest_ex(p.as_ptr(), checks.into(), - self.0, + self.as_ptr(), do_trial_division as c_int, ptr::null_mut())) .map(|r| r != 0) @@ -220,7 +224,7 @@ impl BnCtx { odd: bool) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_rand(r.0, bits.into(), prop as c_int, odd as c_int)).map(|_| ()) + cvt(ffi::BN_rand(r.as_ptr(), bits.into(), prop as c_int, odd as c_int)).map(|_| ()) } } @@ -231,45 +235,52 @@ impl BnCtx { odd: bool) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_pseudo_rand(r.0, bits.into(), prop as c_int, odd as c_int)).map(|_| ()) + cvt(ffi::BN_pseudo_rand(r.as_ptr(), bits.into(), prop as c_int, odd as c_int)).map(|_| ()) } } } /// A borrowed, signed, arbitrary-precision integer. -#[derive(Copy, Clone)] -pub struct BigNumRef<'a>(*mut ffi::BIGNUM, PhantomData<&'a ()>); +pub struct BigNumRef(Opaque); -impl<'a> BigNumRef<'a> { - pub unsafe fn from_ptr(handle: *mut ffi::BIGNUM) -> BigNumRef<'a> { - BigNumRef(handle, PhantomData) +impl BigNumRef { + pub unsafe fn from_ptr<'a>(handle: *mut ffi::BIGNUM) -> &'a BigNumRef { + &*(handle as *mut _) + } + + pub unsafe fn from_ptr_mut<'a>(handle: *mut ffi::BIGNUM) -> &'a mut BigNumRef { + &mut *(handle as *mut _) + } + + pub fn as_ptr(&self) -> *mut ffi::BIGNUM { + self as *const _ as *mut _ } /// Adds a `u32` to `self`. pub fn add_word(&mut self, w: u32) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_add_word(self.0, w as ffi::BN_ULONG)).map(|_| ()) + cvt(ffi::BN_add_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) } } /// Subtracts a `u32` from `self`. pub fn sub_word(&mut self, w: u32) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_sub_word(self.0, w as ffi::BN_ULONG)).map(|_| ()) + cvt(ffi::BN_sub_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) } } /// Multiplies a `u32` by `self`. pub fn mul_word(&mut self, w: u32) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_mul_word(self.0, w as ffi::BN_ULONG)).map(|_| ()) + cvt(ffi::BN_mul_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) } } /// Divides `self` by a `u32`, returning the remainder. pub fn div_word(&mut self, w: u32) -> Result { unsafe { - let r = ffi::BN_div_word(self.0, w.into()); + let r = ffi::BN_div_word(self.as_ptr(), w.into()); if r == ffi::BN_ULONG::max_value() { Err(ErrorStack::get()) } else { @@ -281,7 +292,7 @@ impl<'a> BigNumRef<'a> { /// Returns the result of `self` modulo `w`. pub fn mod_word(&self, w: u32) -> Result { unsafe { - let r = ffi::BN_mod_word(self.0, w.into()); + let r = ffi::BN_mod_word(self.as_ptr(), w.into()); if r == ffi::BN_ULONG::max_value() { Err(ErrorStack::get()) } else { @@ -294,14 +305,14 @@ impl<'a> BigNumRef<'a> { /// number less than `self` in `rnd`. pub fn rand_in_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_rand_range(self.0, rnd.0)).map(|_| ()) + cvt(ffi::BN_rand_range(self.as_ptr(), rnd.as_ptr())).map(|_| ()) } } /// The cryptographically weak counterpart to `rand_in_range`. pub fn pseudo_rand_in_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_pseudo_rand_range(self.0, rnd.0)).map(|_| ()) + cvt(ffi::BN_pseudo_rand_range(self.as_ptr(), rnd.as_ptr())).map(|_| ()) } } @@ -310,7 +321,7 @@ impl<'a> BigNumRef<'a> { /// When setting a bit outside of `self`, it is expanded. pub fn set_bit(&mut self, n: i32) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_set_bit(self.0, n.into())).map(|_| ()) + cvt(ffi::BN_set_bit(self.as_ptr(), n.into())).map(|_| ()) } } @@ -319,14 +330,14 @@ impl<'a> BigNumRef<'a> { /// When clearing a bit outside of `self`, an error is returned. pub fn clear_bit(&mut self, n: i32) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_clear_bit(self.0, n.into())).map(|_| ()) + cvt(ffi::BN_clear_bit(self.as_ptr(), n.into())).map(|_| ()) } } /// Returns `true` if the `n`th bit of `self` is set to 1, `false` otherwise. pub fn is_bit_set(&self, n: i32) -> bool { unsafe { - ffi::BN_is_bit_set(self.0, n.into()) == 1 + ffi::BN_is_bit_set(self.as_ptr(), n.into()) == 1 } } @@ -335,62 +346,62 @@ impl<'a> BigNumRef<'a> { /// An error occurs if `self` is already shorter than `n` bits. pub fn mask_bits(&mut self, n: i32) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_mask_bits(self.0, n.into())).map(|_| ()) + cvt(ffi::BN_mask_bits(self.as_ptr(), n.into())).map(|_| ()) } } /// Places `self << 1` in `r`. pub fn lshift1(&self, r: &mut BigNumRef) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_lshift1(r.0, self.0)).map(|_| ()) + cvt(ffi::BN_lshift1(r.as_ptr(), self.as_ptr())).map(|_| ()) } } /// Places `self >> 1` in `r`. pub fn rshift1(&self, r: &mut BigNumRef) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_rshift1(r.0, self.0)).map(|_| ()) + cvt(ffi::BN_rshift1(r.as_ptr(), self.as_ptr())).map(|_| ()) } } /// Places `self + b` in `r`. pub fn add(&self, r: &mut BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_add(r.0, self.0, b.0)).map(|_| ()) + cvt(ffi::BN_add(r.as_ptr(), self.as_ptr(), b.as_ptr())).map(|_| ()) } } /// Places `self - b` in `r`. pub fn sub(&self, r: &mut BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_sub(r.0, self.0, b.0)).map(|_| ()) + cvt(ffi::BN_sub(r.as_ptr(), self.as_ptr(), b.as_ptr())).map(|_| ()) } } /// Places `self << n` in `r`. pub fn lshift(&self, r: &mut BigNumRef, b: i32) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_lshift(r.0, self.0, b.into())).map(|_| ()) + cvt(ffi::BN_lshift(r.as_ptr(), self.as_ptr(), b.into())).map(|_| ()) } } /// Places `self >> n` in `r`. pub fn rshift(&self, r: &mut BigNumRef, n: i32) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_rshift(r.0, self.0, n.into())).map(|_| ()) + cvt(ffi::BN_rshift(r.as_ptr(), self.as_ptr(), n.into())).map(|_| ()) } } pub fn to_owned(&self) -> Result { unsafe { - cvt_p(ffi::BN_dup(self.0)).map(|b| BigNum::from_ptr(b)) + cvt_p(ffi::BN_dup(self.as_ptr())).map(|b| BigNum::from_ptr(b)) } } /// Sets the sign of `self`. pub fn set_negative(&mut self, negative: bool) { unsafe { - ffi::BN_set_negative(self.0, negative as c_int) + ffi::BN_set_negative(self.as_ptr(), negative as c_int) } } @@ -406,14 +417,7 @@ impl<'a> BigNumRef<'a> { /// ``` pub fn ucmp(&self, oth: &BigNumRef) -> Ordering { unsafe { - let res = ffi::BN_ucmp(self.as_ptr(), oth.as_ptr()); - if res < 0 { - Ordering::Less - } else if res > 0 { - Ordering::Greater - } else { - Ordering::Equal - } + ffi::BN_ucmp(self.as_ptr(), oth.as_ptr()).cmp(&0) } } @@ -441,10 +445,6 @@ impl<'a> BigNumRef<'a> { (self.num_bits() + 7) / 8 } - pub fn as_ptr(&self) -> *mut ffi::BIGNUM { - self.0 - } - /// Returns a big-endian byte vector representation of the absolute value of `self`. /// /// `self` can be recreated by using `new_from_slice`. @@ -510,7 +510,7 @@ impl<'a> BigNumRef<'a> { /// Additionally, it implements the standard operators (`std::ops`), which /// perform unchecked arithmetic, unwrapping the returned `Result` of the /// checked operations. -pub struct BigNum(BigNumRef<'static>); +pub struct BigNum(*mut ffi::BIGNUM); impl BigNum { /// Creates a new `BigNum` with the value 0. @@ -550,7 +550,7 @@ impl BigNum { } pub unsafe fn from_ptr(handle: *mut ffi::BIGNUM) -> BigNum { - BigNum(BigNumRef::from_ptr(handle)) + BigNum(handle) } /// Creates a new `BigNum` from an unsigned, big-endian encoded number of arbitrary length. @@ -584,11 +584,11 @@ impl BigNum { rem: Option<&BigNumRef>) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_generate_prime_ex(r.0, + cvt(ffi::BN_generate_prime_ex(r.as_ptr(), bits as c_int, safe as c_int, - add.map(|n| n.0).unwrap_or(ptr::null_mut()), - rem.map(|n| n.0).unwrap_or(ptr::null_mut()), + add.map(|n| n.as_ptr()).unwrap_or(ptr::null_mut()), + rem.map(|n| n.as_ptr()).unwrap_or(ptr::null_mut()), ptr::null_mut())) .map(|_| ()) } @@ -602,26 +602,30 @@ impl Drop for BigNum { } impl Deref for BigNum { - type Target = BigNumRef<'static>; + type Target = BigNumRef; - fn deref(&self) -> &BigNumRef<'static> { - &self.0 + fn deref(&self) -> &BigNumRef { + unsafe { + BigNumRef::from_ptr(self.0) + } } } impl DerefMut for BigNum { - fn deref_mut(&mut self) -> &mut BigNumRef<'static> { - &mut self.0 + fn deref_mut(&mut self) -> &mut BigNumRef { + unsafe { + BigNumRef::from_ptr_mut(self.0) + } } } -impl AsRef> for BigNum { - fn as_ref(&self) -> &BigNumRef<'static> { +impl AsRef for BigNum { + fn as_ref(&self) -> &BigNumRef { self.deref() } } -impl<'a> fmt::Debug for BigNumRef<'a> { +impl fmt::Debug for BigNumRef { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.to_dec_str() { Ok(s) => f.write_str(&s), @@ -639,7 +643,7 @@ impl fmt::Debug for BigNum { } } -impl<'a> fmt::Display for BigNumRef<'a> { +impl fmt::Display for BigNumRef { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.to_dec_str() { Ok(s) => f.write_str(&s), @@ -657,19 +661,19 @@ impl fmt::Display for BigNum { } } -impl<'a, 'b> PartialEq> for BigNumRef<'a> { +impl PartialEq for BigNumRef { fn eq(&self, oth: &BigNumRef) -> bool { self.cmp(oth) == Ordering::Equal } } -impl<'a> PartialEq for BigNumRef<'a> { +impl PartialEq for BigNumRef { fn eq(&self, oth: &BigNum) -> bool { self.eq(oth.deref()) } } -impl<'a> Eq for BigNumRef<'a> {} +impl Eq for BigNumRef {} impl PartialEq for BigNum { fn eq(&self, oth: &BigNum) -> bool { @@ -677,7 +681,7 @@ impl PartialEq for BigNum { } } -impl<'a> PartialEq> for BigNum { +impl PartialEq for BigNum { fn eq(&self, oth: &BigNumRef) -> bool { self.deref().eq(oth) } @@ -685,19 +689,19 @@ impl<'a> PartialEq> for BigNum { impl Eq for BigNum {} -impl<'a, 'b> PartialOrd> for BigNumRef<'a> { +impl PartialOrd for BigNumRef { fn partial_cmp(&self, oth: &BigNumRef) -> Option { Some(self.cmp(oth)) } } -impl<'a> PartialOrd for BigNumRef<'a> { +impl PartialOrd for BigNumRef { fn partial_cmp(&self, oth: &BigNum) -> Option { Some(self.cmp(oth.deref())) } } -impl<'a> Ord for BigNumRef<'a> { +impl Ord for BigNumRef { fn cmp(&self, oth: &BigNumRef) -> Ordering { unsafe { ffi::BN_cmp(self.as_ptr(), oth.as_ptr()).cmp(&0) } } @@ -709,7 +713,7 @@ impl PartialOrd for BigNum { } } -impl<'a> PartialOrd> for BigNum { +impl PartialOrd for BigNum { fn partial_cmp(&self, oth: &BigNumRef) -> Option { self.deref().partial_cmp(oth) } @@ -723,7 +727,7 @@ impl Ord for BigNum { macro_rules! delegate { ($t:ident, $m:ident) => { - impl<'a, 'b> $t<&'b BigNum> for &'a BigNumRef<'a> { + impl<'a, 'b> $t<&'b BigNum> for &'a BigNumRef { type Output = BigNum; fn $m(self, oth: &BigNum) -> BigNum { @@ -731,7 +735,7 @@ macro_rules! delegate { } } - impl<'a, 'b> $t<&'b BigNumRef<'b>> for &'a BigNum { + impl<'a, 'b> $t<&'b BigNumRef> for &'a BigNum { type Output = BigNum; fn $m(self, oth: &BigNumRef) -> BigNum { @@ -749,7 +753,7 @@ macro_rules! delegate { } } -impl<'a, 'b> Add<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { +impl<'a, 'b> Add<&'b BigNumRef> for &'a BigNumRef { type Output = BigNum; fn add(self, oth: &BigNumRef) -> BigNum { @@ -761,7 +765,7 @@ impl<'a, 'b> Add<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { delegate!(Add, add); -impl<'a, 'b> Sub<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { +impl<'a, 'b> Sub<&'b BigNumRef> for &'a BigNumRef { type Output = BigNum; fn sub(self, oth: &BigNumRef) -> BigNum { @@ -773,7 +777,7 @@ impl<'a, 'b> Sub<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { delegate!(Sub, sub); -impl<'a, 'b> Mul<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { +impl<'a, 'b> Mul<&'b BigNumRef> for &'a BigNumRef { type Output = BigNum; fn mul(self, oth: &BigNumRef) -> BigNum { @@ -786,10 +790,10 @@ impl<'a, 'b> Mul<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { delegate!(Mul, mul); -impl<'a, 'b> Div<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { +impl<'a, 'b> Div<&'b BigNumRef> for &'a BigNumRef { type Output = BigNum; - fn div(self, oth: &'b BigNumRef<'b>) -> BigNum { + fn div(self, oth: &'b BigNumRef) -> BigNum { let mut ctx = BnCtx::new().unwrap(); let mut dv = BigNum::new().unwrap(); ctx.div(Some(&mut dv), None, self, oth).unwrap(); @@ -799,10 +803,10 @@ impl<'a, 'b> Div<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { delegate!(Div, div); -impl<'a, 'b> Rem<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { +impl<'a, 'b> Rem<&'b BigNumRef> for &'a BigNumRef { type Output = BigNum; - fn rem(self, oth: &'b BigNumRef<'b>) -> BigNum { + fn rem(self, oth: &'b BigNumRef) -> BigNum { let mut ctx = BnCtx::new().unwrap(); let mut rem = BigNum::new().unwrap(); ctx.div(None, Some(&mut rem), self, oth).unwrap(); @@ -812,7 +816,7 @@ impl<'a, 'b> Rem<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { delegate!(Rem, rem); -impl<'a> Shl for &'a BigNumRef<'a> { +impl<'a> Shl for &'a BigNumRef { type Output = BigNum; fn shl(self, n: i32) -> BigNum { @@ -830,7 +834,7 @@ impl<'a> Shl for &'a BigNum { } } -impl<'a> Shr for &'a BigNumRef<'a> { +impl<'a> Shr for &'a BigNumRef { type Output = BigNum; fn shr(self, n: i32) -> BigNum { @@ -848,7 +852,7 @@ impl<'a> Shr for &'a BigNum { } } -impl<'a> Neg for &'a BigNumRef<'a> { +impl<'a> Neg for &'a BigNumRef { type Output = BigNum; fn neg(self) -> BigNum { diff --git a/openssl/src/crypto/dsa.rs b/openssl/src/crypto/dsa.rs index f9044661..f5b0f4e4 100644 --- a/openssl/src/crypto/dsa.rs +++ b/openssl/src/crypto/dsa.rs @@ -155,7 +155,7 @@ impl DSA { self.0 } - pub fn p<'a>(&'a self) -> Option> { + pub fn p(&self) -> Option<&BigNumRef> { unsafe { let p = compat::pqg(self.0)[0]; if p.is_null() { @@ -166,7 +166,7 @@ impl DSA { } } - pub fn q<'a>(&'a self) -> Option> { + pub fn q(&self) -> Option<&BigNumRef> { unsafe { let q = compat::pqg(self.0)[1]; if q.is_null() { @@ -177,7 +177,7 @@ impl DSA { } } - pub fn g<'a>(&'a self) -> Option> { + pub fn g(&self) -> Option<&BigNumRef> { unsafe { let g = compat::pqg(self.0)[2]; if g.is_null() { diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index a6a4f2b7..1b9e0e76 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -267,7 +267,7 @@ impl RSA { self.0 } - pub fn n<'a>(&'a self) -> Option> { + pub fn n(&self) -> Option<&BigNumRef> { unsafe { let n = compat::key(self.0)[0]; if n.is_null() { @@ -278,7 +278,7 @@ impl RSA { } } - pub fn d<'a>(&self) -> Option> { + pub fn d(&self) -> Option<&BigNumRef> { unsafe { let d = compat::key(self.0)[2]; if d.is_null() { @@ -289,7 +289,7 @@ impl RSA { } } - pub fn e<'a>(&'a self) -> Option> { + pub fn e(&self) -> Option<&BigNumRef> { unsafe { let e = compat::key(self.0)[1]; if e.is_null() { @@ -300,7 +300,7 @@ impl RSA { } } - pub fn p<'a>(&'a self) -> Option> { + pub fn p(&self) -> Option<&BigNumRef> { unsafe { let p = compat::factors(self.0)[0]; if p.is_null() { @@ -311,7 +311,7 @@ impl RSA { } } - pub fn q<'a>(&'a self) -> Option> { + pub fn q(&self) -> Option<&BigNumRef> { unsafe { let q = compat::factors(self.0)[1]; if q.is_null() { diff --git a/openssl/src/x509/verify.rs b/openssl/src/x509/verify.rs index 11c65dca..77095edc 100644 --- a/openssl/src/x509/verify.rs +++ b/openssl/src/x509/verify.rs @@ -2,7 +2,6 @@ //! //! Requires the `v102` or `v110` features and OpenSSL 1.0.2 or 1.1.0. -use std::marker::PhantomData; use libc::c_uint; use ffi; From 8ec53eb0e1b29d2b5c7e3afc433a26cede6dc84d Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 21 Oct 2016 20:59:07 -0700 Subject: [PATCH 074/186] Fix X509StoreContext --- openssl/src/ssl/mod.rs | 18 +++++++++--------- openssl/src/ssl/tests/mod.rs | 6 +++--- openssl/src/x509/mod.rs | 23 ++++++++++++----------- 3 files changed, 24 insertions(+), 23 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 26cafa9a..7f990a66 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -21,7 +21,7 @@ use ffi; use {init, cvt, cvt_p}; use dh::DH; -use x509::{X509StoreContext, X509FileType, X509, X509Ref, X509VerifyError}; +use x509::{X509StoreContextRef, X509FileType, X509, X509Ref, X509VerifyError}; #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] use x509::verify::X509VerifyParamRef; use crypto::pkey::PKey; @@ -173,7 +173,7 @@ fn get_new_ssl_idx() -> c_int { } extern fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int - where F: Fn(bool, &X509StoreContext) -> bool + Any + 'static + Sync + Send + where F: Fn(bool, &X509StoreContextRef) -> bool + Any + 'static + Sync + Send { unsafe { let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx(); @@ -182,14 +182,14 @@ extern fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) let verify = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_verify_data_idx::()); let verify: &F = &*(verify as *mut F); - let ctx = X509StoreContext::new(x509_ctx); + let ctx = X509StoreContextRef::from_ptr(x509_ctx); - verify(preverify_ok != 0, &ctx) as c_int + verify(preverify_ok != 0, ctx) as c_int } } extern fn ssl_raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int - where F: Fn(bool, &X509StoreContext) -> bool + Any + 'static + Sync + Send + where F: Fn(bool, &X509StoreContextRef) -> bool + Any + 'static + Sync + Send { unsafe { let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx(); @@ -198,9 +198,9 @@ extern fn ssl_raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_ get_ssl_verify_data_idx::()); let verify: &F = &*(verify as *mut F); - let ctx = X509StoreContext::new(x509_ctx); + let ctx = X509StoreContextRef::from_ptr(x509_ctx); - verify(preverify_ok != 0, &ctx) as c_int + verify(preverify_ok != 0, ctx) as c_int } } @@ -361,7 +361,7 @@ impl SslContextRef { /// Configures the certificate verification method for new connections and /// registers a verification callback. pub fn set_verify_callback(&mut self, mode: SslVerifyMode, verify: F) - where F: Fn(bool, &X509StoreContext) -> bool + Any + 'static + Sync + Send + where F: Fn(bool, &X509StoreContextRef) -> bool + Any + 'static + Sync + Send { unsafe { let verify = Box::new(verify); @@ -830,7 +830,7 @@ impl SslRef { /// to the certificate chain. It should return `true` if the certificate /// chain is valid and `false` otherwise. pub fn set_verify_callback(&mut self, mode: SslVerifyMode, verify: F) - where F: Fn(bool, &X509StoreContext) -> bool + Any + 'static + Sync + Send + where F: Fn(bool, &X509StoreContextRef) -> bool + Any + 'static + Sync + Send { unsafe { let verify = Box::new(verify); diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 684f77ac..fada2a8e 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -20,7 +20,7 @@ use ssl::SSL_VERIFY_PEER; use ssl::{SslMethod, HandshakeError}; use ssl::error::Error; use ssl::{SslContext, SslStream, Ssl}; -use x509::X509StoreContext; +use x509::X509StoreContextRef; use x509::X509FileType; use x509::X509; #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] @@ -168,7 +168,7 @@ macro_rules! run_test( use ssl::{SslContext, Ssl, SslStream}; use ssl::SSL_VERIFY_PEER; use crypto::hash::MessageDigest; - use x509::X509StoreContext; + use x509::X509StoreContextRef; use serialize::hex::FromHex; use super::Server; @@ -778,7 +778,7 @@ mod dtlsv1 { use ssl::SslMethod; use ssl::{SslContext, SslStream}; use ssl::SSL_VERIFY_PEER; - use x509::X509StoreContext; + use x509::X509StoreContextRef; #[test] fn test_new_ctx() { diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 9c91bfc1..db5ef1df 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -91,25 +91,26 @@ pub enum X509FileType { Default = ffi::X509_FILETYPE_DEFAULT, } -#[allow(missing_copy_implementations)] -pub struct X509StoreContext { - ctx: *mut ffi::X509_STORE_CTX, -} +pub struct X509StoreContextRef(Opaque); -impl X509StoreContext { - pub fn new(ctx: *mut ffi::X509_STORE_CTX) -> X509StoreContext { - X509StoreContext { ctx: ctx } +impl X509StoreContextRef { + pub unsafe fn from_ptr<'a>(ctx: *mut ffi::X509_STORE_CTX) -> &'a X509StoreContextRef { + &*(ctx as *mut _) + } + + pub fn as_ptr(&self) -> *mut ffi::X509_STORE_CTX { + self as *const _ as *mut _ } pub fn error(&self) -> Option { unsafe { - X509VerifyError::from_raw(ffi::X509_STORE_CTX_get_error(self.ctx) as c_long) + X509VerifyError::from_raw(ffi::X509_STORE_CTX_get_error(self.as_ptr()) as c_long) } } - pub fn current_cert<'a>(&'a self) -> Option<&'a X509Ref> { + pub fn current_cert(&self) -> Option<&X509Ref> { unsafe { - let ptr = ffi::X509_STORE_CTX_get_current_cert(self.ctx); + let ptr = ffi::X509_STORE_CTX_get_current_cert(self.as_ptr()); if ptr.is_null() { None } else { @@ -119,7 +120,7 @@ impl X509StoreContext { } pub fn error_depth(&self) -> u32 { - unsafe { ffi::X509_STORE_CTX_get_error_depth(self.ctx) as u32 } + unsafe { ffi::X509_STORE_CTX_get_error_depth(self.as_ptr()) as u32 } } } From f1c68e354429da9f0ef56972713b110c35850516 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 21 Oct 2016 21:22:05 -0700 Subject: [PATCH 075/186] Rename SslContextOptions --- openssl/src/ssl/mod.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 7f990a66..c703d5fc 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -39,7 +39,7 @@ use self::bio::BioMethod; pub use ssl::error::Error; bitflags! { - pub flags SslContextOptions: c_ulong { + pub flags SslOptions: c_ulong { const SSL_OP_MICROSOFT_SESS_ID_BUG = ffi::SSL_OP_MICROSOFT_SESS_ID_BUG, const SSL_OP_NETSCAPE_CHALLENGE_BUG = ffi::SSL_OP_NETSCAPE_CHALLENGE_BUG, const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = @@ -548,19 +548,19 @@ impl SslContextRef { } } - pub fn set_options(&mut self, option: SslContextOptions) -> SslContextOptions { + pub fn set_options(&mut self, option: SslOptions) -> SslOptions { let ret = unsafe { compat::SSL_CTX_set_options(self.as_ptr(), option.bits()) }; - SslContextOptions::from_bits(ret).unwrap() + SslOptions::from_bits(ret).unwrap() } - pub fn options(&self) -> SslContextOptions { + pub fn options(&self) -> SslOptions { let ret = unsafe { compat::SSL_CTX_get_options(self.as_ptr()) }; - SslContextOptions::from_bits(ret).unwrap() + SslOptions::from_bits(ret).unwrap() } - pub fn clear_options(&mut self, option: SslContextOptions) -> SslContextOptions { + pub fn clear_options(&mut self, option: SslOptions) -> SslOptions { let ret = unsafe { compat::SSL_CTX_clear_options(self.as_ptr(), option.bits()) }; - SslContextOptions::from_bits(ret).unwrap() + SslOptions::from_bits(ret).unwrap() } /// Set the protocols to be used during Next Protocol Negotiation (the protocols From 9be0aab9acaa98c2419832ac396063bdfb9995fd Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 21 Oct 2016 21:46:32 -0700 Subject: [PATCH 076/186] Borrow compression string --- openssl/src/ssl/mod.rs | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index c703d5fc..963f252c 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -955,27 +955,24 @@ impl SslRef { /// /// The result will be either None, indicating no compression is in use, or /// a string with the compression name. - pub fn compression(&self) -> Option { + pub fn compression(&self) -> Option<&str> { self._compression() } #[cfg(not(osslconf = "OPENSSL_NO_COMP"))] - fn _compression(&self) -> Option { - let ptr = unsafe { ffi::SSL_get_current_compression(self.as_ptr()) }; - if ptr == ptr::null() { - return None; + fn _compression(&self) -> Option<&str> { + unsafe { + let ptr = ffi::SSL_get_current_compression(self.as_ptr()); + if ptr == ptr::null() { + return None; + } + let meth = ffi::SSL_COMP_get_name(ptr); + Some(str::from_utf8(CStr::from_ptr(meth as *const _).to_bytes()).unwrap()) } - - let meth = unsafe { ffi::SSL_COMP_get_name(ptr) }; - let s = unsafe { - String::from_utf8(CStr::from_ptr(meth as *const _).to_bytes().to_vec()).unwrap() - }; - - Some(s) } #[cfg(osslconf = "OPENSSL_NO_COMP")] - fn _compression(&self) -> Option { + fn _compression(&self) -> Option<&str> { None } From 58f6d1138afc6381694c9080c398eb851b455ecd Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 21 Oct 2016 21:52:02 -0700 Subject: [PATCH 077/186] Properly propagate panics --- openssl/src/crypto/util.rs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/openssl/src/crypto/util.rs b/openssl/src/crypto/util.rs index 07099b7c..68d9b32a 100644 --- a/openssl/src/crypto/util.rs +++ b/openssl/src/crypto/util.rs @@ -1,7 +1,7 @@ use libc::{c_int, c_char, c_void}; use std::any::Any; -use std::panic; +use std::panic::{self, AssertUnwindSafe}; use std::slice; /// Wraps a user-supplied callback and a slot for panics thrown inside the callback (while FFI @@ -42,17 +42,20 @@ pub unsafe extern fn invoke_passwd_cb(buf: *mut c_char, cb_state: *mut c_void) -> c_int where F: FnOnce(&mut [c_char]) -> usize { - let result = panic::catch_unwind(|| { + let callback = &mut *(cb_state as *mut CallbackState); + + let result = panic::catch_unwind(AssertUnwindSafe(|| { // build a `i8` slice to pass to the user callback let pass_slice = slice::from_raw_parts_mut(buf, size as usize); - let callback = &mut *(cb_state as *mut CallbackState); callback.cb.take().unwrap()(pass_slice) - }); + })); - if let Ok(len) = result { - return len as c_int; - } else { - return 0; + match result { + Ok(len) => len as c_int, + Err(err) => { + callback.panic = Some(err); + 0 + } } } From 98b7f2f9352e4d92b44245d0737f9a45adb4ae2b Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 22 Oct 2016 09:16:38 -0700 Subject: [PATCH 078/186] Flatten crypto module --- openssl/src/crypto/mod.rs | 28 ---------------------------- openssl/src/{crypto => }/dsa.rs | 4 ++-- openssl/src/{crypto => }/hash.rs | 0 openssl/src/lib.rs | 16 +++++++++++++--- openssl/src/{crypto => }/memcmp.rs | 0 openssl/src/{crypto => }/pkcs12.rs | 6 +++--- openssl/src/{crypto => }/pkcs5.rs | 8 ++++---- openssl/src/{crypto => }/pkey.rs | 12 ++++++------ openssl/src/{crypto => }/rand.rs | 0 openssl/src/{crypto => }/rsa.rs | 8 ++++---- openssl/src/{crypto => }/sign.rs | 28 ++++++++++++++-------------- openssl/src/ssl/mod.rs | 2 +- openssl/src/ssl/tests/mod.rs | 8 ++++---- openssl/src/{crypto => }/symm.rs | 0 openssl/src/{crypto => }/util.rs | 0 openssl/src/x509/mod.rs | 6 +++--- openssl/src/x509/tests.rs | 6 +++--- 17 files changed, 57 insertions(+), 75 deletions(-) delete mode 100644 openssl/src/crypto/mod.rs rename openssl/src/{crypto => }/dsa.rs (98%) rename openssl/src/{crypto => }/hash.rs (100%) rename openssl/src/{crypto => }/memcmp.rs (100%) rename openssl/src/{crypto => }/pkcs12.rs (96%) rename openssl/src/{crypto => }/pkcs5.rs (98%) rename openssl/src/{crypto => }/pkey.rs (96%) rename openssl/src/{crypto => }/rand.rs (100%) rename openssl/src/{crypto => }/rsa.rs (98%) rename openssl/src/{crypto => }/sign.rs (95%) rename openssl/src/{crypto => }/symm.rs (100%) rename openssl/src/{crypto => }/util.rs (100%) diff --git a/openssl/src/crypto/mod.rs b/openssl/src/crypto/mod.rs deleted file mode 100644 index 0db23bcc..00000000 --- a/openssl/src/crypto/mod.rs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2011 Google Inc. -// 2013 Jack Lloyd -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -mod util; -pub mod dsa; -pub mod hash; -pub mod memcmp; -pub mod pkcs12; -pub mod pkcs5; -pub mod pkey; -pub mod rand; -pub mod rsa; -pub mod sign; -pub mod symm; - diff --git a/openssl/src/crypto/dsa.rs b/openssl/src/dsa.rs similarity index 98% rename from openssl/src/crypto/dsa.rs rename to openssl/src/dsa.rs index f5b0f4e4..fc005574 100644 --- a/openssl/src/crypto/dsa.rs +++ b/openssl/src/dsa.rs @@ -7,7 +7,7 @@ use libc::{c_int, c_char, c_void}; use {cvt, cvt_p}; use bn::BigNumRef; use bio::{MemBio, MemBioSlice}; -use crypto::util::{CallbackState, invoke_passwd_cb}; +use util::{CallbackState, invoke_passwd_cb}; /// Builder for upfront DSA parameter generation pub struct DSAParams(*mut ffi::DSA); @@ -248,7 +248,7 @@ mod test { #[test] pub fn test_password() { let mut password_queried = false; - let key = include_bytes!("../../test/dsa-encrypted.pem"); + let key = include_bytes!("../test/dsa-encrypted.pem"); DSA::private_key_from_pem_cb(key, |password| { password_queried = true; password[0] = b'm' as c_char; diff --git a/openssl/src/crypto/hash.rs b/openssl/src/hash.rs similarity index 100% rename from openssl/src/crypto/hash.rs rename to openssl/src/hash.rs diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index 10f450dd..9ed02207 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -22,17 +22,27 @@ use error::ErrorStack; mod macros; -pub mod asn1; mod bio; +mod opaque; +mod util; +pub mod asn1; pub mod bn; -pub mod crypto; pub mod dh; +pub mod dsa; pub mod error; +pub mod hash; +pub mod memcmp; pub mod nid; +pub mod pkcs12; +pub mod pkcs5; +pub mod pkey; +pub mod rand; +pub mod rsa; +pub mod sign; pub mod ssl; +pub mod symm; pub mod version; pub mod x509; -mod opaque; pub fn cvt_p(r: *mut T) -> Result<*mut T, ErrorStack> { if r.is_null() { diff --git a/openssl/src/crypto/memcmp.rs b/openssl/src/memcmp.rs similarity index 100% rename from openssl/src/crypto/memcmp.rs rename to openssl/src/memcmp.rs diff --git a/openssl/src/crypto/pkcs12.rs b/openssl/src/pkcs12.rs similarity index 96% rename from openssl/src/crypto/pkcs12.rs rename to openssl/src/pkcs12.rs index 846b7baf..f143ec49 100644 --- a/openssl/src/crypto/pkcs12.rs +++ b/openssl/src/pkcs12.rs @@ -7,7 +7,7 @@ use std::ptr; use std::ffi::CString; use {cvt, cvt_p}; -use crypto::pkey::PKey; +use pkey::PKey; use error::ErrorStack; use x509::X509; @@ -98,14 +98,14 @@ mod compat { #[cfg(test)] mod test { - use crypto::hash::MessageDigest; + use hash::MessageDigest; use serialize::hex::ToHex; use super::*; #[test] fn parse() { - let der = include_bytes!("../../test/identity.p12"); + let der = include_bytes!("../test/identity.p12"); let pkcs12 = Pkcs12::from_der(der).unwrap(); let parsed = pkcs12.parse("mypass").unwrap(); diff --git a/openssl/src/crypto/pkcs5.rs b/openssl/src/pkcs5.rs similarity index 98% rename from openssl/src/crypto/pkcs5.rs rename to openssl/src/pkcs5.rs index 8bcb9b31..b0c899e5 100644 --- a/openssl/src/crypto/pkcs5.rs +++ b/openssl/src/pkcs5.rs @@ -3,8 +3,8 @@ use std::ptr; use ffi; use cvt; -use crypto::hash::MessageDigest; -use crypto::symm::Cipher; +use hash::MessageDigest; +use symm::Cipher; use error::ErrorStack; #[derive(Clone, Eq, PartialEq, Hash, Debug)] @@ -98,8 +98,8 @@ pub fn pbkdf2_hmac(pass: &[u8], #[cfg(test)] mod tests { - use crypto::hash::MessageDigest; - use crypto::symm::Cipher; + use hash::MessageDigest; + use symm::Cipher; // Test vectors from // https://git.lysator.liu.se/nettle/nettle/blob/nettle_3.1.1_release_20150424/testsuite/pbkdf2-test.c diff --git a/openssl/src/crypto/pkey.rs b/openssl/src/pkey.rs similarity index 96% rename from openssl/src/crypto/pkey.rs rename to openssl/src/pkey.rs index 1d062cfa..d91acb36 100644 --- a/openssl/src/crypto/pkey.rs +++ b/openssl/src/pkey.rs @@ -5,10 +5,10 @@ use ffi; use {cvt, cvt_p}; use bio::{MemBio, MemBioSlice}; -use crypto::dsa::DSA; -use crypto::rsa::RSA; +use dsa::DSA; +use rsa::RSA; use error::ErrorStack; -use crypto::util::{CallbackState, invoke_passwd_cb}; +use util::{CallbackState, invoke_passwd_cb}; pub struct PKey(*mut ffi::EVP_PKEY); @@ -167,19 +167,19 @@ impl Drop for PKey { mod tests { #[test] fn test_private_key_from_pem() { - let key = include_bytes!("../../test/key.pem"); + let key = include_bytes!("../test/key.pem"); super::PKey::private_key_from_pem(key).unwrap(); } #[test] fn test_public_key_from_pem() { - let key = include_bytes!("../../test/key.pem.pub"); + let key = include_bytes!("../test/key.pem.pub"); super::PKey::public_key_from_pem(key).unwrap(); } #[test] fn test_pem() { - let key = include_bytes!("../../test/key.pem"); + let key = include_bytes!("../test/key.pem"); let key = super::PKey::private_key_from_pem(key).unwrap(); let priv_key = key.private_key_to_pem().unwrap(); diff --git a/openssl/src/crypto/rand.rs b/openssl/src/rand.rs similarity index 100% rename from openssl/src/crypto/rand.rs rename to openssl/src/rand.rs diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/rsa.rs similarity index 98% rename from openssl/src/crypto/rsa.rs rename to openssl/src/rsa.rs index 1b9e0e76..b8702f97 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/rsa.rs @@ -8,7 +8,7 @@ use {cvt, cvt_p, cvt_n}; use bn::{BigNum, BigNumRef}; use bio::{MemBio, MemBioSlice}; use error::ErrorStack; -use crypto::util::{CallbackState, invoke_passwd_cb}; +use util::{CallbackState, invoke_passwd_cb}; /// Type of encryption padding to use. #[derive(Copy, Clone)] @@ -421,7 +421,7 @@ mod test { #[test] pub fn test_password() { let mut password_queried = false; - let key = include_bytes!("../../test/rsa-encrypted.pem"); + let key = include_bytes!("../test/rsa-encrypted.pem"); RSA::private_key_from_pem_cb(key, |password| { password_queried = true; password[0] = b'm' as c_char; @@ -438,7 +438,7 @@ mod test { #[test] pub fn test_public_encrypt_private_decrypt_with_padding() { - let key = include_bytes!("../../test/rsa.pem.pub"); + let key = include_bytes!("../test/rsa.pem.pub"); let public_key = RSA::public_key_from_pem(key).unwrap(); let mut result = vec![0; public_key.size()]; @@ -446,7 +446,7 @@ mod test { let len = public_key.public_encrypt(original_data, &mut result, Padding::pkcs1()).unwrap(); assert_eq!(len, 256); - let pkey = include_bytes!("../../test/rsa.pem"); + let pkey = include_bytes!("../test/rsa.pem"); let private_key = RSA::private_key_from_pem(pkey).unwrap(); let mut dec_result = vec![0; private_key.size()]; let len = private_key.private_decrypt(&result, &mut dec_result, Padding::pkcs1()).unwrap(); diff --git a/openssl/src/crypto/sign.rs b/openssl/src/sign.rs similarity index 95% rename from openssl/src/crypto/sign.rs rename to openssl/src/sign.rs index 41009149..8fb27427 100644 --- a/openssl/src/crypto/sign.rs +++ b/openssl/src/sign.rs @@ -60,8 +60,8 @@ use std::marker::PhantomData; use std::ptr; use {cvt, cvt_p}; -use crypto::hash::MessageDigest; -use crypto::pkey::PKey; +use hash::MessageDigest; +use pkey::PKey; use error::ErrorStack; #[cfg(ossl110)] @@ -208,11 +208,11 @@ mod test { use serialize::hex::FromHex; use std::iter; - use crypto::hash::MessageDigest; - use crypto::sign::{Signer, Verifier}; - use crypto::rsa::RSA; - use crypto::dsa::DSA; - use crypto::pkey::PKey; + use hash::MessageDigest; + use sign::{Signer, Verifier}; + use rsa::RSA; + use dsa::DSA; + use pkey::PKey; static INPUT: &'static [u8] = &[101, 121, 74, 104, 98, 71, 99, 105, 79, 105, 74, 83, 85, 122, 73, 49, 78, 105, 74, 57, @@ -240,7 +240,7 @@ mod test { #[test] fn rsa_sign() { - let key = include_bytes!("../../test/rsa.pem"); + let key = include_bytes!("../test/rsa.pem"); let private_key = RSA::private_key_from_pem(key).unwrap(); let pkey = PKey::from_rsa(private_key).unwrap(); @@ -253,7 +253,7 @@ mod test { #[test] fn rsa_verify_ok() { - let key = include_bytes!("../../test/rsa.pem"); + let key = include_bytes!("../test/rsa.pem"); let private_key = RSA::private_key_from_pem(key).unwrap(); let pkey = PKey::from_rsa(private_key).unwrap(); @@ -264,7 +264,7 @@ mod test { #[test] fn rsa_verify_invalid() { - let key = include_bytes!("../../test/rsa.pem"); + let key = include_bytes!("../test/rsa.pem"); let private_key = RSA::private_key_from_pem(key).unwrap(); let pkey = PKey::from_rsa(private_key).unwrap(); @@ -279,12 +279,12 @@ mod test { let input: Vec = (0..25).cycle().take(1024).collect(); let private_key = { - let key = include_bytes!("../../test/dsa.pem"); + let key = include_bytes!("../test/dsa.pem"); PKey::from_dsa(DSA::private_key_from_pem(key).unwrap()).unwrap() }; let public_key = { - let key = include_bytes!("../../test/dsa.pem.pub"); + let key = include_bytes!("../test/dsa.pem.pub"); PKey::from_dsa(DSA::public_key_from_pem(key).unwrap()).unwrap() }; @@ -302,12 +302,12 @@ mod test { let input: Vec = (0..25).cycle().take(1024).collect(); let private_key = { - let key = include_bytes!("../../test/dsa.pem"); + let key = include_bytes!("../test/dsa.pem"); PKey::from_dsa(DSA::private_key_from_pem(key).unwrap()).unwrap() }; let public_key = { - let key = include_bytes!("../../test/dsa.pem.pub"); + let key = include_bytes!("../test/dsa.pem.pub"); PKey::from_dsa(DSA::public_key_from_pem(key).unwrap()).unwrap() }; diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 963f252c..6e5a2c09 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -24,7 +24,7 @@ use dh::DH; use x509::{X509StoreContextRef, X509FileType, X509, X509Ref, X509VerifyError}; #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] use x509::verify::X509VerifyParamRef; -use crypto::pkey::PKey; +use pkey::PKey; use error::ErrorStack; use opaque::Opaque; diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index fada2a8e..45c5b215 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -14,7 +14,7 @@ use std::time::Duration; use tempdir::TempDir; -use crypto::hash::MessageDigest; +use hash::MessageDigest; use ssl; use ssl::SSL_VERIFY_PEER; use ssl::{SslMethod, HandshakeError}; @@ -25,7 +25,7 @@ use x509::X509FileType; use x509::X509; #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] use x509::verify::X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS; -use crypto::pkey::PKey; +use pkey::PKey; use std::net::UdpSocket; @@ -167,7 +167,7 @@ macro_rules! run_test( use ssl::SslMethod; use ssl::{SslContext, Ssl, SslStream}; use ssl::SSL_VERIFY_PEER; - use crypto::hash::MessageDigest; + use hash::MessageDigest; use x509::X509StoreContextRef; use serialize::hex::FromHex; use super::Server; @@ -774,7 +774,7 @@ mod dtlsv1 { use std::net::TcpStream; use std::thread; - use crypto::hash::MessageDigest; + use hash::MessageDigest; use ssl::SslMethod; use ssl::{SslContext, SslStream}; use ssl::SSL_VERIFY_PEER; diff --git a/openssl/src/crypto/symm.rs b/openssl/src/symm.rs similarity index 100% rename from openssl/src/crypto/symm.rs rename to openssl/src/symm.rs diff --git a/openssl/src/crypto/util.rs b/openssl/src/util.rs similarity index 100% rename from openssl/src/crypto/util.rs rename to openssl/src/util.rs diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index db5ef1df..dfd61cac 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -15,9 +15,9 @@ use {cvt, cvt_p}; use asn1::Asn1Time; use asn1::Asn1TimeRef; use bio::{MemBio, MemBioSlice}; -use crypto::hash::MessageDigest; -use crypto::pkey::PKey; -use crypto::rand::rand_bytes; +use hash::MessageDigest; +use pkey::PKey; +use rand::rand_bytes; use error::ErrorStack; use ffi; use nid::Nid; diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index afb06408..a5eb04e7 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -1,8 +1,8 @@ use serialize::hex::FromHex; -use crypto::hash::MessageDigest; -use crypto::pkey::PKey; -use crypto::rsa::RSA; +use hash::MessageDigest; +use pkey::PKey; +use rsa::RSA; use x509::{X509, X509Generator}; use x509::extension::Extension::{KeyUsage, ExtKeyUsage, SubjectAltName, OtherNid, OtherStr}; use x509::extension::AltNameOption as SAN; From ae72cbd28b16823a44588b13efd79be31ffd3b7e Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 22 Oct 2016 09:17:41 -0700 Subject: [PATCH 079/186] Fix hasher docs --- openssl/src/hash.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openssl/src/hash.rs b/openssl/src/hash.rs index ec265631..9112ed24 100644 --- a/openssl/src/hash.rs +++ b/openssl/src/hash.rs @@ -103,7 +103,7 @@ use self::State::*; /// /// Don't actually use MD5 and SHA-1 hashes, they're not secure anymore. /// -/// Don't ever hash passwords, use `crypto::pkcs5` or bcrypt/scrypt instead. +/// Don't ever hash passwords, use the functions in the `pkcs5` module or bcrypt/scrypt instead. pub struct Hasher { ctx: *mut ffi::EVP_MD_CTX, md: *const ffi::EVP_MD, From 2fd201d9c3df7fd76c0194fc10fa09cf5f0eb841 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 22 Oct 2016 10:08:21 -0700 Subject: [PATCH 080/186] De-enumify Nid --- openssl-sys/src/lib.rs | 952 +++++++- openssl/src/nid.rs | 4012 +++++++++++++++++++++++++++++++-- openssl/src/x509/extension.rs | 8 +- openssl/src/x509/mod.rs | 6 +- openssl/src/x509/tests.rs | 20 +- 5 files changed, 4784 insertions(+), 214 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 4c8d63ca..dfe2fae0 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -118,11 +118,957 @@ pub const MBSTRING_FLAG: c_int = 0x1000; pub const MBSTRING_UNIV: c_int = MBSTRING_FLAG | 4; pub const MBSTRING_UTF8: c_int = MBSTRING_FLAG; +pub const NID_undef: c_int = 0; +pub const NID_itu_t: c_int = 645; +pub const NID_ccitt: c_int = 404; +pub const NID_iso: c_int = 181; +pub const NID_joint_iso_itu_t: c_int = 646; +pub const NID_joint_iso_ccitt: c_int = 393; +pub const NID_member_body: c_int = 182; +pub const NID_identified_organization: c_int = 676; +pub const NID_hmac_md5: c_int = 780; +pub const NID_hmac_sha1: c_int = 781; +pub const NID_certicom_arc: c_int = 677; +pub const NID_international_organizations: c_int = 647; +pub const NID_wap: c_int = 678; +pub const NID_wap_wsg: c_int = 679; +pub const NID_selected_attribute_types: c_int = 394; +pub const NID_clearance: c_int = 395; +pub const NID_ISO_US: c_int = 183; +pub const NID_X9_57: c_int = 184; +pub const NID_X9cm: c_int = 185; +pub const NID_dsa: c_int = 116; +pub const NID_dsaWithSHA1: c_int = 113; +pub const NID_ansi_X9_62: c_int = 405; +pub const NID_X9_62_prime_field: c_int = 406; +pub const NID_X9_62_characteristic_two_field: c_int = 407; +pub const NID_X9_62_id_characteristic_two_basis: c_int = 680; +pub const NID_X9_62_onBasis: c_int = 681; +pub const NID_X9_62_tpBasis: c_int = 682; +pub const NID_X9_62_ppBasis: c_int = 683; +pub const NID_X9_62_id_ecPublicKey: c_int = 408; +pub const NID_X9_62_c2pnb163v1: c_int = 684; +pub const NID_X9_62_c2pnb163v2: c_int = 685; +pub const NID_X9_62_c2pnb163v3: c_int = 686; +pub const NID_X9_62_c2pnb176v1: c_int = 687; +pub const NID_X9_62_c2tnb191v1: c_int = 688; +pub const NID_X9_62_c2tnb191v2: c_int = 689; +pub const NID_X9_62_c2tnb191v3: c_int = 690; +pub const NID_X9_62_c2onb191v4: c_int = 691; +pub const NID_X9_62_c2onb191v5: c_int = 692; +pub const NID_X9_62_c2pnb208w1: c_int = 693; +pub const NID_X9_62_c2tnb239v1: c_int = 694; +pub const NID_X9_62_c2tnb239v2: c_int = 695; +pub const NID_X9_62_c2tnb239v3: c_int = 696; +pub const NID_X9_62_c2onb239v4: c_int = 697; +pub const NID_X9_62_c2onb239v5: c_int = 698; +pub const NID_X9_62_c2pnb272w1: c_int = 699; +pub const NID_X9_62_c2pnb304w1: c_int = 700; +pub const NID_X9_62_c2tnb359v1: c_int = 701; +pub const NID_X9_62_c2pnb368w1: c_int = 702; +pub const NID_X9_62_c2tnb431r1: c_int = 703; +pub const NID_X9_62_prime192v1: c_int = 409; +pub const NID_X9_62_prime192v2: c_int = 410; +pub const NID_X9_62_prime192v3: c_int = 411; +pub const NID_X9_62_prime239v1: c_int = 412; +pub const NID_X9_62_prime239v2: c_int = 413; +pub const NID_X9_62_prime239v3: c_int = 414; +pub const NID_X9_62_prime256v1: c_int = 415; +pub const NID_ecdsa_with_SHA1: c_int = 416; +pub const NID_ecdsa_with_Recommended: c_int = 791; +pub const NID_ecdsa_with_Specified: c_int = 792; +pub const NID_ecdsa_with_SHA224: c_int = 793; +pub const NID_ecdsa_with_SHA256: c_int = 794; +pub const NID_ecdsa_with_SHA384: c_int = 795; +pub const NID_ecdsa_with_SHA512: c_int = 796; +pub const NID_secp112r1: c_int = 704; +pub const NID_secp112r2: c_int = 705; +pub const NID_secp128r1: c_int = 706; +pub const NID_secp128r2: c_int = 707; +pub const NID_secp160k1: c_int = 708; +pub const NID_secp160r1: c_int = 709; +pub const NID_secp160r2: c_int = 710; +pub const NID_secp192k1: c_int = 711; +pub const NID_secp224k1: c_int = 712; +pub const NID_secp224r1: c_int = 713; +pub const NID_secp256k1: c_int = 714; +pub const NID_secp384r1: c_int = 715; +pub const NID_secp521r1: c_int = 716; +pub const NID_sect113r1: c_int = 717; +pub const NID_sect113r2: c_int = 718; +pub const NID_sect131r1: c_int = 719; +pub const NID_sect131r2: c_int = 720; +pub const NID_sect163k1: c_int = 721; +pub const NID_sect163r1: c_int = 722; +pub const NID_sect163r2: c_int = 723; +pub const NID_sect193r1: c_int = 724; +pub const NID_sect193r2: c_int = 725; +pub const NID_sect233k1: c_int = 726; +pub const NID_sect233r1: c_int = 727; +pub const NID_sect239k1: c_int = 728; +pub const NID_sect283k1: c_int = 729; +pub const NID_sect283r1: c_int = 730; +pub const NID_sect409k1: c_int = 731; +pub const NID_sect409r1: c_int = 732; +pub const NID_sect571k1: c_int = 733; +pub const NID_sect571r1: c_int = 734; +pub const NID_wap_wsg_idm_ecid_wtls1: c_int = 735; +pub const NID_wap_wsg_idm_ecid_wtls3: c_int = 736; +pub const NID_wap_wsg_idm_ecid_wtls4: c_int = 737; +pub const NID_wap_wsg_idm_ecid_wtls5: c_int = 738; +pub const NID_wap_wsg_idm_ecid_wtls6: c_int = 739; +pub const NID_wap_wsg_idm_ecid_wtls7: c_int = 740; +pub const NID_wap_wsg_idm_ecid_wtls8: c_int = 741; +pub const NID_wap_wsg_idm_ecid_wtls9: c_int = 742; +pub const NID_wap_wsg_idm_ecid_wtls10: c_int = 743; +pub const NID_wap_wsg_idm_ecid_wtls11: c_int = 744; +pub const NID_wap_wsg_idm_ecid_wtls12: c_int = 745; +pub const NID_cast5_cbc: c_int = 108; +pub const NID_cast5_ecb: c_int = 109; +pub const NID_cast5_cfb64: c_int = 110; +pub const NID_cast5_ofb64: c_int = 111; +pub const NID_pbeWithMD5AndCast5_CBC: c_int = 112; +pub const NID_id_PasswordBasedMAC: c_int = 782; +pub const NID_id_DHBasedMac: c_int = 783; +pub const NID_rsadsi: c_int = 1; +pub const NID_pkcs: c_int = 2; +pub const NID_pkcs1: c_int = 186; pub const NID_rsaEncryption: c_int = 6; +pub const NID_md2WithRSAEncryption: c_int = 7; +pub const NID_md4WithRSAEncryption: c_int = 396; +pub const NID_md5WithRSAEncryption: c_int = 8; +pub const NID_sha1WithRSAEncryption: c_int = 65; +pub const NID_rsaesOaep: c_int = 919; +pub const NID_mgf1: c_int = 911; +pub const NID_pSpecified: c_int = 935; +pub const NID_rsassaPss: c_int = 912; +pub const NID_sha256WithRSAEncryption: c_int = 668; +pub const NID_sha384WithRSAEncryption: c_int = 669; +pub const NID_sha512WithRSAEncryption: c_int = 670; +pub const NID_sha224WithRSAEncryption: c_int = 671; +pub const NID_pkcs3: c_int = 27; +pub const NID_dhKeyAgreement: c_int = 28; +pub const NID_pkcs5: c_int = 187; +pub const NID_pbeWithMD2AndDES_CBC: c_int = 9; +pub const NID_pbeWithMD5AndDES_CBC: c_int = 10; +pub const NID_pbeWithMD2AndRC2_CBC: c_int = 168; +pub const NID_pbeWithMD5AndRC2_CBC: c_int = 169; +pub const NID_pbeWithSHA1AndDES_CBC: c_int = 170; +pub const NID_pbeWithSHA1AndRC2_CBC: c_int = 68; +pub const NID_id_pbkdf2: c_int = 69; +pub const NID_pbes2: c_int = 161; +pub const NID_pbmac1: c_int = 162; +pub const NID_pkcs7: c_int = 20; +pub const NID_pkcs7_data: c_int = 21; +pub const NID_pkcs7_signed: c_int = 22; +pub const NID_pkcs7_enveloped: c_int = 23; +pub const NID_pkcs7_signedAndEnveloped: c_int = 24; +pub const NID_pkcs7_digest: c_int = 25; +pub const NID_pkcs7_encrypted: c_int = 26; +pub const NID_pkcs9: c_int = 47; +pub const NID_pkcs9_emailAddress: c_int = 48; +pub const NID_pkcs9_unstructuredName: c_int = 49; +pub const NID_pkcs9_contentType: c_int = 50; +pub const NID_pkcs9_messageDigest: c_int = 51; +pub const NID_pkcs9_signingTime: c_int = 52; +pub const NID_pkcs9_countersignature: c_int = 53; +pub const NID_pkcs9_challengePassword: c_int = 54; +pub const NID_pkcs9_unstructuredAddress: c_int = 55; +pub const NID_pkcs9_extCertAttributes: c_int = 56; +pub const NID_ext_req: c_int = 172; +pub const NID_SMIMECapabilities: c_int = 167; +pub const NID_SMIME: c_int = 188; +pub const NID_id_smime_mod: c_int = 189; +pub const NID_id_smime_ct: c_int = 190; +pub const NID_id_smime_aa: c_int = 191; +pub const NID_id_smime_alg: c_int = 192; +pub const NID_id_smime_cd: c_int = 193; +pub const NID_id_smime_spq: c_int = 194; +pub const NID_id_smime_cti: c_int = 195; +pub const NID_id_smime_mod_cms: c_int = 196; +pub const NID_id_smime_mod_ess: c_int = 197; +pub const NID_id_smime_mod_oid: c_int = 198; +pub const NID_id_smime_mod_msg_v3: c_int = 199; +pub const NID_id_smime_mod_ets_eSignature_88: c_int = 200; +pub const NID_id_smime_mod_ets_eSignature_97: c_int = 201; +pub const NID_id_smime_mod_ets_eSigPolicy_88: c_int = 202; +pub const NID_id_smime_mod_ets_eSigPolicy_97: c_int = 203; +pub const NID_id_smime_ct_receipt: c_int = 204; +pub const NID_id_smime_ct_authData: c_int = 205; +pub const NID_id_smime_ct_publishCert: c_int = 206; +pub const NID_id_smime_ct_TSTInfo: c_int = 207; +pub const NID_id_smime_ct_TDTInfo: c_int = 208; +pub const NID_id_smime_ct_contentInfo: c_int = 209; +pub const NID_id_smime_ct_DVCSRequestData: c_int = 210; +pub const NID_id_smime_ct_DVCSResponseData: c_int = 211; +pub const NID_id_smime_ct_compressedData: c_int = 786; +pub const NID_id_ct_asciiTextWithCRLF: c_int = 787; +pub const NID_id_smime_aa_receiptRequest: c_int = 212; +pub const NID_id_smime_aa_securityLabel: c_int = 213; +pub const NID_id_smime_aa_mlExpandHistory: c_int = 214; +pub const NID_id_smime_aa_contentHint: c_int = 215; +pub const NID_id_smime_aa_msgSigDigest: c_int = 216; +pub const NID_id_smime_aa_encapContentType: c_int = 217; +pub const NID_id_smime_aa_contentIdentifier: c_int = 218; +pub const NID_id_smime_aa_macValue: c_int = 219; +pub const NID_id_smime_aa_equivalentLabels: c_int = 220; +pub const NID_id_smime_aa_contentReference: c_int = 221; +pub const NID_id_smime_aa_encrypKeyPref: c_int = 222; +pub const NID_id_smime_aa_signingCertificate: c_int = 223; +pub const NID_id_smime_aa_smimeEncryptCerts: c_int = 224; +pub const NID_id_smime_aa_timeStampToken: c_int = 225; +pub const NID_id_smime_aa_ets_sigPolicyId: c_int = 226; +pub const NID_id_smime_aa_ets_commitmentType: c_int = 227; +pub const NID_id_smime_aa_ets_signerLocation: c_int = 228; +pub const NID_id_smime_aa_ets_signerAttr: c_int = 229; +pub const NID_id_smime_aa_ets_otherSigCert: c_int = 230; +pub const NID_id_smime_aa_ets_contentTimestamp: c_int = 231; +pub const NID_id_smime_aa_ets_CertificateRefs: c_int = 232; +pub const NID_id_smime_aa_ets_RevocationRefs: c_int = 233; +pub const NID_id_smime_aa_ets_certValues: c_int = 234; +pub const NID_id_smime_aa_ets_revocationValues: c_int = 235; +pub const NID_id_smime_aa_ets_escTimeStamp: c_int = 236; +pub const NID_id_smime_aa_ets_certCRLTimestamp: c_int = 237; +pub const NID_id_smime_aa_ets_archiveTimeStamp: c_int = 238; +pub const NID_id_smime_aa_signatureType: c_int = 239; +pub const NID_id_smime_aa_dvcs_dvc: c_int = 240; +pub const NID_id_smime_alg_ESDHwith3DES: c_int = 241; +pub const NID_id_smime_alg_ESDHwithRC2: c_int = 242; +pub const NID_id_smime_alg_3DESwrap: c_int = 243; +pub const NID_id_smime_alg_RC2wrap: c_int = 244; +pub const NID_id_smime_alg_ESDH: c_int = 245; +pub const NID_id_smime_alg_CMS3DESwrap: c_int = 246; +pub const NID_id_smime_alg_CMSRC2wrap: c_int = 247; +pub const NID_id_alg_PWRI_KEK: c_int = 893; +pub const NID_id_smime_cd_ldap: c_int = 248; +pub const NID_id_smime_spq_ets_sqt_uri: c_int = 249; +pub const NID_id_smime_spq_ets_sqt_unotice: c_int = 250; +pub const NID_id_smime_cti_ets_proofOfOrigin: c_int = 251; +pub const NID_id_smime_cti_ets_proofOfReceipt: c_int = 252; +pub const NID_id_smime_cti_ets_proofOfDelivery: c_int = 253; +pub const NID_id_smime_cti_ets_proofOfSender: c_int = 254; +pub const NID_id_smime_cti_ets_proofOfApproval: c_int = 255; +pub const NID_id_smime_cti_ets_proofOfCreation: c_int = 256; +pub const NID_friendlyName: c_int = 156; +pub const NID_localKeyID: c_int = 157; +pub const NID_ms_csp_name: c_int = 417; +pub const NID_LocalKeySet: c_int = 856; +pub const NID_x509Certificate: c_int = 158; +pub const NID_sdsiCertificate: c_int = 159; +pub const NID_x509Crl: c_int = 160; +pub const NID_pbe_WithSHA1And128BitRC4: c_int = 144; +pub const NID_pbe_WithSHA1And40BitRC4: c_int = 145; +pub const NID_pbe_WithSHA1And3_Key_TripleDES_CBC: c_int = 146; +pub const NID_pbe_WithSHA1And2_Key_TripleDES_CBC: c_int = 147; +pub const NID_pbe_WithSHA1And128BitRC2_CBC: c_int = 148; +pub const NID_pbe_WithSHA1And40BitRC2_CBC: c_int = 149; +pub const NID_keyBag: c_int = 150; +pub const NID_pkcs8ShroudedKeyBag: c_int = 151; +pub const NID_certBag: c_int = 152; +pub const NID_crlBag: c_int = 153; +pub const NID_secretBag: c_int = 154; +pub const NID_safeContentsBag: c_int = 155; +pub const NID_md2: c_int = 3; +pub const NID_md4: c_int = 257; +pub const NID_md5: c_int = 4; +pub const NID_md5_sha1: c_int = 114; +pub const NID_hmacWithMD5: c_int = 797; +pub const NID_hmacWithSHA1: c_int = 163; +pub const NID_hmacWithSHA224: c_int = 798; +pub const NID_hmacWithSHA256: c_int = 799; +pub const NID_hmacWithSHA384: c_int = 800; +pub const NID_hmacWithSHA512: c_int = 801; +pub const NID_rc2_cbc: c_int = 37; +pub const NID_rc2_ecb: c_int = 38; +pub const NID_rc2_cfb64: c_int = 39; +pub const NID_rc2_ofb64: c_int = 40; +pub const NID_rc2_40_cbc: c_int = 98; +pub const NID_rc2_64_cbc: c_int = 166; +pub const NID_rc4: c_int = 5; +pub const NID_rc4_40: c_int = 97; +pub const NID_des_ede3_cbc: c_int = 44; +pub const NID_rc5_cbc: c_int = 120; +pub const NID_rc5_ecb: c_int = 121; +pub const NID_rc5_cfb64: c_int = 122; +pub const NID_rc5_ofb64: c_int = 123; +pub const NID_ms_ext_req: c_int = 171; +pub const NID_ms_code_ind: c_int = 134; +pub const NID_ms_code_com: c_int = 135; +pub const NID_ms_ctl_sign: c_int = 136; +pub const NID_ms_sgc: c_int = 137; +pub const NID_ms_efs: c_int = 138; +pub const NID_ms_smartcard_login: c_int = 648; +pub const NID_ms_upn: c_int = 649; +pub const NID_idea_cbc: c_int = 34; +pub const NID_idea_ecb: c_int = 36; +pub const NID_idea_cfb64: c_int = 35; +pub const NID_idea_ofb64: c_int = 46; +pub const NID_bf_cbc: c_int = 91; +pub const NID_bf_ecb: c_int = 92; +pub const NID_bf_cfb64: c_int = 93; +pub const NID_bf_ofb64: c_int = 94; +pub const NID_id_pkix: c_int = 127; +pub const NID_id_pkix_mod: c_int = 258; +pub const NID_id_pe: c_int = 175; +pub const NID_id_qt: c_int = 259; +pub const NID_id_kp: c_int = 128; +pub const NID_id_it: c_int = 260; +pub const NID_id_pkip: c_int = 261; +pub const NID_id_alg: c_int = 262; +pub const NID_id_cmc: c_int = 263; +pub const NID_id_on: c_int = 264; +pub const NID_id_pda: c_int = 265; +pub const NID_id_aca: c_int = 266; +pub const NID_id_qcs: c_int = 267; +pub const NID_id_cct: c_int = 268; +pub const NID_id_ppl: c_int = 662; +pub const NID_id_ad: c_int = 176; +pub const NID_id_pkix1_explicit_88: c_int = 269; +pub const NID_id_pkix1_implicit_88: c_int = 270; +pub const NID_id_pkix1_explicit_93: c_int = 271; +pub const NID_id_pkix1_implicit_93: c_int = 272; +pub const NID_id_mod_crmf: c_int = 273; +pub const NID_id_mod_cmc: c_int = 274; +pub const NID_id_mod_kea_profile_88: c_int = 275; +pub const NID_id_mod_kea_profile_93: c_int = 276; +pub const NID_id_mod_cmp: c_int = 277; +pub const NID_id_mod_qualified_cert_88: c_int = 278; +pub const NID_id_mod_qualified_cert_93: c_int = 279; +pub const NID_id_mod_attribute_cert: c_int = 280; +pub const NID_id_mod_timestamp_protocol: c_int = 281; +pub const NID_id_mod_ocsp: c_int = 282; +pub const NID_id_mod_dvcs: c_int = 283; +pub const NID_id_mod_cmp2000: c_int = 284; +pub const NID_info_access: c_int = 177; +pub const NID_biometricInfo: c_int = 285; +pub const NID_qcStatements: c_int = 286; +pub const NID_ac_auditEntity: c_int = 287; +pub const NID_ac_targeting: c_int = 288; +pub const NID_aaControls: c_int = 289; +pub const NID_sbgp_ipAddrBlock: c_int = 290; +pub const NID_sbgp_autonomousSysNum: c_int = 291; +pub const NID_sbgp_routerIdentifier: c_int = 292; +pub const NID_ac_proxying: c_int = 397; +pub const NID_sinfo_access: c_int = 398; +pub const NID_proxyCertInfo: c_int = 663; +pub const NID_id_qt_cps: c_int = 164; +pub const NID_id_qt_unotice: c_int = 165; +pub const NID_textNotice: c_int = 293; +pub const NID_server_auth: c_int = 129; +pub const NID_client_auth: c_int = 130; +pub const NID_code_sign: c_int = 131; +pub const NID_email_protect: c_int = 132; +pub const NID_ipsecEndSystem: c_int = 294; +pub const NID_ipsecTunnel: c_int = 295; +pub const NID_ipsecUser: c_int = 296; +pub const NID_time_stamp: c_int = 133; +pub const NID_OCSP_sign: c_int = 180; +pub const NID_dvcs: c_int = 297; +pub const NID_id_it_caProtEncCert: c_int = 298; +pub const NID_id_it_signKeyPairTypes: c_int = 299; +pub const NID_id_it_encKeyPairTypes: c_int = 300; +pub const NID_id_it_preferredSymmAlg: c_int = 301; +pub const NID_id_it_caKeyUpdateInfo: c_int = 302; +pub const NID_id_it_currentCRL: c_int = 303; +pub const NID_id_it_unsupportedOIDs: c_int = 304; +pub const NID_id_it_subscriptionRequest: c_int = 305; +pub const NID_id_it_subscriptionResponse: c_int = 306; +pub const NID_id_it_keyPairParamReq: c_int = 307; +pub const NID_id_it_keyPairParamRep: c_int = 308; +pub const NID_id_it_revPassphrase: c_int = 309; +pub const NID_id_it_implicitConfirm: c_int = 310; +pub const NID_id_it_confirmWaitTime: c_int = 311; +pub const NID_id_it_origPKIMessage: c_int = 312; +pub const NID_id_it_suppLangTags: c_int = 784; +pub const NID_id_regCtrl: c_int = 313; +pub const NID_id_regInfo: c_int = 314; +pub const NID_id_regCtrl_regToken: c_int = 315; +pub const NID_id_regCtrl_authenticator: c_int = 316; +pub const NID_id_regCtrl_pkiPublicationInfo: c_int = 317; +pub const NID_id_regCtrl_pkiArchiveOptions: c_int = 318; +pub const NID_id_regCtrl_oldCertID: c_int = 319; +pub const NID_id_regCtrl_protocolEncrKey: c_int = 320; +pub const NID_id_regInfo_utf8Pairs: c_int = 321; +pub const NID_id_regInfo_certReq: c_int = 322; +pub const NID_id_alg_des40: c_int = 323; +pub const NID_id_alg_noSignature: c_int = 324; +pub const NID_id_alg_dh_sig_hmac_sha1: c_int = 325; +pub const NID_id_alg_dh_pop: c_int = 326; +pub const NID_id_cmc_statusInfo: c_int = 327; +pub const NID_id_cmc_identification: c_int = 328; +pub const NID_id_cmc_identityProof: c_int = 329; +pub const NID_id_cmc_dataReturn: c_int = 330; +pub const NID_id_cmc_transactionId: c_int = 331; +pub const NID_id_cmc_senderNonce: c_int = 332; +pub const NID_id_cmc_recipientNonce: c_int = 333; +pub const NID_id_cmc_addExtensions: c_int = 334; +pub const NID_id_cmc_encryptedPOP: c_int = 335; +pub const NID_id_cmc_decryptedPOP: c_int = 336; +pub const NID_id_cmc_lraPOPWitness: c_int = 337; +pub const NID_id_cmc_getCert: c_int = 338; +pub const NID_id_cmc_getCRL: c_int = 339; +pub const NID_id_cmc_revokeRequest: c_int = 340; +pub const NID_id_cmc_regInfo: c_int = 341; +pub const NID_id_cmc_responseInfo: c_int = 342; +pub const NID_id_cmc_queryPending: c_int = 343; +pub const NID_id_cmc_popLinkRandom: c_int = 344; +pub const NID_id_cmc_popLinkWitness: c_int = 345; +pub const NID_id_cmc_confirmCertAcceptance: c_int = 346; +pub const NID_id_on_personalData: c_int = 347; +pub const NID_id_on_permanentIdentifier: c_int = 858; +pub const NID_id_pda_dateOfBirth: c_int = 348; +pub const NID_id_pda_placeOfBirth: c_int = 349; +pub const NID_id_pda_gender: c_int = 351; +pub const NID_id_pda_countryOfCitizenship: c_int = 352; +pub const NID_id_pda_countryOfResidence: c_int = 353; +pub const NID_id_aca_authenticationInfo: c_int = 354; +pub const NID_id_aca_accessIdentity: c_int = 355; +pub const NID_id_aca_chargingIdentity: c_int = 356; +pub const NID_id_aca_group: c_int = 357; +pub const NID_id_aca_role: c_int = 358; +pub const NID_id_aca_encAttrs: c_int = 399; +pub const NID_id_qcs_pkixQCSyntax_v1: c_int = 359; +pub const NID_id_cct_crs: c_int = 360; +pub const NID_id_cct_PKIData: c_int = 361; +pub const NID_id_cct_PKIResponse: c_int = 362; +pub const NID_id_ppl_anyLanguage: c_int = 664; +pub const NID_id_ppl_inheritAll: c_int = 665; +pub const NID_Independent: c_int = 667; +pub const NID_ad_OCSP: c_int = 178; +pub const NID_ad_ca_issuers: c_int = 179; +pub const NID_ad_timeStamping: c_int = 363; +pub const NID_ad_dvcs: c_int = 364; +pub const NID_caRepository: c_int = 785; +pub const NID_id_pkix_OCSP_basic: c_int = 365; +pub const NID_id_pkix_OCSP_Nonce: c_int = 366; +pub const NID_id_pkix_OCSP_CrlID: c_int = 367; +pub const NID_id_pkix_OCSP_acceptableResponses: c_int = 368; +pub const NID_id_pkix_OCSP_noCheck: c_int = 369; +pub const NID_id_pkix_OCSP_archiveCutoff: c_int = 370; +pub const NID_id_pkix_OCSP_serviceLocator: c_int = 371; +pub const NID_id_pkix_OCSP_extendedStatus: c_int = 372; +pub const NID_id_pkix_OCSP_valid: c_int = 373; +pub const NID_id_pkix_OCSP_path: c_int = 374; +pub const NID_id_pkix_OCSP_trustRoot: c_int = 375; +pub const NID_algorithm: c_int = 376; +pub const NID_md5WithRSA: c_int = 104; +pub const NID_des_ecb: c_int = 29; +pub const NID_des_cbc: c_int = 31; +pub const NID_des_ofb64: c_int = 45; +pub const NID_des_cfb64: c_int = 30; +pub const NID_rsaSignature: c_int = 377; +pub const NID_dsa_2: c_int = 67; +pub const NID_dsaWithSHA: c_int = 66; +pub const NID_shaWithRSAEncryption: c_int = 42; +pub const NID_des_ede_ecb: c_int = 32; +pub const NID_des_ede3_ecb: c_int = 33; +pub const NID_des_ede_cbc: c_int = 43; +pub const NID_des_ede_cfb64: c_int = 60; +pub const NID_des_ede3_cfb64: c_int = 61; +pub const NID_des_ede_ofb64: c_int = 62; +pub const NID_des_ede3_ofb64: c_int = 63; +pub const NID_desx_cbc: c_int = 80; +pub const NID_sha: c_int = 41; +pub const NID_sha1: c_int = 64; +pub const NID_dsaWithSHA1_2: c_int = 70; +pub const NID_sha1WithRSA: c_int = 115; +pub const NID_ripemd160: c_int = 117; +pub const NID_ripemd160WithRSA: c_int = 119; +pub const NID_sxnet: c_int = 143; +pub const NID_X500: c_int = 11; +pub const NID_X509: c_int = 12; +pub const NID_commonName: c_int = 13; +pub const NID_surname: c_int = 100; +pub const NID_serialNumber: c_int = 105; +pub const NID_countryName: c_int = 14; +pub const NID_localityName: c_int = 15; +pub const NID_stateOrProvinceName: c_int = 16; +pub const NID_streetAddress: c_int = 660; +pub const NID_organizationName: c_int = 17; +pub const NID_organizationalUnitName: c_int = 18; +pub const NID_title: c_int = 106; +pub const NID_description: c_int = 107; +pub const NID_searchGuide: c_int = 859; +pub const NID_businessCategory: c_int = 860; +pub const NID_postalAddress: c_int = 861; +pub const NID_postalCode: c_int = 661; +pub const NID_postOfficeBox: c_int = 862; +pub const NID_physicalDeliveryOfficeName: c_int = 863; +pub const NID_telephoneNumber: c_int = 864; +pub const NID_telexNumber: c_int = 865; +pub const NID_teletexTerminalIdentifier: c_int = 866; +pub const NID_facsimileTelephoneNumber: c_int = 867; +pub const NID_x121Address: c_int = 868; +pub const NID_internationaliSDNNumber: c_int = 869; +pub const NID_registeredAddress: c_int = 870; +pub const NID_destinationIndicator: c_int = 871; +pub const NID_preferredDeliveryMethod: c_int = 872; +pub const NID_presentationAddress: c_int = 873; +pub const NID_supportedApplicationContext: c_int = 874; +pub const NID_member: c_int = 875; +pub const NID_owner: c_int = 876; +pub const NID_roleOccupant: c_int = 877; +pub const NID_seeAlso: c_int = 878; +pub const NID_userPassword: c_int = 879; +pub const NID_userCertificate: c_int = 880; +pub const NID_cACertificate: c_int = 881; +pub const NID_authorityRevocationList: c_int = 882; +pub const NID_certificateRevocationList: c_int = 883; +pub const NID_crossCertificatePair: c_int = 884; +pub const NID_name: c_int = 173; +pub const NID_givenName: c_int = 99; +pub const NID_initials: c_int = 101; +pub const NID_generationQualifier: c_int = 509; +pub const NID_x500UniqueIdentifier: c_int = 503; +pub const NID_dnQualifier: c_int = 174; +pub const NID_enhancedSearchGuide: c_int = 885; +pub const NID_protocolInformation: c_int = 886; +pub const NID_distinguishedName: c_int = 887; +pub const NID_uniqueMember: c_int = 888; +pub const NID_houseIdentifier: c_int = 889; +pub const NID_supportedAlgorithms: c_int = 890; +pub const NID_deltaRevocationList: c_int = 891; +pub const NID_dmdName: c_int = 892; +pub const NID_pseudonym: c_int = 510; +pub const NID_role: c_int = 400; +pub const NID_X500algorithms: c_int = 378; +pub const NID_rsa: c_int = 19; +pub const NID_mdc2WithRSA: c_int = 96; +pub const NID_mdc2: c_int = 95; +pub const NID_id_ce: c_int = 81; +pub const NID_subject_directory_attributes: c_int = 769; +pub const NID_subject_key_identifier: c_int = 82; +pub const NID_key_usage: c_int = 83; +pub const NID_private_key_usage_period: c_int = 84; +pub const NID_subject_alt_name: c_int = 85; +pub const NID_issuer_alt_name: c_int = 86; +pub const NID_basic_constraints: c_int = 87; +pub const NID_crl_number: c_int = 88; +pub const NID_crl_reason: c_int = 141; +pub const NID_invalidity_date: c_int = 142; +pub const NID_delta_crl: c_int = 140; +pub const NID_issuing_distribution_point: c_int = 770; +pub const NID_certificate_issuer: c_int = 771; +pub const NID_name_constraints: c_int = 666; +pub const NID_crl_distribution_points: c_int = 103; +pub const NID_certificate_policies: c_int = 89; +pub const NID_any_policy: c_int = 746; +pub const NID_policy_mappings: c_int = 747; +pub const NID_authority_key_identifier: c_int = 90; +pub const NID_policy_constraints: c_int = 401; pub const NID_ext_key_usage: c_int = 126; -pub const NID_key_usage: c_int = 83; -pub const NID_dsa: c_int = 116; -pub const NID_hmac: c_int = 855; +pub const NID_freshest_crl: c_int = 857; +pub const NID_inhibit_any_policy: c_int = 748; +pub const NID_target_information: c_int = 402; +pub const NID_no_rev_avail: c_int = 403; +pub const NID_anyExtendedKeyUsage: c_int = 910; +pub const NID_netscape: c_int = 57; +pub const NID_netscape_cert_extension: c_int = 58; +pub const NID_netscape_data_type: c_int = 59; +pub const NID_netscape_cert_type: c_int = 71; +pub const NID_netscape_base_url: c_int = 72; +pub const NID_netscape_revocation_url: c_int = 73; +pub const NID_netscape_ca_revocation_url: c_int = 74; +pub const NID_netscape_renewal_url: c_int = 75; +pub const NID_netscape_ca_policy_url: c_int = 76; +pub const NID_netscape_ssl_server_name: c_int = 77; +pub const NID_netscape_comment: c_int = 78; +pub const NID_netscape_cert_sequence: c_int = 79; +pub const NID_ns_sgc: c_int = 139; +pub const NID_org: c_int = 379; +pub const NID_dod: c_int = 380; +pub const NID_iana: c_int = 381; +pub const NID_Directory: c_int = 382; +pub const NID_Management: c_int = 383; +pub const NID_Experimental: c_int = 384; +pub const NID_Private: c_int = 385; +pub const NID_Security: c_int = 386; +pub const NID_SNMPv2: c_int = 387; +pub const NID_Mail: c_int = 388; +pub const NID_Enterprises: c_int = 389; +pub const NID_dcObject: c_int = 390; +pub const NID_mime_mhs: c_int = 504; +pub const NID_mime_mhs_headings: c_int = 505; +pub const NID_mime_mhs_bodies: c_int = 506; +pub const NID_id_hex_partial_message: c_int = 507; +pub const NID_id_hex_multipart_message: c_int = 508; +pub const NID_rle_compression: c_int = 124; +pub const NID_zlib_compression: c_int = 125; +pub const NID_aes_128_ecb: c_int = 418; +pub const NID_aes_128_cbc: c_int = 419; +pub const NID_aes_128_ofb128: c_int = 420; +pub const NID_aes_128_cfb128: c_int = 421; +pub const NID_id_aes128_wrap: c_int = 788; +pub const NID_aes_128_gcm: c_int = 895; +pub const NID_aes_128_ccm: c_int = 896; +pub const NID_id_aes128_wrap_pad: c_int = 897; +pub const NID_aes_192_ecb: c_int = 422; +pub const NID_aes_192_cbc: c_int = 423; +pub const NID_aes_192_ofb128: c_int = 424; +pub const NID_aes_192_cfb128: c_int = 425; +pub const NID_id_aes192_wrap: c_int = 789; +pub const NID_aes_192_gcm: c_int = 898; +pub const NID_aes_192_ccm: c_int = 899; +pub const NID_id_aes192_wrap_pad: c_int = 900; +pub const NID_aes_256_ecb: c_int = 426; +pub const NID_aes_256_cbc: c_int = 427; +pub const NID_aes_256_ofb128: c_int = 428; +pub const NID_aes_256_cfb128: c_int = 429; +pub const NID_id_aes256_wrap: c_int = 790; +pub const NID_aes_256_gcm: c_int = 901; +pub const NID_aes_256_ccm: c_int = 902; +pub const NID_id_aes256_wrap_pad: c_int = 903; +pub const NID_aes_128_cfb1: c_int = 650; +pub const NID_aes_192_cfb1: c_int = 651; +pub const NID_aes_256_cfb1: c_int = 652; +pub const NID_aes_128_cfb8: c_int = 653; +pub const NID_aes_192_cfb8: c_int = 654; +pub const NID_aes_256_cfb8: c_int = 655; +pub const NID_aes_128_ctr: c_int = 904; +pub const NID_aes_192_ctr: c_int = 905; +pub const NID_aes_256_ctr: c_int = 906; +pub const NID_aes_128_xts: c_int = 913; +pub const NID_aes_256_xts: c_int = 914; +pub const NID_des_cfb1: c_int = 656; +pub const NID_des_cfb8: c_int = 657; +pub const NID_des_ede3_cfb1: c_int = 658; +pub const NID_des_ede3_cfb8: c_int = 659; +pub const NID_sha256: c_int = 672; +pub const NID_sha384: c_int = 673; +pub const NID_sha512: c_int = 674; +pub const NID_sha224: c_int = 675; +pub const NID_dsa_with_SHA224: c_int = 802; +pub const NID_dsa_with_SHA256: c_int = 803; +pub const NID_hold_instruction_code: c_int = 430; +pub const NID_hold_instruction_none: c_int = 431; +pub const NID_hold_instruction_call_issuer: c_int = 432; +pub const NID_hold_instruction_reject: c_int = 433; +pub const NID_data: c_int = 434; +pub const NID_pss: c_int = 435; +pub const NID_ucl: c_int = 436; +pub const NID_pilot: c_int = 437; +pub const NID_pilotAttributeType: c_int = 438; +pub const NID_pilotAttributeSyntax: c_int = 439; +pub const NID_pilotObjectClass: c_int = 440; +pub const NID_pilotGroups: c_int = 441; +pub const NID_iA5StringSyntax: c_int = 442; +pub const NID_caseIgnoreIA5StringSyntax: c_int = 443; +pub const NID_pilotObject: c_int = 444; +pub const NID_pilotPerson: c_int = 445; +pub const NID_account: c_int = 446; +pub const NID_document: c_int = 447; +pub const NID_room: c_int = 448; +pub const NID_documentSeries: c_int = 449; +pub const NID_Domain: c_int = 392; +pub const NID_rFC822localPart: c_int = 450; +pub const NID_dNSDomain: c_int = 451; +pub const NID_domainRelatedObject: c_int = 452; +pub const NID_friendlyCountry: c_int = 453; +pub const NID_simpleSecurityObject: c_int = 454; +pub const NID_pilotOrganization: c_int = 455; +pub const NID_pilotDSA: c_int = 456; +pub const NID_qualityLabelledData: c_int = 457; +pub const NID_userId: c_int = 458; +pub const NID_textEncodedORAddress: c_int = 459; +pub const NID_rfc822Mailbox: c_int = 460; +pub const NID_info: c_int = 461; +pub const NID_favouriteDrink: c_int = 462; +pub const NID_roomNumber: c_int = 463; +pub const NID_photo: c_int = 464; +pub const NID_userClass: c_int = 465; +pub const NID_host: c_int = 466; +pub const NID_manager: c_int = 467; +pub const NID_documentIdentifier: c_int = 468; +pub const NID_documentTitle: c_int = 469; +pub const NID_documentVersion: c_int = 470; +pub const NID_documentAuthor: c_int = 471; +pub const NID_documentLocation: c_int = 472; +pub const NID_homeTelephoneNumber: c_int = 473; +pub const NID_secretary: c_int = 474; +pub const NID_otherMailbox: c_int = 475; +pub const NID_lastModifiedTime: c_int = 476; +pub const NID_lastModifiedBy: c_int = 477; +pub const NID_domainComponent: c_int = 391; +pub const NID_aRecord: c_int = 478; +pub const NID_pilotAttributeType27: c_int = 479; +pub const NID_mXRecord: c_int = 480; +pub const NID_nSRecord: c_int = 481; +pub const NID_sOARecord: c_int = 482; +pub const NID_cNAMERecord: c_int = 483; +pub const NID_associatedDomain: c_int = 484; +pub const NID_associatedName: c_int = 485; +pub const NID_homePostalAddress: c_int = 486; +pub const NID_personalTitle: c_int = 487; +pub const NID_mobileTelephoneNumber: c_int = 488; +pub const NID_pagerTelephoneNumber: c_int = 489; +pub const NID_friendlyCountryName: c_int = 490; +pub const NID_organizationalStatus: c_int = 491; +pub const NID_janetMailbox: c_int = 492; +pub const NID_mailPreferenceOption: c_int = 493; +pub const NID_buildingName: c_int = 494; +pub const NID_dSAQuality: c_int = 495; +pub const NID_singleLevelQuality: c_int = 496; +pub const NID_subtreeMinimumQuality: c_int = 497; +pub const NID_subtreeMaximumQuality: c_int = 498; +pub const NID_personalSignature: c_int = 499; +pub const NID_dITRedirect: c_int = 500; +pub const NID_audio: c_int = 501; +pub const NID_documentPublisher: c_int = 502; +pub const NID_id_set: c_int = 512; +pub const NID_set_ctype: c_int = 513; +pub const NID_set_msgExt: c_int = 514; +pub const NID_set_attr: c_int = 515; +pub const NID_set_policy: c_int = 516; +pub const NID_set_certExt: c_int = 517; +pub const NID_set_brand: c_int = 518; +pub const NID_setct_PANData: c_int = 519; +pub const NID_setct_PANToken: c_int = 520; +pub const NID_setct_PANOnly: c_int = 521; +pub const NID_setct_OIData: c_int = 522; +pub const NID_setct_PI: c_int = 523; +pub const NID_setct_PIData: c_int = 524; +pub const NID_setct_PIDataUnsigned: c_int = 525; +pub const NID_setct_HODInput: c_int = 526; +pub const NID_setct_AuthResBaggage: c_int = 527; +pub const NID_setct_AuthRevReqBaggage: c_int = 528; +pub const NID_setct_AuthRevResBaggage: c_int = 529; +pub const NID_setct_CapTokenSeq: c_int = 530; +pub const NID_setct_PInitResData: c_int = 531; +pub const NID_setct_PI_TBS: c_int = 532; +pub const NID_setct_PResData: c_int = 533; +pub const NID_setct_AuthReqTBS: c_int = 534; +pub const NID_setct_AuthResTBS: c_int = 535; +pub const NID_setct_AuthResTBSX: c_int = 536; +pub const NID_setct_AuthTokenTBS: c_int = 537; +pub const NID_setct_CapTokenData: c_int = 538; +pub const NID_setct_CapTokenTBS: c_int = 539; +pub const NID_setct_AcqCardCodeMsg: c_int = 540; +pub const NID_setct_AuthRevReqTBS: c_int = 541; +pub const NID_setct_AuthRevResData: c_int = 542; +pub const NID_setct_AuthRevResTBS: c_int = 543; +pub const NID_setct_CapReqTBS: c_int = 544; +pub const NID_setct_CapReqTBSX: c_int = 545; +pub const NID_setct_CapResData: c_int = 546; +pub const NID_setct_CapRevReqTBS: c_int = 547; +pub const NID_setct_CapRevReqTBSX: c_int = 548; +pub const NID_setct_CapRevResData: c_int = 549; +pub const NID_setct_CredReqTBS: c_int = 550; +pub const NID_setct_CredReqTBSX: c_int = 551; +pub const NID_setct_CredResData: c_int = 552; +pub const NID_setct_CredRevReqTBS: c_int = 553; +pub const NID_setct_CredRevReqTBSX: c_int = 554; +pub const NID_setct_CredRevResData: c_int = 555; +pub const NID_setct_PCertReqData: c_int = 556; +pub const NID_setct_PCertResTBS: c_int = 557; +pub const NID_setct_BatchAdminReqData: c_int = 558; +pub const NID_setct_BatchAdminResData: c_int = 559; +pub const NID_setct_CardCInitResTBS: c_int = 560; +pub const NID_setct_MeAqCInitResTBS: c_int = 561; +pub const NID_setct_RegFormResTBS: c_int = 562; +pub const NID_setct_CertReqData: c_int = 563; +pub const NID_setct_CertReqTBS: c_int = 564; +pub const NID_setct_CertResData: c_int = 565; +pub const NID_setct_CertInqReqTBS: c_int = 566; +pub const NID_setct_ErrorTBS: c_int = 567; +pub const NID_setct_PIDualSignedTBE: c_int = 568; +pub const NID_setct_PIUnsignedTBE: c_int = 569; +pub const NID_setct_AuthReqTBE: c_int = 570; +pub const NID_setct_AuthResTBE: c_int = 571; +pub const NID_setct_AuthResTBEX: c_int = 572; +pub const NID_setct_AuthTokenTBE: c_int = 573; +pub const NID_setct_CapTokenTBE: c_int = 574; +pub const NID_setct_CapTokenTBEX: c_int = 575; +pub const NID_setct_AcqCardCodeMsgTBE: c_int = 576; +pub const NID_setct_AuthRevReqTBE: c_int = 577; +pub const NID_setct_AuthRevResTBE: c_int = 578; +pub const NID_setct_AuthRevResTBEB: c_int = 579; +pub const NID_setct_CapReqTBE: c_int = 580; +pub const NID_setct_CapReqTBEX: c_int = 581; +pub const NID_setct_CapResTBE: c_int = 582; +pub const NID_setct_CapRevReqTBE: c_int = 583; +pub const NID_setct_CapRevReqTBEX: c_int = 584; +pub const NID_setct_CapRevResTBE: c_int = 585; +pub const NID_setct_CredReqTBE: c_int = 586; +pub const NID_setct_CredReqTBEX: c_int = 587; +pub const NID_setct_CredResTBE: c_int = 588; +pub const NID_setct_CredRevReqTBE: c_int = 589; +pub const NID_setct_CredRevReqTBEX: c_int = 590; +pub const NID_setct_CredRevResTBE: c_int = 591; +pub const NID_setct_BatchAdminReqTBE: c_int = 592; +pub const NID_setct_BatchAdminResTBE: c_int = 593; +pub const NID_setct_RegFormReqTBE: c_int = 594; +pub const NID_setct_CertReqTBE: c_int = 595; +pub const NID_setct_CertReqTBEX: c_int = 596; +pub const NID_setct_CertResTBE: c_int = 597; +pub const NID_setct_CRLNotificationTBS: c_int = 598; +pub const NID_setct_CRLNotificationResTBS: c_int = 599; +pub const NID_setct_BCIDistributionTBS: c_int = 600; +pub const NID_setext_genCrypt: c_int = 601; +pub const NID_setext_miAuth: c_int = 602; +pub const NID_setext_pinSecure: c_int = 603; +pub const NID_setext_pinAny: c_int = 604; +pub const NID_setext_track2: c_int = 605; +pub const NID_setext_cv: c_int = 606; +pub const NID_set_policy_root: c_int = 607; +pub const NID_setCext_hashedRoot: c_int = 608; +pub const NID_setCext_certType: c_int = 609; +pub const NID_setCext_merchData: c_int = 610; +pub const NID_setCext_cCertRequired: c_int = 611; +pub const NID_setCext_tunneling: c_int = 612; +pub const NID_setCext_setExt: c_int = 613; +pub const NID_setCext_setQualf: c_int = 614; +pub const NID_setCext_PGWYcapabilities: c_int = 615; +pub const NID_setCext_TokenIdentifier: c_int = 616; +pub const NID_setCext_Track2Data: c_int = 617; +pub const NID_setCext_TokenType: c_int = 618; +pub const NID_setCext_IssuerCapabilities: c_int = 619; +pub const NID_setAttr_Cert: c_int = 620; +pub const NID_setAttr_PGWYcap: c_int = 621; +pub const NID_setAttr_TokenType: c_int = 622; +pub const NID_setAttr_IssCap: c_int = 623; +pub const NID_set_rootKeyThumb: c_int = 624; +pub const NID_set_addPolicy: c_int = 625; +pub const NID_setAttr_Token_EMV: c_int = 626; +pub const NID_setAttr_Token_B0Prime: c_int = 627; +pub const NID_setAttr_IssCap_CVM: c_int = 628; +pub const NID_setAttr_IssCap_T2: c_int = 629; +pub const NID_setAttr_IssCap_Sig: c_int = 630; +pub const NID_setAttr_GenCryptgrm: c_int = 631; +pub const NID_setAttr_T2Enc: c_int = 632; +pub const NID_setAttr_T2cleartxt: c_int = 633; +pub const NID_setAttr_TokICCsig: c_int = 634; +pub const NID_setAttr_SecDevSig: c_int = 635; +pub const NID_set_brand_IATA_ATA: c_int = 636; +pub const NID_set_brand_Diners: c_int = 637; +pub const NID_set_brand_AmericanExpress: c_int = 638; +pub const NID_set_brand_JCB: c_int = 639; +pub const NID_set_brand_Visa: c_int = 640; +pub const NID_set_brand_MasterCard: c_int = 641; +pub const NID_set_brand_Novus: c_int = 642; +pub const NID_des_cdmf: c_int = 643; +pub const NID_rsaOAEPEncryptionSET: c_int = 644; +pub const NID_ipsec3: c_int = 749; +pub const NID_ipsec4: c_int = 750; +pub const NID_whirlpool: c_int = 804; +pub const NID_cryptopro: c_int = 805; +pub const NID_cryptocom: c_int = 806; +pub const NID_id_GostR3411_94_with_GostR3410_2001: c_int = 807; +pub const NID_id_GostR3411_94_with_GostR3410_94: c_int = 808; +pub const NID_id_GostR3411_94: c_int = 809; +pub const NID_id_HMACGostR3411_94: c_int = 810; +pub const NID_id_GostR3410_2001: c_int = 811; +pub const NID_id_GostR3410_94: c_int = 812; +pub const NID_id_Gost28147_89: c_int = 813; +pub const NID_gost89_cnt: c_int = 814; +pub const NID_id_Gost28147_89_MAC: c_int = 815; +pub const NID_id_GostR3411_94_prf: c_int = 816; +pub const NID_id_GostR3410_2001DH: c_int = 817; +pub const NID_id_GostR3410_94DH: c_int = 818; +pub const NID_id_Gost28147_89_CryptoPro_KeyMeshing: c_int = 819; +pub const NID_id_Gost28147_89_None_KeyMeshing: c_int = 820; +pub const NID_id_GostR3411_94_TestParamSet: c_int = 821; +pub const NID_id_GostR3411_94_CryptoProParamSet: c_int = 822; +pub const NID_id_Gost28147_89_TestParamSet: c_int = 823; +pub const NID_id_Gost28147_89_CryptoPro_A_ParamSet: c_int = 824; +pub const NID_id_Gost28147_89_CryptoPro_B_ParamSet: c_int = 825; +pub const NID_id_Gost28147_89_CryptoPro_C_ParamSet: c_int = 826; +pub const NID_id_Gost28147_89_CryptoPro_D_ParamSet: c_int = 827; +pub const NID_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet: c_int = 828; +pub const NID_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet: c_int = 829; +pub const NID_id_Gost28147_89_CryptoPro_RIC_1_ParamSet: c_int = 830; +pub const NID_id_GostR3410_94_TestParamSet: c_int = 831; +pub const NID_id_GostR3410_94_CryptoPro_A_ParamSet: c_int = 832; +pub const NID_id_GostR3410_94_CryptoPro_B_ParamSet: c_int = 833; +pub const NID_id_GostR3410_94_CryptoPro_C_ParamSet: c_int = 834; +pub const NID_id_GostR3410_94_CryptoPro_D_ParamSet: c_int = 835; +pub const NID_id_GostR3410_94_CryptoPro_XchA_ParamSet: c_int = 836; +pub const NID_id_GostR3410_94_CryptoPro_XchB_ParamSet: c_int = 837; +pub const NID_id_GostR3410_94_CryptoPro_XchC_ParamSet: c_int = 838; +pub const NID_id_GostR3410_2001_TestParamSet: c_int = 839; +pub const NID_id_GostR3410_2001_CryptoPro_A_ParamSet: c_int = 840; +pub const NID_id_GostR3410_2001_CryptoPro_B_ParamSet: c_int = 841; +pub const NID_id_GostR3410_2001_CryptoPro_C_ParamSet: c_int = 842; +pub const NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet: c_int = 843; +pub const NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet: c_int = 844; +pub const NID_id_GostR3410_94_a: c_int = 845; +pub const NID_id_GostR3410_94_aBis: c_int = 846; +pub const NID_id_GostR3410_94_b: c_int = 847; +pub const NID_id_GostR3410_94_bBis: c_int = 848; +pub const NID_id_Gost28147_89_cc: c_int = 849; +pub const NID_id_GostR3410_94_cc: c_int = 850; +pub const NID_id_GostR3410_2001_cc: c_int = 851; +pub const NID_id_GostR3411_94_with_GostR3410_94_cc: c_int = 852; +pub const NID_id_GostR3411_94_with_GostR3410_2001_cc: c_int = 853; +pub const NID_id_GostR3410_2001_ParamSet_cc: c_int = 854; +pub const NID_camellia_128_cbc: c_int = 751; +pub const NID_camellia_192_cbc: c_int = 752; +pub const NID_camellia_256_cbc: c_int = 753; +pub const NID_id_camellia128_wrap: c_int = 907; +pub const NID_id_camellia192_wrap: c_int = 908; +pub const NID_id_camellia256_wrap: c_int = 909; +pub const NID_camellia_128_ecb: c_int = 754; +pub const NID_camellia_128_ofb128: c_int = 766; +pub const NID_camellia_128_cfb128: c_int = 757; +pub const NID_camellia_192_ecb: c_int = 755; +pub const NID_camellia_192_ofb128: c_int = 767; +pub const NID_camellia_192_cfb128: c_int = 758; +pub const NID_camellia_256_ecb: c_int = 756; +pub const NID_camellia_256_ofb128: c_int = 768; +pub const NID_camellia_256_cfb128: c_int = 759; +pub const NID_camellia_128_cfb1: c_int = 760; +pub const NID_camellia_192_cfb1: c_int = 761; +pub const NID_camellia_256_cfb1: c_int = 762; +pub const NID_camellia_128_cfb8: c_int = 763; +pub const NID_camellia_192_cfb8: c_int = 764; +pub const NID_camellia_256_cfb8: c_int = 765; +pub const NID_kisa: c_int = 773; +pub const NID_seed_ecb: c_int = 776; +pub const NID_seed_cbc: c_int = 777; +pub const NID_seed_cfb128: c_int = 779; +pub const NID_seed_ofb128: c_int = 778; +pub const NID_hmac: c_int = 855; +pub const NID_cmac: c_int = 894; +pub const NID_rc4_hmac_md5: c_int = 915; +pub const NID_aes_128_cbc_hmac_sha1: c_int = 916; +pub const NID_aes_192_cbc_hmac_sha1: c_int = 917; +pub const NID_aes_256_cbc_hmac_sha1: c_int = 918; +pub const NID_aes_128_cbc_hmac_sha256: c_int = 948; +pub const NID_aes_192_cbc_hmac_sha256: c_int = 949; +pub const NID_aes_256_cbc_hmac_sha256: c_int = 950; +pub const NID_dhpublicnumber: c_int = 920; +pub const NID_brainpoolP160r1: c_int = 921; +pub const NID_brainpoolP160t1: c_int = 922; +pub const NID_brainpoolP192r1: c_int = 923; +pub const NID_brainpoolP192t1: c_int = 924; +pub const NID_brainpoolP224r1: c_int = 925; +pub const NID_brainpoolP224t1: c_int = 926; +pub const NID_brainpoolP256r1: c_int = 927; +pub const NID_brainpoolP256t1: c_int = 928; +pub const NID_brainpoolP320r1: c_int = 929; +pub const NID_brainpoolP320t1: c_int = 930; +pub const NID_brainpoolP384r1: c_int = 931; +pub const NID_brainpoolP384t1: c_int = 932; +pub const NID_brainpoolP512r1: c_int = 933; +pub const NID_brainpoolP512t1: c_int = 934; +pub const NID_dhSinglePass_stdDH_sha1kdf_scheme: c_int = 936; +pub const NID_dhSinglePass_stdDH_sha224kdf_scheme: c_int = 937; +pub const NID_dhSinglePass_stdDH_sha256kdf_scheme: c_int = 938; +pub const NID_dhSinglePass_stdDH_sha384kdf_scheme: c_int = 939; +pub const NID_dhSinglePass_stdDH_sha512kdf_scheme: c_int = 940; +pub const NID_dhSinglePass_cofactorDH_sha1kdf_scheme: c_int = 941; +pub const NID_dhSinglePass_cofactorDH_sha224kdf_scheme: c_int = 942; +pub const NID_dhSinglePass_cofactorDH_sha256kdf_scheme: c_int = 943; +pub const NID_dhSinglePass_cofactorDH_sha384kdf_scheme: c_int = 944; +pub const NID_dhSinglePass_cofactorDH_sha512kdf_scheme: c_int = 945; +pub const NID_dh_std_kdf: c_int = 946; +pub const NID_dh_cofactor_kdf: c_int = 947; +pub const NID_ct_precert_scts: c_int = 951; +pub const NID_ct_precert_poison: c_int = 952; +pub const NID_ct_precert_signer: c_int = 953; +pub const NID_ct_cert_scts: c_int = 954; +pub const NID_jurisdictionLocalityName: c_int = 955; +pub const NID_jurisdictionStateOrProvinceName: c_int = 956; +pub const NID_jurisdictionCountryName: c_int = 957; pub const PKCS5_SALT_LEN: c_int = 8; diff --git a/openssl/src/nid.rs b/openssl/src/nid.rs index 874d4a6f..abc377da 100644 --- a/openssl/src/nid.rs +++ b/openssl/src/nid.rs @@ -1,196 +1,3820 @@ -#[allow(non_camel_case_types)] -#[derive(Copy, Clone, Hash, PartialEq, Eq)] -#[repr(usize)] -pub enum Nid { - Undefined, // 0 - Rsadsi, - Pkcs, - MD2, - MD4, - MD5, - RC4, - RsaEncryption, - RSA_MD2, - RSA_MD5, - PBE_MD2_DES, // 10 - X500, - x509, - CN, - C, - L, - ST, - O, - OU, - RSA, - Pkcs7, // 20 - Pkcs7_data, - Pkcs7_signedData, - Pkcs7_envelopedData, - Pkcs7_signedAndEnvelopedData, - Pkcs7_digestData, - Pkcs7_encryptedData, - Pkcs3, - DhKeyAgreement, - DES_ECB, - DES_CFB, // 30 - DES_CBC, - DES_EDE, - DES_EDE3, - IDEA_CBC, - IDEA_CFB, - IDEA_ECB, - RC2_CBC, - RC2_ECB, - RC2_CFB, - RC2_OFB, // 40 - SHA, - RSA_SHA, - DES_EDE_CBC, - DES_EDE3_CBC, - DES_OFB, - IDEA_OFB, - Pkcs9, - Email, - UnstructuredName, - ContentType, // 50 - MessageDigest, - SigningTime, - CounterSignature, - ChallengePassword, - UnstructuredAddress, - ExtendedCertificateAttributes, - Netscape, - NetscapeCertExtention, - NetscapeDatatype, - DES_EDE_CFB64, // 60 - DES_EDE3_CFB64, - DES_EDE_OFB64, - DES_EDE3_OFB64, - SHA1, - RSA_SHA1, - DSA_SHA, - DSA_OLD, - PBE_SHA1_RC2_64, - PBKDF2, - DSA_SHA1_OLD, // 70 - NetscapeCertType, - NetscapeBaseUrl, - NetscapeRevocationUrl, - NetscapeCARevocationUrl, - NetscapeRenewalUrl, - NetscapeCAPolicyUrl, - NetscapeSSLServerName, - NetscapeComment, - NetscapeCertSequence, - DESX_CBC, // 80 - ID_CE, - SubjectKeyIdentifier, - KeyUsage, - PrivateKeyUsagePeriod, - SubjectAltName, - IssuerAltName, - BasicConstraints, - CrlNumber, - CertificatePolicies, - AuthorityKeyIdentifier, // 90 - BF_CBC, - BF_ECB, - BF_CFB, - BF_OFB, - MDC2, - RSA_MDC2, - RC4_40, - RC2_40_CBC, - G, - S, // 100 - I, - /// uniqueIdentifier - UID, - CrlDistributionPoints, - RSA_NP_MD5, - SN, - T, - D, - CAST5_CBC, - CAST5_ECB, - CAST5_CFB, // 110 - CAST5_OFB, - PbeWithMD5AndCast5CBC, - DSA_SHA1, - MD5_SHA1, - RSA_SHA1_2, - DSA, - RIPEMD160, - // 118 missing - RSA_RIPEMD160 = 119, - RC5_CBC, // 120 - RC5_ECB, - RC5_CFB, - RC5_OFB, - RLE, - ZLIB, - ExtendedKeyUsage, - PKIX, - ID_KP, - ServerAuth, - ClientAuth, // 130 - CodeSigning, - EmailProtection, - TimeStamping, - MsCodeInd, - MsCodeCom, - MsCtlSigh, - MsSGC, - MsEFS, - NsSGC, - DeltaCRL, // 140 - CRLReason, - InvalidityDate, - SXNetID, - PBE_SHA1_RC4_128, - PBE_SHA1_RC4_40, - PBE_SHA1_3DES, - PBE_SHA1_2DES, - PBE_SHA1_RC2_128, - PBE_SHA1_RC2_40, - KeyBag, // 150 - Pkcs8ShroudedKeyBag, - CertBag, - CrlBag, - SecretBag, - SafeContentsBag, - FriendlyName, - LocalKeyID, - X509Certificate, - SdsiCertificate, - X509Crl, // 160 - PBES2, - PBMAC1, - HmacWithSha1, - ID_QT_CPS, - ID_QT_UNOTICE, - RC2_64_CBC, - SMIMECaps, - PBE_MD2_RC2_64, - PBE_MD5_RC2_64, - PBE_SHA1_DES, - MicrosoftExtensionRequest, - ExtensionRequest, - Name, - DnQualifier, - IdPe, - IdAd, - AuthorityInfoAccess, - OCSP, - CaIssuers, - OCSPSigning, // 180 +use ffi; +use libc::c_int; - // 181 and up are from openssl's obj_mac.h - /// Shown as UID in cert subject - UserId = 458, +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub struct Nid(c_int); - SHA256 = 672, - SHA384, - SHA512, - SHA224, -} +#[allow(non_snake_case)] +impl Nid { + pub fn from_raw(raw: c_int) -> Nid { + Nid(raw) + } + + pub fn as_raw(&self) -> c_int { + self.0 + } + + pub fn undef() -> Nid { + Nid(ffi::NID_undef) + } + + pub fn itu_t() -> Nid { + Nid(ffi::NID_itu_t) + } + + pub fn ccitt() -> Nid { + Nid(ffi::NID_ccitt) + } + + pub fn iso() -> Nid { + Nid(ffi::NID_iso) + } + + pub fn joint_iso_itu_t() -> Nid { + Nid(ffi::NID_joint_iso_itu_t) + } + + pub fn joint_iso_ccitt() -> Nid { + Nid(ffi::NID_joint_iso_ccitt) + } + + pub fn member_body() -> Nid { + Nid(ffi::NID_member_body) + } + + pub fn identified_organization() -> Nid { + Nid(ffi::NID_identified_organization) + } + + pub fn hmac_md5() -> Nid { + Nid(ffi::NID_hmac_md5) + } + + pub fn hmac_sha1() -> Nid { + Nid(ffi::NID_hmac_sha1) + } + + pub fn certicom_arc() -> Nid { + Nid(ffi::NID_certicom_arc) + } + + pub fn international_organizations() -> Nid { + Nid(ffi::NID_international_organizations) + } + + pub fn wap() -> Nid { + Nid(ffi::NID_wap) + } + + pub fn wap_wsg() -> Nid { + Nid(ffi::NID_wap_wsg) + } + + pub fn selected_attribute_types() -> Nid { + Nid(ffi::NID_selected_attribute_types) + } + + pub fn clearance() -> Nid { + Nid(ffi::NID_clearance) + } + + pub fn ISO_US() -> Nid { + Nid(ffi::NID_ISO_US) + } + + pub fn X9_57() -> Nid { + Nid(ffi::NID_X9_57) + } + + pub fn X9cm() -> Nid { + Nid(ffi::NID_X9cm) + } + + pub fn dsa() -> Nid { + Nid(ffi::NID_dsa) + } + + pub fn dsaWithSHA1() -> Nid { + Nid(ffi::NID_dsaWithSHA1) + } + + pub fn ansi_X9_62() -> Nid { + Nid(ffi::NID_ansi_X9_62) + } + + pub fn X9_62_prime_field() -> Nid { + Nid(ffi::NID_X9_62_prime_field) + } + + pub fn X9_62_characteristic_two_field() -> Nid { + Nid(ffi::NID_X9_62_characteristic_two_field) + } + + pub fn X9_62_id_characteristic_two_basis() -> Nid { + Nid(ffi::NID_X9_62_id_characteristic_two_basis) + } + + pub fn X9_62_onBasis() -> Nid { + Nid(ffi::NID_X9_62_onBasis) + } + + pub fn X9_62_tpBasis() -> Nid { + Nid(ffi::NID_X9_62_tpBasis) + } + + pub fn X9_62_ppBasis() -> Nid { + Nid(ffi::NID_X9_62_ppBasis) + } + + pub fn X9_62_id_ecPublicKey() -> Nid { + Nid(ffi::NID_X9_62_id_ecPublicKey) + } + + pub fn X9_62_c2pnb163v1() -> Nid { + Nid(ffi::NID_X9_62_c2pnb163v1) + } + + pub fn X9_62_c2pnb163v2() -> Nid { + Nid(ffi::NID_X9_62_c2pnb163v2) + } + + pub fn X9_62_c2pnb163v3() -> Nid { + Nid(ffi::NID_X9_62_c2pnb163v3) + } + + pub fn X9_62_c2pnb176v1() -> Nid { + Nid(ffi::NID_X9_62_c2pnb176v1) + } + + pub fn X9_62_c2tnb191v1() -> Nid { + Nid(ffi::NID_X9_62_c2tnb191v1) + } + + pub fn X9_62_c2tnb191v2() -> Nid { + Nid(ffi::NID_X9_62_c2tnb191v2) + } + + pub fn X9_62_c2tnb191v3() -> Nid { + Nid(ffi::NID_X9_62_c2tnb191v3) + } + + pub fn X9_62_c2onb191v4() -> Nid { + Nid(ffi::NID_X9_62_c2onb191v4) + } + + pub fn X9_62_c2onb191v5() -> Nid { + Nid(ffi::NID_X9_62_c2onb191v5) + } + + pub fn X9_62_c2pnb208w1() -> Nid { + Nid(ffi::NID_X9_62_c2pnb208w1) + } + + pub fn X9_62_c2tnb239v1() -> Nid { + Nid(ffi::NID_X9_62_c2tnb239v1) + } + + pub fn X9_62_c2tnb239v2() -> Nid { + Nid(ffi::NID_X9_62_c2tnb239v2) + } + + pub fn X9_62_c2tnb239v3() -> Nid { + Nid(ffi::NID_X9_62_c2tnb239v3) + } + + pub fn X9_62_c2onb239v4() -> Nid { + Nid(ffi::NID_X9_62_c2onb239v4) + } + + pub fn X9_62_c2onb239v5() -> Nid { + Nid(ffi::NID_X9_62_c2onb239v5) + } + + pub fn X9_62_c2pnb272w1() -> Nid { + Nid(ffi::NID_X9_62_c2pnb272w1) + } + + pub fn X9_62_c2pnb304w1() -> Nid { + Nid(ffi::NID_X9_62_c2pnb304w1) + } + + pub fn X9_62_c2tnb359v1() -> Nid { + Nid(ffi::NID_X9_62_c2tnb359v1) + } + + pub fn X9_62_c2pnb368w1() -> Nid { + Nid(ffi::NID_X9_62_c2pnb368w1) + } + + pub fn X9_62_c2tnb431r1() -> Nid { + Nid(ffi::NID_X9_62_c2tnb431r1) + } + + pub fn X9_62_prime192v1() -> Nid { + Nid(ffi::NID_X9_62_prime192v1) + } + + pub fn X9_62_prime192v2() -> Nid { + Nid(ffi::NID_X9_62_prime192v2) + } + + pub fn X9_62_prime192v3() -> Nid { + Nid(ffi::NID_X9_62_prime192v3) + } + + pub fn X9_62_prime239v1() -> Nid { + Nid(ffi::NID_X9_62_prime239v1) + } + + pub fn X9_62_prime239v2() -> Nid { + Nid(ffi::NID_X9_62_prime239v2) + } + + pub fn X9_62_prime239v3() -> Nid { + Nid(ffi::NID_X9_62_prime239v3) + } + + pub fn X9_62_prime256v1() -> Nid { + Nid(ffi::NID_X9_62_prime256v1) + } + + pub fn ecdsa_with_SHA1() -> Nid { + Nid(ffi::NID_ecdsa_with_SHA1) + } + + pub fn ecdsa_with_Recommended() -> Nid { + Nid(ffi::NID_ecdsa_with_Recommended) + } + + pub fn ecdsa_with_Specified() -> Nid { + Nid(ffi::NID_ecdsa_with_Specified) + } + + pub fn ecdsa_with_SHA224() -> Nid { + Nid(ffi::NID_ecdsa_with_SHA224) + } + + pub fn ecdsa_with_SHA256() -> Nid { + Nid(ffi::NID_ecdsa_with_SHA256) + } + + pub fn ecdsa_with_SHA384() -> Nid { + Nid(ffi::NID_ecdsa_with_SHA384) + } + + pub fn ecdsa_with_SHA512() -> Nid { + Nid(ffi::NID_ecdsa_with_SHA512) + } + + pub fn secp112r1() -> Nid { + Nid(ffi::NID_secp112r1) + } + + pub fn secp112r2() -> Nid { + Nid(ffi::NID_secp112r2) + } + + pub fn secp128r1() -> Nid { + Nid(ffi::NID_secp128r1) + } + + pub fn secp128r2() -> Nid { + Nid(ffi::NID_secp128r2) + } + + pub fn secp160k1() -> Nid { + Nid(ffi::NID_secp160k1) + } + + pub fn secp160r1() -> Nid { + Nid(ffi::NID_secp160r1) + } + + pub fn secp160r2() -> Nid { + Nid(ffi::NID_secp160r2) + } + + pub fn secp192k1() -> Nid { + Nid(ffi::NID_secp192k1) + } + + pub fn secp224k1() -> Nid { + Nid(ffi::NID_secp224k1) + } + + pub fn secp224r1() -> Nid { + Nid(ffi::NID_secp224r1) + } + + pub fn secp256k1() -> Nid { + Nid(ffi::NID_secp256k1) + } + + pub fn secp384r1() -> Nid { + Nid(ffi::NID_secp384r1) + } + + pub fn secp521r1() -> Nid { + Nid(ffi::NID_secp521r1) + } + + pub fn sect113r1() -> Nid { + Nid(ffi::NID_sect113r1) + } + + pub fn sect113r2() -> Nid { + Nid(ffi::NID_sect113r2) + } + + pub fn sect131r1() -> Nid { + Nid(ffi::NID_sect131r1) + } + + pub fn sect131r2() -> Nid { + Nid(ffi::NID_sect131r2) + } + + pub fn sect163k1() -> Nid { + Nid(ffi::NID_sect163k1) + } + + pub fn sect163r1() -> Nid { + Nid(ffi::NID_sect163r1) + } + + pub fn sect163r2() -> Nid { + Nid(ffi::NID_sect163r2) + } + + pub fn sect193r1() -> Nid { + Nid(ffi::NID_sect193r1) + } + + pub fn sect193r2() -> Nid { + Nid(ffi::NID_sect193r2) + } + + pub fn sect233k1() -> Nid { + Nid(ffi::NID_sect233k1) + } + + pub fn sect233r1() -> Nid { + Nid(ffi::NID_sect233r1) + } + + pub fn sect239k1() -> Nid { + Nid(ffi::NID_sect239k1) + } + + pub fn sect283k1() -> Nid { + Nid(ffi::NID_sect283k1) + } + + pub fn sect283r1() -> Nid { + Nid(ffi::NID_sect283r1) + } + + pub fn sect409k1() -> Nid { + Nid(ffi::NID_sect409k1) + } + + pub fn sect409r1() -> Nid { + Nid(ffi::NID_sect409r1) + } + + pub fn sect571k1() -> Nid { + Nid(ffi::NID_sect571k1) + } + + pub fn sect571r1() -> Nid { + Nid(ffi::NID_sect571r1) + } + + pub fn wap_wsg_idm_ecid_wtls1() -> Nid { + Nid(ffi::NID_wap_wsg_idm_ecid_wtls1) + } + + pub fn wap_wsg_idm_ecid_wtls3() -> Nid { + Nid(ffi::NID_wap_wsg_idm_ecid_wtls3) + } + + pub fn wap_wsg_idm_ecid_wtls4() -> Nid { + Nid(ffi::NID_wap_wsg_idm_ecid_wtls4) + } + + pub fn wap_wsg_idm_ecid_wtls5() -> Nid { + Nid(ffi::NID_wap_wsg_idm_ecid_wtls5) + } + + pub fn wap_wsg_idm_ecid_wtls6() -> Nid { + Nid(ffi::NID_wap_wsg_idm_ecid_wtls6) + } + + pub fn wap_wsg_idm_ecid_wtls7() -> Nid { + Nid(ffi::NID_wap_wsg_idm_ecid_wtls7) + } + + pub fn wap_wsg_idm_ecid_wtls8() -> Nid { + Nid(ffi::NID_wap_wsg_idm_ecid_wtls8) + } + + pub fn wap_wsg_idm_ecid_wtls9() -> Nid { + Nid(ffi::NID_wap_wsg_idm_ecid_wtls9) + } + + pub fn wap_wsg_idm_ecid_wtls10() -> Nid { + Nid(ffi::NID_wap_wsg_idm_ecid_wtls10) + } + + pub fn wap_wsg_idm_ecid_wtls11() -> Nid { + Nid(ffi::NID_wap_wsg_idm_ecid_wtls11) + } + + pub fn wap_wsg_idm_ecid_wtls12() -> Nid { + Nid(ffi::NID_wap_wsg_idm_ecid_wtls12) + } + + pub fn cast5_cbc() -> Nid { + Nid(ffi::NID_cast5_cbc) + } + + pub fn cast5_ecb() -> Nid { + Nid(ffi::NID_cast5_ecb) + } + + pub fn cast5_cfb64() -> Nid { + Nid(ffi::NID_cast5_cfb64) + } + + pub fn cast5_ofb64() -> Nid { + Nid(ffi::NID_cast5_ofb64) + } + + pub fn pbeWithMD5AndCast5_CBC() -> Nid { + Nid(ffi::NID_pbeWithMD5AndCast5_CBC) + } + + pub fn id_PasswordBasedMAC() -> Nid { + Nid(ffi::NID_id_PasswordBasedMAC) + } + + pub fn id_DHBasedMac() -> Nid { + Nid(ffi::NID_id_DHBasedMac) + } + + pub fn rsadsi() -> Nid { + Nid(ffi::NID_rsadsi) + } + + pub fn pkcs() -> Nid { + Nid(ffi::NID_pkcs) + } + + pub fn pkcs1() -> Nid { + Nid(ffi::NID_pkcs1) + } + + pub fn rsaEncryption() -> Nid { + Nid(ffi::NID_rsaEncryption) + } + + pub fn md2WithRSAEncryption() -> Nid { + Nid(ffi::NID_md2WithRSAEncryption) + } + + pub fn md4WithRSAEncryption() -> Nid { + Nid(ffi::NID_md4WithRSAEncryption) + } + + pub fn md5WithRSAEncryption() -> Nid { + Nid(ffi::NID_md5WithRSAEncryption) + } + + pub fn sha1WithRSAEncryption() -> Nid { + Nid(ffi::NID_sha1WithRSAEncryption) + } + + pub fn rsaesOaep() -> Nid { + Nid(ffi::NID_rsaesOaep) + } + + pub fn mgf1() -> Nid { + Nid(ffi::NID_mgf1) + } + + pub fn pSpecified() -> Nid { + Nid(ffi::NID_pSpecified) + } + + pub fn rsassaPss() -> Nid { + Nid(ffi::NID_rsassaPss) + } + + pub fn sha256WithRSAEncryption() -> Nid { + Nid(ffi::NID_sha256WithRSAEncryption) + } + + pub fn sha384WithRSAEncryption() -> Nid { + Nid(ffi::NID_sha384WithRSAEncryption) + } + + pub fn sha512WithRSAEncryption() -> Nid { + Nid(ffi::NID_sha512WithRSAEncryption) + } + + pub fn sha224WithRSAEncryption() -> Nid { + Nid(ffi::NID_sha224WithRSAEncryption) + } + + pub fn pkcs3() -> Nid { + Nid(ffi::NID_pkcs3) + } + + pub fn dhKeyAgreement() -> Nid { + Nid(ffi::NID_dhKeyAgreement) + } + + pub fn pkcs5() -> Nid { + Nid(ffi::NID_pkcs5) + } + + pub fn pbeWithMD2AndDES_CBC() -> Nid { + Nid(ffi::NID_pbeWithMD2AndDES_CBC) + } + + pub fn pbeWithMD5AndDES_CBC() -> Nid { + Nid(ffi::NID_pbeWithMD5AndDES_CBC) + } + + pub fn pbeWithMD2AndRC2_CBC() -> Nid { + Nid(ffi::NID_pbeWithMD2AndRC2_CBC) + } + + pub fn pbeWithMD5AndRC2_CBC() -> Nid { + Nid(ffi::NID_pbeWithMD5AndRC2_CBC) + } + + pub fn pbeWithSHA1AndDES_CBC() -> Nid { + Nid(ffi::NID_pbeWithSHA1AndDES_CBC) + } + + pub fn pbeWithSHA1AndRC2_CBC() -> Nid { + Nid(ffi::NID_pbeWithSHA1AndRC2_CBC) + } + + pub fn id_pbkdf2() -> Nid { + Nid(ffi::NID_id_pbkdf2) + } + + pub fn pbes2() -> Nid { + Nid(ffi::NID_pbes2) + } + + pub fn pbmac1() -> Nid { + Nid(ffi::NID_pbmac1) + } + + pub fn pkcs7() -> Nid { + Nid(ffi::NID_pkcs7) + } + + pub fn pkcs7_data() -> Nid { + Nid(ffi::NID_pkcs7_data) + } + + pub fn pkcs7_signed() -> Nid { + Nid(ffi::NID_pkcs7_signed) + } + + pub fn pkcs7_enveloped() -> Nid { + Nid(ffi::NID_pkcs7_enveloped) + } + + pub fn pkcs7_signedAndEnveloped() -> Nid { + Nid(ffi::NID_pkcs7_signedAndEnveloped) + } + + pub fn pkcs7_digest() -> Nid { + Nid(ffi::NID_pkcs7_digest) + } + + pub fn pkcs7_encrypted() -> Nid { + Nid(ffi::NID_pkcs7_encrypted) + } + + pub fn pkcs9() -> Nid { + Nid(ffi::NID_pkcs9) + } + + pub fn pkcs9_emailAddress() -> Nid { + Nid(ffi::NID_pkcs9_emailAddress) + } + + pub fn pkcs9_unstructuredName() -> Nid { + Nid(ffi::NID_pkcs9_unstructuredName) + } + + pub fn pkcs9_contentType() -> Nid { + Nid(ffi::NID_pkcs9_contentType) + } + + pub fn pkcs9_messageDigest() -> Nid { + Nid(ffi::NID_pkcs9_messageDigest) + } + + pub fn pkcs9_signingTime() -> Nid { + Nid(ffi::NID_pkcs9_signingTime) + } + + pub fn pkcs9_countersignature() -> Nid { + Nid(ffi::NID_pkcs9_countersignature) + } + + pub fn pkcs9_challengePassword() -> Nid { + Nid(ffi::NID_pkcs9_challengePassword) + } + + pub fn pkcs9_unstructuredAddress() -> Nid { + Nid(ffi::NID_pkcs9_unstructuredAddress) + } + + pub fn pkcs9_extCertAttributes() -> Nid { + Nid(ffi::NID_pkcs9_extCertAttributes) + } + + pub fn ext_req() -> Nid { + Nid(ffi::NID_ext_req) + } + + pub fn SMIMECapabilities() -> Nid { + Nid(ffi::NID_SMIMECapabilities) + } + + pub fn SMIME() -> Nid { + Nid(ffi::NID_SMIME) + } + + pub fn id_smime_mod() -> Nid { + Nid(ffi::NID_id_smime_mod) + } + + pub fn id_smime_ct() -> Nid { + Nid(ffi::NID_id_smime_ct) + } + + pub fn id_smime_aa() -> Nid { + Nid(ffi::NID_id_smime_aa) + } + + pub fn id_smime_alg() -> Nid { + Nid(ffi::NID_id_smime_alg) + } + + pub fn id_smime_cd() -> Nid { + Nid(ffi::NID_id_smime_cd) + } + + pub fn id_smime_spq() -> Nid { + Nid(ffi::NID_id_smime_spq) + } + + pub fn id_smime_cti() -> Nid { + Nid(ffi::NID_id_smime_cti) + } + + pub fn id_smime_mod_cms() -> Nid { + Nid(ffi::NID_id_smime_mod_cms) + } + + pub fn id_smime_mod_ess() -> Nid { + Nid(ffi::NID_id_smime_mod_ess) + } + + pub fn id_smime_mod_oid() -> Nid { + Nid(ffi::NID_id_smime_mod_oid) + } + + pub fn id_smime_mod_msg_v3() -> Nid { + Nid(ffi::NID_id_smime_mod_msg_v3) + } + + pub fn id_smime_mod_ets_eSignature_88() -> Nid { + Nid(ffi::NID_id_smime_mod_ets_eSignature_88) + } + + pub fn id_smime_mod_ets_eSignature_97() -> Nid { + Nid(ffi::NID_id_smime_mod_ets_eSignature_97) + } + + pub fn id_smime_mod_ets_eSigPolicy_88() -> Nid { + Nid(ffi::NID_id_smime_mod_ets_eSigPolicy_88) + } + + pub fn id_smime_mod_ets_eSigPolicy_97() -> Nid { + Nid(ffi::NID_id_smime_mod_ets_eSigPolicy_97) + } + + pub fn id_smime_ct_receipt() -> Nid { + Nid(ffi::NID_id_smime_ct_receipt) + } + + pub fn id_smime_ct_authData() -> Nid { + Nid(ffi::NID_id_smime_ct_authData) + } + + pub fn id_smime_ct_publishCert() -> Nid { + Nid(ffi::NID_id_smime_ct_publishCert) + } + + pub fn id_smime_ct_TSTInfo() -> Nid { + Nid(ffi::NID_id_smime_ct_TSTInfo) + } + + pub fn id_smime_ct_TDTInfo() -> Nid { + Nid(ffi::NID_id_smime_ct_TDTInfo) + } + + pub fn id_smime_ct_contentInfo() -> Nid { + Nid(ffi::NID_id_smime_ct_contentInfo) + } + + pub fn id_smime_ct_DVCSRequestData() -> Nid { + Nid(ffi::NID_id_smime_ct_DVCSRequestData) + } + + pub fn id_smime_ct_DVCSResponseData() -> Nid { + Nid(ffi::NID_id_smime_ct_DVCSResponseData) + } + + pub fn id_smime_ct_compressedData() -> Nid { + Nid(ffi::NID_id_smime_ct_compressedData) + } + + pub fn id_ct_asciiTextWithCRLF() -> Nid { + Nid(ffi::NID_id_ct_asciiTextWithCRLF) + } + + pub fn id_smime_aa_receiptRequest() -> Nid { + Nid(ffi::NID_id_smime_aa_receiptRequest) + } + + pub fn id_smime_aa_securityLabel() -> Nid { + Nid(ffi::NID_id_smime_aa_securityLabel) + } + + pub fn id_smime_aa_mlExpandHistory() -> Nid { + Nid(ffi::NID_id_smime_aa_mlExpandHistory) + } + + pub fn id_smime_aa_contentHint() -> Nid { + Nid(ffi::NID_id_smime_aa_contentHint) + } + + pub fn id_smime_aa_msgSigDigest() -> Nid { + Nid(ffi::NID_id_smime_aa_msgSigDigest) + } + + pub fn id_smime_aa_encapContentType() -> Nid { + Nid(ffi::NID_id_smime_aa_encapContentType) + } + + pub fn id_smime_aa_contentIdentifier() -> Nid { + Nid(ffi::NID_id_smime_aa_contentIdentifier) + } + + pub fn id_smime_aa_macValue() -> Nid { + Nid(ffi::NID_id_smime_aa_macValue) + } + + pub fn id_smime_aa_equivalentLabels() -> Nid { + Nid(ffi::NID_id_smime_aa_equivalentLabels) + } + + pub fn id_smime_aa_contentReference() -> Nid { + Nid(ffi::NID_id_smime_aa_contentReference) + } + + pub fn id_smime_aa_encrypKeyPref() -> Nid { + Nid(ffi::NID_id_smime_aa_encrypKeyPref) + } + + pub fn id_smime_aa_signingCertificate() -> Nid { + Nid(ffi::NID_id_smime_aa_signingCertificate) + } + + pub fn id_smime_aa_smimeEncryptCerts() -> Nid { + Nid(ffi::NID_id_smime_aa_smimeEncryptCerts) + } + + pub fn id_smime_aa_timeStampToken() -> Nid { + Nid(ffi::NID_id_smime_aa_timeStampToken) + } + + pub fn id_smime_aa_ets_sigPolicyId() -> Nid { + Nid(ffi::NID_id_smime_aa_ets_sigPolicyId) + } + + pub fn id_smime_aa_ets_commitmentType() -> Nid { + Nid(ffi::NID_id_smime_aa_ets_commitmentType) + } + + pub fn id_smime_aa_ets_signerLocation() -> Nid { + Nid(ffi::NID_id_smime_aa_ets_signerLocation) + } + + pub fn id_smime_aa_ets_signerAttr() -> Nid { + Nid(ffi::NID_id_smime_aa_ets_signerAttr) + } + + pub fn id_smime_aa_ets_otherSigCert() -> Nid { + Nid(ffi::NID_id_smime_aa_ets_otherSigCert) + } + + pub fn id_smime_aa_ets_contentTimestamp() -> Nid { + Nid(ffi::NID_id_smime_aa_ets_contentTimestamp) + } + + pub fn id_smime_aa_ets_CertificateRefs() -> Nid { + Nid(ffi::NID_id_smime_aa_ets_CertificateRefs) + } + + pub fn id_smime_aa_ets_RevocationRefs() -> Nid { + Nid(ffi::NID_id_smime_aa_ets_RevocationRefs) + } + + pub fn id_smime_aa_ets_certValues() -> Nid { + Nid(ffi::NID_id_smime_aa_ets_certValues) + } + + pub fn id_smime_aa_ets_revocationValues() -> Nid { + Nid(ffi::NID_id_smime_aa_ets_revocationValues) + } + + pub fn id_smime_aa_ets_escTimeStamp() -> Nid { + Nid(ffi::NID_id_smime_aa_ets_escTimeStamp) + } + + pub fn id_smime_aa_ets_certCRLTimestamp() -> Nid { + Nid(ffi::NID_id_smime_aa_ets_certCRLTimestamp) + } + + pub fn id_smime_aa_ets_archiveTimeStamp() -> Nid { + Nid(ffi::NID_id_smime_aa_ets_archiveTimeStamp) + } + + pub fn id_smime_aa_signatureType() -> Nid { + Nid(ffi::NID_id_smime_aa_signatureType) + } + + pub fn id_smime_aa_dvcs_dvc() -> Nid { + Nid(ffi::NID_id_smime_aa_dvcs_dvc) + } + + pub fn id_smime_alg_ESDHwith3DES() -> Nid { + Nid(ffi::NID_id_smime_alg_ESDHwith3DES) + } + + pub fn id_smime_alg_ESDHwithRC2() -> Nid { + Nid(ffi::NID_id_smime_alg_ESDHwithRC2) + } + + pub fn id_smime_alg_3DESwrap() -> Nid { + Nid(ffi::NID_id_smime_alg_3DESwrap) + } + + pub fn id_smime_alg_RC2wrap() -> Nid { + Nid(ffi::NID_id_smime_alg_RC2wrap) + } + + pub fn id_smime_alg_ESDH() -> Nid { + Nid(ffi::NID_id_smime_alg_ESDH) + } + + pub fn id_smime_alg_CMS3DESwrap() -> Nid { + Nid(ffi::NID_id_smime_alg_CMS3DESwrap) + } + + pub fn id_smime_alg_CMSRC2wrap() -> Nid { + Nid(ffi::NID_id_smime_alg_CMSRC2wrap) + } + + pub fn id_alg_PWRI_KEK() -> Nid { + Nid(ffi::NID_id_alg_PWRI_KEK) + } + + pub fn id_smime_cd_ldap() -> Nid { + Nid(ffi::NID_id_smime_cd_ldap) + } + + pub fn id_smime_spq_ets_sqt_uri() -> Nid { + Nid(ffi::NID_id_smime_spq_ets_sqt_uri) + } + + pub fn id_smime_spq_ets_sqt_unotice() -> Nid { + Nid(ffi::NID_id_smime_spq_ets_sqt_unotice) + } + + pub fn id_smime_cti_ets_proofOfOrigin() -> Nid { + Nid(ffi::NID_id_smime_cti_ets_proofOfOrigin) + } + + pub fn id_smime_cti_ets_proofOfReceipt() -> Nid { + Nid(ffi::NID_id_smime_cti_ets_proofOfReceipt) + } + + pub fn id_smime_cti_ets_proofOfDelivery() -> Nid { + Nid(ffi::NID_id_smime_cti_ets_proofOfDelivery) + } + + pub fn id_smime_cti_ets_proofOfSender() -> Nid { + Nid(ffi::NID_id_smime_cti_ets_proofOfSender) + } + + pub fn id_smime_cti_ets_proofOfApproval() -> Nid { + Nid(ffi::NID_id_smime_cti_ets_proofOfApproval) + } + + pub fn id_smime_cti_ets_proofOfCreation() -> Nid { + Nid(ffi::NID_id_smime_cti_ets_proofOfCreation) + } + + pub fn friendlyName() -> Nid { + Nid(ffi::NID_friendlyName) + } + + pub fn localKeyID() -> Nid { + Nid(ffi::NID_localKeyID) + } + + pub fn ms_csp_name() -> Nid { + Nid(ffi::NID_ms_csp_name) + } + + pub fn LocalKeySet() -> Nid { + Nid(ffi::NID_LocalKeySet) + } + + pub fn x509Certificate() -> Nid { + Nid(ffi::NID_x509Certificate) + } + + pub fn sdsiCertificate() -> Nid { + Nid(ffi::NID_sdsiCertificate) + } + + pub fn x509Crl() -> Nid { + Nid(ffi::NID_x509Crl) + } + + pub fn pbe_WithSHA1And128BitRC4() -> Nid { + Nid(ffi::NID_pbe_WithSHA1And128BitRC4) + } + + pub fn pbe_WithSHA1And40BitRC4() -> Nid { + Nid(ffi::NID_pbe_WithSHA1And40BitRC4) + } + + pub fn pbe_WithSHA1And3_Key_TripleDES_CBC() -> Nid { + Nid(ffi::NID_pbe_WithSHA1And3_Key_TripleDES_CBC) + } + + pub fn pbe_WithSHA1And2_Key_TripleDES_CBC() -> Nid { + Nid(ffi::NID_pbe_WithSHA1And2_Key_TripleDES_CBC) + } + + pub fn pbe_WithSHA1And128BitRC2_CBC() -> Nid { + Nid(ffi::NID_pbe_WithSHA1And128BitRC2_CBC) + } + + pub fn pbe_WithSHA1And40BitRC2_CBC() -> Nid { + Nid(ffi::NID_pbe_WithSHA1And40BitRC2_CBC) + } + + pub fn keyBag() -> Nid { + Nid(ffi::NID_keyBag) + } + + pub fn pkcs8ShroudedKeyBag() -> Nid { + Nid(ffi::NID_pkcs8ShroudedKeyBag) + } + + pub fn certBag() -> Nid { + Nid(ffi::NID_certBag) + } + + pub fn crlBag() -> Nid { + Nid(ffi::NID_crlBag) + } + + pub fn secretBag() -> Nid { + Nid(ffi::NID_secretBag) + } + + pub fn safeContentsBag() -> Nid { + Nid(ffi::NID_safeContentsBag) + } + + pub fn md2() -> Nid { + Nid(ffi::NID_md2) + } + + pub fn md4() -> Nid { + Nid(ffi::NID_md4) + } + + pub fn md5() -> Nid { + Nid(ffi::NID_md5) + } + + pub fn md5_sha1() -> Nid { + Nid(ffi::NID_md5_sha1) + } + + pub fn hmacWithMD5() -> Nid { + Nid(ffi::NID_hmacWithMD5) + } + + pub fn hmacWithSHA1() -> Nid { + Nid(ffi::NID_hmacWithSHA1) + } + + pub fn hmacWithSHA224() -> Nid { + Nid(ffi::NID_hmacWithSHA224) + } + + pub fn hmacWithSHA256() -> Nid { + Nid(ffi::NID_hmacWithSHA256) + } + + pub fn hmacWithSHA384() -> Nid { + Nid(ffi::NID_hmacWithSHA384) + } + + pub fn hmacWithSHA512() -> Nid { + Nid(ffi::NID_hmacWithSHA512) + } + + pub fn rc2_cbc() -> Nid { + Nid(ffi::NID_rc2_cbc) + } + + pub fn rc2_ecb() -> Nid { + Nid(ffi::NID_rc2_ecb) + } + + pub fn rc2_cfb64() -> Nid { + Nid(ffi::NID_rc2_cfb64) + } + + pub fn rc2_ofb64() -> Nid { + Nid(ffi::NID_rc2_ofb64) + } + + pub fn rc2_40_cbc() -> Nid { + Nid(ffi::NID_rc2_40_cbc) + } + + pub fn rc2_64_cbc() -> Nid { + Nid(ffi::NID_rc2_64_cbc) + } + + pub fn rc4() -> Nid { + Nid(ffi::NID_rc4) + } + + pub fn rc4_40() -> Nid { + Nid(ffi::NID_rc4_40) + } + + pub fn des_ede3_cbc() -> Nid { + Nid(ffi::NID_des_ede3_cbc) + } + + pub fn rc5_cbc() -> Nid { + Nid(ffi::NID_rc5_cbc) + } + + pub fn rc5_ecb() -> Nid { + Nid(ffi::NID_rc5_ecb) + } + + pub fn rc5_cfb64() -> Nid { + Nid(ffi::NID_rc5_cfb64) + } + + pub fn rc5_ofb64() -> Nid { + Nid(ffi::NID_rc5_ofb64) + } + + pub fn ms_ext_req() -> Nid { + Nid(ffi::NID_ms_ext_req) + } + + pub fn ms_code_ind() -> Nid { + Nid(ffi::NID_ms_code_ind) + } + + pub fn ms_code_com() -> Nid { + Nid(ffi::NID_ms_code_com) + } + + pub fn ms_ctl_sign() -> Nid { + Nid(ffi::NID_ms_ctl_sign) + } + + pub fn ms_sgc() -> Nid { + Nid(ffi::NID_ms_sgc) + } + + pub fn ms_efs() -> Nid { + Nid(ffi::NID_ms_efs) + } + + pub fn ms_smartcard_login() -> Nid { + Nid(ffi::NID_ms_smartcard_login) + } + + pub fn ms_upn() -> Nid { + Nid(ffi::NID_ms_upn) + } + + pub fn idea_cbc() -> Nid { + Nid(ffi::NID_idea_cbc) + } + + pub fn idea_ecb() -> Nid { + Nid(ffi::NID_idea_ecb) + } + + pub fn idea_cfb64() -> Nid { + Nid(ffi::NID_idea_cfb64) + } + + pub fn idea_ofb64() -> Nid { + Nid(ffi::NID_idea_ofb64) + } + + pub fn bf_cbc() -> Nid { + Nid(ffi::NID_bf_cbc) + } + + pub fn bf_ecb() -> Nid { + Nid(ffi::NID_bf_ecb) + } + + pub fn bf_cfb64() -> Nid { + Nid(ffi::NID_bf_cfb64) + } + + pub fn bf_ofb64() -> Nid { + Nid(ffi::NID_bf_ofb64) + } + + pub fn id_pkix() -> Nid { + Nid(ffi::NID_id_pkix) + } + + pub fn id_pkix_mod() -> Nid { + Nid(ffi::NID_id_pkix_mod) + } + + pub fn id_pe() -> Nid { + Nid(ffi::NID_id_pe) + } + + pub fn id_qt() -> Nid { + Nid(ffi::NID_id_qt) + } + + pub fn id_kp() -> Nid { + Nid(ffi::NID_id_kp) + } + + pub fn id_it() -> Nid { + Nid(ffi::NID_id_it) + } + + pub fn id_pkip() -> Nid { + Nid(ffi::NID_id_pkip) + } + + pub fn id_alg() -> Nid { + Nid(ffi::NID_id_alg) + } + + pub fn id_cmc() -> Nid { + Nid(ffi::NID_id_cmc) + } + + pub fn id_on() -> Nid { + Nid(ffi::NID_id_on) + } + + pub fn id_pda() -> Nid { + Nid(ffi::NID_id_pda) + } + + pub fn id_aca() -> Nid { + Nid(ffi::NID_id_aca) + } + + pub fn id_qcs() -> Nid { + Nid(ffi::NID_id_qcs) + } + + pub fn id_cct() -> Nid { + Nid(ffi::NID_id_cct) + } + + pub fn id_ppl() -> Nid { + Nid(ffi::NID_id_ppl) + } + + pub fn id_ad() -> Nid { + Nid(ffi::NID_id_ad) + } + + pub fn id_pkix1_explicit_88() -> Nid { + Nid(ffi::NID_id_pkix1_explicit_88) + } + + pub fn id_pkix1_implicit_88() -> Nid { + Nid(ffi::NID_id_pkix1_implicit_88) + } + + pub fn id_pkix1_explicit_93() -> Nid { + Nid(ffi::NID_id_pkix1_explicit_93) + } + + pub fn id_pkix1_implicit_93() -> Nid { + Nid(ffi::NID_id_pkix1_implicit_93) + } + + pub fn id_mod_crmf() -> Nid { + Nid(ffi::NID_id_mod_crmf) + } + + pub fn id_mod_cmc() -> Nid { + Nid(ffi::NID_id_mod_cmc) + } + + pub fn id_mod_kea_profile_88() -> Nid { + Nid(ffi::NID_id_mod_kea_profile_88) + } + + pub fn id_mod_kea_profile_93() -> Nid { + Nid(ffi::NID_id_mod_kea_profile_93) + } + + pub fn id_mod_cmp() -> Nid { + Nid(ffi::NID_id_mod_cmp) + } + + pub fn id_mod_qualified_cert_88() -> Nid { + Nid(ffi::NID_id_mod_qualified_cert_88) + } + + pub fn id_mod_qualified_cert_93() -> Nid { + Nid(ffi::NID_id_mod_qualified_cert_93) + } + + pub fn id_mod_attribute_cert() -> Nid { + Nid(ffi::NID_id_mod_attribute_cert) + } + + pub fn id_mod_timestamp_protocol() -> Nid { + Nid(ffi::NID_id_mod_timestamp_protocol) + } + + pub fn id_mod_ocsp() -> Nid { + Nid(ffi::NID_id_mod_ocsp) + } + + pub fn id_mod_dvcs() -> Nid { + Nid(ffi::NID_id_mod_dvcs) + } + + pub fn id_mod_cmp2000() -> Nid { + Nid(ffi::NID_id_mod_cmp2000) + } + + pub fn info_access() -> Nid { + Nid(ffi::NID_info_access) + } + + pub fn biometricInfo() -> Nid { + Nid(ffi::NID_biometricInfo) + } + + pub fn qcStatements() -> Nid { + Nid(ffi::NID_qcStatements) + } + + pub fn ac_auditEntity() -> Nid { + Nid(ffi::NID_ac_auditEntity) + } + + pub fn ac_targeting() -> Nid { + Nid(ffi::NID_ac_targeting) + } + + pub fn aaControls() -> Nid { + Nid(ffi::NID_aaControls) + } + + pub fn sbgp_ipAddrBlock() -> Nid { + Nid(ffi::NID_sbgp_ipAddrBlock) + } + + pub fn sbgp_autonomousSysNum() -> Nid { + Nid(ffi::NID_sbgp_autonomousSysNum) + } + + pub fn sbgp_routerIdentifier() -> Nid { + Nid(ffi::NID_sbgp_routerIdentifier) + } + + pub fn ac_proxying() -> Nid { + Nid(ffi::NID_ac_proxying) + } + + pub fn sinfo_access() -> Nid { + Nid(ffi::NID_sinfo_access) + } + + pub fn proxyCertInfo() -> Nid { + Nid(ffi::NID_proxyCertInfo) + } + + pub fn id_qt_cps() -> Nid { + Nid(ffi::NID_id_qt_cps) + } + + pub fn id_qt_unotice() -> Nid { + Nid(ffi::NID_id_qt_unotice) + } + + pub fn textNotice() -> Nid { + Nid(ffi::NID_textNotice) + } + + pub fn server_auth() -> Nid { + Nid(ffi::NID_server_auth) + } + + pub fn client_auth() -> Nid { + Nid(ffi::NID_client_auth) + } + + pub fn code_sign() -> Nid { + Nid(ffi::NID_code_sign) + } + + pub fn email_protect() -> Nid { + Nid(ffi::NID_email_protect) + } + + pub fn ipsecEndSystem() -> Nid { + Nid(ffi::NID_ipsecEndSystem) + } + + pub fn ipsecTunnel() -> Nid { + Nid(ffi::NID_ipsecTunnel) + } + + pub fn ipsecUser() -> Nid { + Nid(ffi::NID_ipsecUser) + } + + pub fn time_stamp() -> Nid { + Nid(ffi::NID_time_stamp) + } + + pub fn OCSP_sign() -> Nid { + Nid(ffi::NID_OCSP_sign) + } + + pub fn dvcs() -> Nid { + Nid(ffi::NID_dvcs) + } + + pub fn id_it_caProtEncCert() -> Nid { + Nid(ffi::NID_id_it_caProtEncCert) + } + + pub fn id_it_signKeyPairTypes() -> Nid { + Nid(ffi::NID_id_it_signKeyPairTypes) + } + + pub fn id_it_encKeyPairTypes() -> Nid { + Nid(ffi::NID_id_it_encKeyPairTypes) + } + + pub fn id_it_preferredSymmAlg() -> Nid { + Nid(ffi::NID_id_it_preferredSymmAlg) + } + + pub fn id_it_caKeyUpdateInfo() -> Nid { + Nid(ffi::NID_id_it_caKeyUpdateInfo) + } + + pub fn id_it_currentCRL() -> Nid { + Nid(ffi::NID_id_it_currentCRL) + } + + pub fn id_it_unsupportedOIDs() -> Nid { + Nid(ffi::NID_id_it_unsupportedOIDs) + } + + pub fn id_it_subscriptionRequest() -> Nid { + Nid(ffi::NID_id_it_subscriptionRequest) + } + + pub fn id_it_subscriptionResponse() -> Nid { + Nid(ffi::NID_id_it_subscriptionResponse) + } + + pub fn id_it_keyPairParamReq() -> Nid { + Nid(ffi::NID_id_it_keyPairParamReq) + } + + pub fn id_it_keyPairParamRep() -> Nid { + Nid(ffi::NID_id_it_keyPairParamRep) + } + + pub fn id_it_revPassphrase() -> Nid { + Nid(ffi::NID_id_it_revPassphrase) + } + + pub fn id_it_implicitConfirm() -> Nid { + Nid(ffi::NID_id_it_implicitConfirm) + } + + pub fn id_it_confirmWaitTime() -> Nid { + Nid(ffi::NID_id_it_confirmWaitTime) + } + + pub fn id_it_origPKIMessage() -> Nid { + Nid(ffi::NID_id_it_origPKIMessage) + } + + pub fn id_it_suppLangTags() -> Nid { + Nid(ffi::NID_id_it_suppLangTags) + } + + pub fn id_regCtrl() -> Nid { + Nid(ffi::NID_id_regCtrl) + } + + pub fn id_regInfo() -> Nid { + Nid(ffi::NID_id_regInfo) + } + + pub fn id_regCtrl_regToken() -> Nid { + Nid(ffi::NID_id_regCtrl_regToken) + } + + pub fn id_regCtrl_authenticator() -> Nid { + Nid(ffi::NID_id_regCtrl_authenticator) + } + + pub fn id_regCtrl_pkiPublicationInfo() -> Nid { + Nid(ffi::NID_id_regCtrl_pkiPublicationInfo) + } + + pub fn id_regCtrl_pkiArchiveOptions() -> Nid { + Nid(ffi::NID_id_regCtrl_pkiArchiveOptions) + } + + pub fn id_regCtrl_oldCertID() -> Nid { + Nid(ffi::NID_id_regCtrl_oldCertID) + } + + pub fn id_regCtrl_protocolEncrKey() -> Nid { + Nid(ffi::NID_id_regCtrl_protocolEncrKey) + } + + pub fn id_regInfo_utf8Pairs() -> Nid { + Nid(ffi::NID_id_regInfo_utf8Pairs) + } + + pub fn id_regInfo_certReq() -> Nid { + Nid(ffi::NID_id_regInfo_certReq) + } + + pub fn id_alg_des40() -> Nid { + Nid(ffi::NID_id_alg_des40) + } + + pub fn id_alg_noSignature() -> Nid { + Nid(ffi::NID_id_alg_noSignature) + } + + pub fn id_alg_dh_sig_hmac_sha1() -> Nid { + Nid(ffi::NID_id_alg_dh_sig_hmac_sha1) + } + + pub fn id_alg_dh_pop() -> Nid { + Nid(ffi::NID_id_alg_dh_pop) + } + + pub fn id_cmc_statusInfo() -> Nid { + Nid(ffi::NID_id_cmc_statusInfo) + } + + pub fn id_cmc_identification() -> Nid { + Nid(ffi::NID_id_cmc_identification) + } + + pub fn id_cmc_identityProof() -> Nid { + Nid(ffi::NID_id_cmc_identityProof) + } + + pub fn id_cmc_dataReturn() -> Nid { + Nid(ffi::NID_id_cmc_dataReturn) + } + + pub fn id_cmc_transactionId() -> Nid { + Nid(ffi::NID_id_cmc_transactionId) + } + + pub fn id_cmc_senderNonce() -> Nid { + Nid(ffi::NID_id_cmc_senderNonce) + } + + pub fn id_cmc_recipientNonce() -> Nid { + Nid(ffi::NID_id_cmc_recipientNonce) + } + + pub fn id_cmc_addExtensions() -> Nid { + Nid(ffi::NID_id_cmc_addExtensions) + } + + pub fn id_cmc_encryptedPOP() -> Nid { + Nid(ffi::NID_id_cmc_encryptedPOP) + } + + pub fn id_cmc_decryptedPOP() -> Nid { + Nid(ffi::NID_id_cmc_decryptedPOP) + } + + pub fn id_cmc_lraPOPWitness() -> Nid { + Nid(ffi::NID_id_cmc_lraPOPWitness) + } + + pub fn id_cmc_getCert() -> Nid { + Nid(ffi::NID_id_cmc_getCert) + } + + pub fn id_cmc_getCRL() -> Nid { + Nid(ffi::NID_id_cmc_getCRL) + } + + pub fn id_cmc_revokeRequest() -> Nid { + Nid(ffi::NID_id_cmc_revokeRequest) + } + + pub fn id_cmc_regInfo() -> Nid { + Nid(ffi::NID_id_cmc_regInfo) + } + + pub fn id_cmc_responseInfo() -> Nid { + Nid(ffi::NID_id_cmc_responseInfo) + } + + pub fn id_cmc_queryPending() -> Nid { + Nid(ffi::NID_id_cmc_queryPending) + } + + pub fn id_cmc_popLinkRandom() -> Nid { + Nid(ffi::NID_id_cmc_popLinkRandom) + } + + pub fn id_cmc_popLinkWitness() -> Nid { + Nid(ffi::NID_id_cmc_popLinkWitness) + } + + pub fn id_cmc_confirmCertAcceptance() -> Nid { + Nid(ffi::NID_id_cmc_confirmCertAcceptance) + } + + pub fn id_on_personalData() -> Nid { + Nid(ffi::NID_id_on_personalData) + } + + pub fn id_on_permanentIdentifier() -> Nid { + Nid(ffi::NID_id_on_permanentIdentifier) + } + + pub fn id_pda_dateOfBirth() -> Nid { + Nid(ffi::NID_id_pda_dateOfBirth) + } + + pub fn id_pda_placeOfBirth() -> Nid { + Nid(ffi::NID_id_pda_placeOfBirth) + } + + pub fn id_pda_gender() -> Nid { + Nid(ffi::NID_id_pda_gender) + } + + pub fn id_pda_countryOfCitizenship() -> Nid { + Nid(ffi::NID_id_pda_countryOfCitizenship) + } + + pub fn id_pda_countryOfResidence() -> Nid { + Nid(ffi::NID_id_pda_countryOfResidence) + } + + pub fn id_aca_authenticationInfo() -> Nid { + Nid(ffi::NID_id_aca_authenticationInfo) + } + + pub fn id_aca_accessIdentity() -> Nid { + Nid(ffi::NID_id_aca_accessIdentity) + } + + pub fn id_aca_chargingIdentity() -> Nid { + Nid(ffi::NID_id_aca_chargingIdentity) + } + + pub fn id_aca_group() -> Nid { + Nid(ffi::NID_id_aca_group) + } + + pub fn id_aca_role() -> Nid { + Nid(ffi::NID_id_aca_role) + } + + pub fn id_aca_encAttrs() -> Nid { + Nid(ffi::NID_id_aca_encAttrs) + } + + pub fn id_qcs_pkixQCSyntax_v1() -> Nid { + Nid(ffi::NID_id_qcs_pkixQCSyntax_v1) + } + + pub fn id_cct_crs() -> Nid { + Nid(ffi::NID_id_cct_crs) + } + + pub fn id_cct_PKIData() -> Nid { + Nid(ffi::NID_id_cct_PKIData) + } + + pub fn id_cct_PKIResponse() -> Nid { + Nid(ffi::NID_id_cct_PKIResponse) + } + + pub fn id_ppl_anyLanguage() -> Nid { + Nid(ffi::NID_id_ppl_anyLanguage) + } + + pub fn id_ppl_inheritAll() -> Nid { + Nid(ffi::NID_id_ppl_inheritAll) + } + + pub fn Independent() -> Nid { + Nid(ffi::NID_Independent) + } + + pub fn ad_OCSP() -> Nid { + Nid(ffi::NID_ad_OCSP) + } + + pub fn ad_ca_issuers() -> Nid { + Nid(ffi::NID_ad_ca_issuers) + } + + pub fn ad_timeStamping() -> Nid { + Nid(ffi::NID_ad_timeStamping) + } + + pub fn ad_dvcs() -> Nid { + Nid(ffi::NID_ad_dvcs) + } + + pub fn caRepository() -> Nid { + Nid(ffi::NID_caRepository) + } + + pub fn id_pkix_OCSP_basic() -> Nid { + Nid(ffi::NID_id_pkix_OCSP_basic) + } + + pub fn id_pkix_OCSP_Nonce() -> Nid { + Nid(ffi::NID_id_pkix_OCSP_Nonce) + } + + pub fn id_pkix_OCSP_CrlID() -> Nid { + Nid(ffi::NID_id_pkix_OCSP_CrlID) + } + + pub fn id_pkix_OCSP_acceptableResponses() -> Nid { + Nid(ffi::NID_id_pkix_OCSP_acceptableResponses) + } + + pub fn id_pkix_OCSP_noCheck() -> Nid { + Nid(ffi::NID_id_pkix_OCSP_noCheck) + } + + pub fn id_pkix_OCSP_archiveCutoff() -> Nid { + Nid(ffi::NID_id_pkix_OCSP_archiveCutoff) + } + + pub fn id_pkix_OCSP_serviceLocator() -> Nid { + Nid(ffi::NID_id_pkix_OCSP_serviceLocator) + } + + pub fn id_pkix_OCSP_extendedStatus() -> Nid { + Nid(ffi::NID_id_pkix_OCSP_extendedStatus) + } + + pub fn id_pkix_OCSP_valid() -> Nid { + Nid(ffi::NID_id_pkix_OCSP_valid) + } + + pub fn id_pkix_OCSP_path() -> Nid { + Nid(ffi::NID_id_pkix_OCSP_path) + } + + pub fn id_pkix_OCSP_trustRoot() -> Nid { + Nid(ffi::NID_id_pkix_OCSP_trustRoot) + } + + pub fn algorithm() -> Nid { + Nid(ffi::NID_algorithm) + } + + pub fn md5WithRSA() -> Nid { + Nid(ffi::NID_md5WithRSA) + } + + pub fn des_ecb() -> Nid { + Nid(ffi::NID_des_ecb) + } + + pub fn des_cbc() -> Nid { + Nid(ffi::NID_des_cbc) + } + + pub fn des_ofb64() -> Nid { + Nid(ffi::NID_des_ofb64) + } + + pub fn des_cfb64() -> Nid { + Nid(ffi::NID_des_cfb64) + } + + pub fn rsaSignature() -> Nid { + Nid(ffi::NID_rsaSignature) + } + + pub fn dsa_2() -> Nid { + Nid(ffi::NID_dsa_2) + } + + pub fn dsaWithSHA() -> Nid { + Nid(ffi::NID_dsaWithSHA) + } + + pub fn shaWithRSAEncryption() -> Nid { + Nid(ffi::NID_shaWithRSAEncryption) + } + + pub fn des_ede_ecb() -> Nid { + Nid(ffi::NID_des_ede_ecb) + } + + pub fn des_ede3_ecb() -> Nid { + Nid(ffi::NID_des_ede3_ecb) + } + + pub fn des_ede_cbc() -> Nid { + Nid(ffi::NID_des_ede_cbc) + } + + pub fn des_ede_cfb64() -> Nid { + Nid(ffi::NID_des_ede_cfb64) + } + + pub fn des_ede3_cfb64() -> Nid { + Nid(ffi::NID_des_ede3_cfb64) + } + + pub fn des_ede_ofb64() -> Nid { + Nid(ffi::NID_des_ede_ofb64) + } + + pub fn des_ede3_ofb64() -> Nid { + Nid(ffi::NID_des_ede3_ofb64) + } + + pub fn desx_cbc() -> Nid { + Nid(ffi::NID_desx_cbc) + } + + pub fn sha() -> Nid { + Nid(ffi::NID_sha) + } + + pub fn sha1() -> Nid { + Nid(ffi::NID_sha1) + } + + pub fn dsaWithSHA1_2() -> Nid { + Nid(ffi::NID_dsaWithSHA1_2) + } + + pub fn sha1WithRSA() -> Nid { + Nid(ffi::NID_sha1WithRSA) + } + + pub fn ripemd160() -> Nid { + Nid(ffi::NID_ripemd160) + } + + pub fn ripemd160WithRSA() -> Nid { + Nid(ffi::NID_ripemd160WithRSA) + } + + pub fn sxnet() -> Nid { + Nid(ffi::NID_sxnet) + } + + pub fn X500() -> Nid { + Nid(ffi::NID_X500) + } + + pub fn X509() -> Nid { + Nid(ffi::NID_X509) + } + + pub fn commonName() -> Nid { + Nid(ffi::NID_commonName) + } + + pub fn surname() -> Nid { + Nid(ffi::NID_surname) + } + + pub fn serialNumber() -> Nid { + Nid(ffi::NID_serialNumber) + } + + pub fn countryName() -> Nid { + Nid(ffi::NID_countryName) + } + + pub fn localityName() -> Nid { + Nid(ffi::NID_localityName) + } + + pub fn stateOrProvinceName() -> Nid { + Nid(ffi::NID_stateOrProvinceName) + } + + pub fn streetAddress() -> Nid { + Nid(ffi::NID_streetAddress) + } + + pub fn organizationName() -> Nid { + Nid(ffi::NID_organizationName) + } + + pub fn organizationalUnitName() -> Nid { + Nid(ffi::NID_organizationalUnitName) + } + + pub fn title() -> Nid { + Nid(ffi::NID_title) + } + + pub fn description() -> Nid { + Nid(ffi::NID_description) + } + + pub fn searchGuide() -> Nid { + Nid(ffi::NID_searchGuide) + } + + pub fn businessCategory() -> Nid { + Nid(ffi::NID_businessCategory) + } + + pub fn postalAddress() -> Nid { + Nid(ffi::NID_postalAddress) + } + + pub fn postalCode() -> Nid { + Nid(ffi::NID_postalCode) + } + + pub fn postOfficeBox() -> Nid { + Nid(ffi::NID_postOfficeBox) + } + + pub fn physicalDeliveryOfficeName() -> Nid { + Nid(ffi::NID_physicalDeliveryOfficeName) + } + + pub fn telephoneNumber() -> Nid { + Nid(ffi::NID_telephoneNumber) + } + + pub fn telexNumber() -> Nid { + Nid(ffi::NID_telexNumber) + } + + pub fn teletexTerminalIdentifier() -> Nid { + Nid(ffi::NID_teletexTerminalIdentifier) + } + + pub fn facsimileTelephoneNumber() -> Nid { + Nid(ffi::NID_facsimileTelephoneNumber) + } + + pub fn x121Address() -> Nid { + Nid(ffi::NID_x121Address) + } + + pub fn internationaliSDNNumber() -> Nid { + Nid(ffi::NID_internationaliSDNNumber) + } + + pub fn registeredAddress() -> Nid { + Nid(ffi::NID_registeredAddress) + } + + pub fn destinationIndicator() -> Nid { + Nid(ffi::NID_destinationIndicator) + } + + pub fn preferredDeliveryMethod() -> Nid { + Nid(ffi::NID_preferredDeliveryMethod) + } + + pub fn presentationAddress() -> Nid { + Nid(ffi::NID_presentationAddress) + } + + pub fn supportedApplicationContext() -> Nid { + Nid(ffi::NID_supportedApplicationContext) + } + + pub fn member() -> Nid { + Nid(ffi::NID_member) + } + + pub fn owner() -> Nid { + Nid(ffi::NID_owner) + } + + pub fn roleOccupant() -> Nid { + Nid(ffi::NID_roleOccupant) + } + + pub fn seeAlso() -> Nid { + Nid(ffi::NID_seeAlso) + } + + pub fn userPassword() -> Nid { + Nid(ffi::NID_userPassword) + } + + pub fn userCertificate() -> Nid { + Nid(ffi::NID_userCertificate) + } + + pub fn cACertificate() -> Nid { + Nid(ffi::NID_cACertificate) + } + + pub fn authorityRevocationList() -> Nid { + Nid(ffi::NID_authorityRevocationList) + } + + pub fn certificateRevocationList() -> Nid { + Nid(ffi::NID_certificateRevocationList) + } + + pub fn crossCertificatePair() -> Nid { + Nid(ffi::NID_crossCertificatePair) + } + + pub fn name() -> Nid { + Nid(ffi::NID_name) + } + + pub fn givenName() -> Nid { + Nid(ffi::NID_givenName) + } + + pub fn initials() -> Nid { + Nid(ffi::NID_initials) + } + + pub fn generationQualifier() -> Nid { + Nid(ffi::NID_generationQualifier) + } + + pub fn x500UniqueIdentifier() -> Nid { + Nid(ffi::NID_x500UniqueIdentifier) + } + + pub fn dnQualifier() -> Nid { + Nid(ffi::NID_dnQualifier) + } + + pub fn enhancedSearchGuide() -> Nid { + Nid(ffi::NID_enhancedSearchGuide) + } + + pub fn protocolInformation() -> Nid { + Nid(ffi::NID_protocolInformation) + } + + pub fn distinguishedName() -> Nid { + Nid(ffi::NID_distinguishedName) + } + + pub fn uniqueMember() -> Nid { + Nid(ffi::NID_uniqueMember) + } + + pub fn houseIdentifier() -> Nid { + Nid(ffi::NID_houseIdentifier) + } + + pub fn supportedAlgorithms() -> Nid { + Nid(ffi::NID_supportedAlgorithms) + } + + pub fn deltaRevocationList() -> Nid { + Nid(ffi::NID_deltaRevocationList) + } + + pub fn dmdName() -> Nid { + Nid(ffi::NID_dmdName) + } + + pub fn pseudonym() -> Nid { + Nid(ffi::NID_pseudonym) + } + + pub fn role() -> Nid { + Nid(ffi::NID_role) + } + + pub fn X500algorithms() -> Nid { + Nid(ffi::NID_X500algorithms) + } + + pub fn rsa() -> Nid { + Nid(ffi::NID_rsa) + } + + pub fn mdc2WithRSA() -> Nid { + Nid(ffi::NID_mdc2WithRSA) + } + + pub fn mdc2() -> Nid { + Nid(ffi::NID_mdc2) + } + + pub fn id_ce() -> Nid { + Nid(ffi::NID_id_ce) + } + + pub fn subject_directory_attributes() -> Nid { + Nid(ffi::NID_subject_directory_attributes) + } + + pub fn subject_key_identifier() -> Nid { + Nid(ffi::NID_subject_key_identifier) + } + + pub fn key_usage() -> Nid { + Nid(ffi::NID_key_usage) + } + + pub fn private_key_usage_period() -> Nid { + Nid(ffi::NID_private_key_usage_period) + } + + pub fn subject_alt_name() -> Nid { + Nid(ffi::NID_subject_alt_name) + } + + pub fn issuer_alt_name() -> Nid { + Nid(ffi::NID_issuer_alt_name) + } + + pub fn basic_constraints() -> Nid { + Nid(ffi::NID_basic_constraints) + } + + pub fn crl_number() -> Nid { + Nid(ffi::NID_crl_number) + } + + pub fn crl_reason() -> Nid { + Nid(ffi::NID_crl_reason) + } + + pub fn invalidity_date() -> Nid { + Nid(ffi::NID_invalidity_date) + } + + pub fn delta_crl() -> Nid { + Nid(ffi::NID_delta_crl) + } + + pub fn issuing_distribution_point() -> Nid { + Nid(ffi::NID_issuing_distribution_point) + } + + pub fn certificate_issuer() -> Nid { + Nid(ffi::NID_certificate_issuer) + } + + pub fn name_constraints() -> Nid { + Nid(ffi::NID_name_constraints) + } + + pub fn crl_distribution_points() -> Nid { + Nid(ffi::NID_crl_distribution_points) + } + + pub fn certificate_policies() -> Nid { + Nid(ffi::NID_certificate_policies) + } + + pub fn any_policy() -> Nid { + Nid(ffi::NID_any_policy) + } + + pub fn policy_mappings() -> Nid { + Nid(ffi::NID_policy_mappings) + } + + pub fn authority_key_identifier() -> Nid { + Nid(ffi::NID_authority_key_identifier) + } + + pub fn policy_constraints() -> Nid { + Nid(ffi::NID_policy_constraints) + } + + pub fn ext_key_usage() -> Nid { + Nid(ffi::NID_ext_key_usage) + } + + pub fn freshest_crl() -> Nid { + Nid(ffi::NID_freshest_crl) + } + + pub fn inhibit_any_policy() -> Nid { + Nid(ffi::NID_inhibit_any_policy) + } + + pub fn target_information() -> Nid { + Nid(ffi::NID_target_information) + } + + pub fn no_rev_avail() -> Nid { + Nid(ffi::NID_no_rev_avail) + } + + pub fn anyExtendedKeyUsage() -> Nid { + Nid(ffi::NID_anyExtendedKeyUsage) + } + + pub fn netscape() -> Nid { + Nid(ffi::NID_netscape) + } + + pub fn netscape_cert_extension() -> Nid { + Nid(ffi::NID_netscape_cert_extension) + } + + pub fn netscape_data_type() -> Nid { + Nid(ffi::NID_netscape_data_type) + } + + pub fn netscape_cert_type() -> Nid { + Nid(ffi::NID_netscape_cert_type) + } + + pub fn netscape_base_url() -> Nid { + Nid(ffi::NID_netscape_base_url) + } + + pub fn netscape_revocation_url() -> Nid { + Nid(ffi::NID_netscape_revocation_url) + } + + pub fn netscape_ca_revocation_url() -> Nid { + Nid(ffi::NID_netscape_ca_revocation_url) + } + + pub fn netscape_renewal_url() -> Nid { + Nid(ffi::NID_netscape_renewal_url) + } + + pub fn netscape_ca_policy_url() -> Nid { + Nid(ffi::NID_netscape_ca_policy_url) + } + + pub fn netscape_ssl_server_name() -> Nid { + Nid(ffi::NID_netscape_ssl_server_name) + } + + pub fn netscape_comment() -> Nid { + Nid(ffi::NID_netscape_comment) + } + + pub fn netscape_cert_sequence() -> Nid { + Nid(ffi::NID_netscape_cert_sequence) + } + + pub fn ns_sgc() -> Nid { + Nid(ffi::NID_ns_sgc) + } + + pub fn org() -> Nid { + Nid(ffi::NID_org) + } + + pub fn dod() -> Nid { + Nid(ffi::NID_dod) + } + + pub fn iana() -> Nid { + Nid(ffi::NID_iana) + } + + pub fn Directory() -> Nid { + Nid(ffi::NID_Directory) + } + + pub fn Management() -> Nid { + Nid(ffi::NID_Management) + } + + pub fn Experimental() -> Nid { + Nid(ffi::NID_Experimental) + } + + pub fn Private() -> Nid { + Nid(ffi::NID_Private) + } + + pub fn Security() -> Nid { + Nid(ffi::NID_Security) + } + + pub fn SNMPv2() -> Nid { + Nid(ffi::NID_SNMPv2) + } + + pub fn Mail() -> Nid { + Nid(ffi::NID_Mail) + } + + pub fn Enterprises() -> Nid { + Nid(ffi::NID_Enterprises) + } + + pub fn dcObject() -> Nid { + Nid(ffi::NID_dcObject) + } + + pub fn mime_mhs() -> Nid { + Nid(ffi::NID_mime_mhs) + } + + pub fn mime_mhs_headings() -> Nid { + Nid(ffi::NID_mime_mhs_headings) + } + + pub fn mime_mhs_bodies() -> Nid { + Nid(ffi::NID_mime_mhs_bodies) + } + + pub fn id_hex_partial_message() -> Nid { + Nid(ffi::NID_id_hex_partial_message) + } + + pub fn id_hex_multipart_message() -> Nid { + Nid(ffi::NID_id_hex_multipart_message) + } + + pub fn rle_compression() -> Nid { + Nid(ffi::NID_rle_compression) + } + + pub fn zlib_compression() -> Nid { + Nid(ffi::NID_zlib_compression) + } + + pub fn aes_128_ecb() -> Nid { + Nid(ffi::NID_aes_128_ecb) + } + + pub fn aes_128_cbc() -> Nid { + Nid(ffi::NID_aes_128_cbc) + } + + pub fn aes_128_ofb128() -> Nid { + Nid(ffi::NID_aes_128_ofb128) + } + + pub fn aes_128_cfb128() -> Nid { + Nid(ffi::NID_aes_128_cfb128) + } + + pub fn id_aes128_wrap() -> Nid { + Nid(ffi::NID_id_aes128_wrap) + } + + pub fn aes_128_gcm() -> Nid { + Nid(ffi::NID_aes_128_gcm) + } + + pub fn aes_128_ccm() -> Nid { + Nid(ffi::NID_aes_128_ccm) + } + + pub fn id_aes128_wrap_pad() -> Nid { + Nid(ffi::NID_id_aes128_wrap_pad) + } + + pub fn aes_192_ecb() -> Nid { + Nid(ffi::NID_aes_192_ecb) + } + + pub fn aes_192_cbc() -> Nid { + Nid(ffi::NID_aes_192_cbc) + } + + pub fn aes_192_ofb128() -> Nid { + Nid(ffi::NID_aes_192_ofb128) + } + + pub fn aes_192_cfb128() -> Nid { + Nid(ffi::NID_aes_192_cfb128) + } + + pub fn id_aes192_wrap() -> Nid { + Nid(ffi::NID_id_aes192_wrap) + } + + pub fn aes_192_gcm() -> Nid { + Nid(ffi::NID_aes_192_gcm) + } + + pub fn aes_192_ccm() -> Nid { + Nid(ffi::NID_aes_192_ccm) + } + + pub fn id_aes192_wrap_pad() -> Nid { + Nid(ffi::NID_id_aes192_wrap_pad) + } + + pub fn aes_256_ecb() -> Nid { + Nid(ffi::NID_aes_256_ecb) + } + + pub fn aes_256_cbc() -> Nid { + Nid(ffi::NID_aes_256_cbc) + } + + pub fn aes_256_ofb128() -> Nid { + Nid(ffi::NID_aes_256_ofb128) + } + + pub fn aes_256_cfb128() -> Nid { + Nid(ffi::NID_aes_256_cfb128) + } + + pub fn id_aes256_wrap() -> Nid { + Nid(ffi::NID_id_aes256_wrap) + } + + pub fn aes_256_gcm() -> Nid { + Nid(ffi::NID_aes_256_gcm) + } + + pub fn aes_256_ccm() -> Nid { + Nid(ffi::NID_aes_256_ccm) + } + + pub fn id_aes256_wrap_pad() -> Nid { + Nid(ffi::NID_id_aes256_wrap_pad) + } + + pub fn aes_128_cfb1() -> Nid { + Nid(ffi::NID_aes_128_cfb1) + } + + pub fn aes_192_cfb1() -> Nid { + Nid(ffi::NID_aes_192_cfb1) + } + + pub fn aes_256_cfb1() -> Nid { + Nid(ffi::NID_aes_256_cfb1) + } + + pub fn aes_128_cfb8() -> Nid { + Nid(ffi::NID_aes_128_cfb8) + } + + pub fn aes_192_cfb8() -> Nid { + Nid(ffi::NID_aes_192_cfb8) + } + + pub fn aes_256_cfb8() -> Nid { + Nid(ffi::NID_aes_256_cfb8) + } + + pub fn aes_128_ctr() -> Nid { + Nid(ffi::NID_aes_128_ctr) + } + + pub fn aes_192_ctr() -> Nid { + Nid(ffi::NID_aes_192_ctr) + } + + pub fn aes_256_ctr() -> Nid { + Nid(ffi::NID_aes_256_ctr) + } + + pub fn aes_128_xts() -> Nid { + Nid(ffi::NID_aes_128_xts) + } + + pub fn aes_256_xts() -> Nid { + Nid(ffi::NID_aes_256_xts) + } + + pub fn des_cfb1() -> Nid { + Nid(ffi::NID_des_cfb1) + } + + pub fn des_cfb8() -> Nid { + Nid(ffi::NID_des_cfb8) + } + + pub fn des_ede3_cfb1() -> Nid { + Nid(ffi::NID_des_ede3_cfb1) + } + + pub fn des_ede3_cfb8() -> Nid { + Nid(ffi::NID_des_ede3_cfb8) + } + + pub fn sha256() -> Nid { + Nid(ffi::NID_sha256) + } + + pub fn sha384() -> Nid { + Nid(ffi::NID_sha384) + } + + pub fn sha512() -> Nid { + Nid(ffi::NID_sha512) + } + + pub fn sha224() -> Nid { + Nid(ffi::NID_sha224) + } + + pub fn dsa_with_SHA224() -> Nid { + Nid(ffi::NID_dsa_with_SHA224) + } + + pub fn dsa_with_SHA256() -> Nid { + Nid(ffi::NID_dsa_with_SHA256) + } + + pub fn hold_instruction_code() -> Nid { + Nid(ffi::NID_hold_instruction_code) + } + + pub fn hold_instruction_none() -> Nid { + Nid(ffi::NID_hold_instruction_none) + } + + pub fn hold_instruction_call_issuer() -> Nid { + Nid(ffi::NID_hold_instruction_call_issuer) + } + + pub fn hold_instruction_reject() -> Nid { + Nid(ffi::NID_hold_instruction_reject) + } + + pub fn data() -> Nid { + Nid(ffi::NID_data) + } + + pub fn pss() -> Nid { + Nid(ffi::NID_pss) + } + + pub fn ucl() -> Nid { + Nid(ffi::NID_ucl) + } + + pub fn pilot() -> Nid { + Nid(ffi::NID_pilot) + } + + pub fn pilotAttributeType() -> Nid { + Nid(ffi::NID_pilotAttributeType) + } + + pub fn pilotAttributeSyntax() -> Nid { + Nid(ffi::NID_pilotAttributeSyntax) + } + + pub fn pilotObjectClass() -> Nid { + Nid(ffi::NID_pilotObjectClass) + } + + pub fn pilotGroups() -> Nid { + Nid(ffi::NID_pilotGroups) + } + + pub fn iA5StringSyntax() -> Nid { + Nid(ffi::NID_iA5StringSyntax) + } + + pub fn caseIgnoreIA5StringSyntax() -> Nid { + Nid(ffi::NID_caseIgnoreIA5StringSyntax) + } + + pub fn pilotObject() -> Nid { + Nid(ffi::NID_pilotObject) + } + + pub fn pilotPerson() -> Nid { + Nid(ffi::NID_pilotPerson) + } + + pub fn account() -> Nid { + Nid(ffi::NID_account) + } + + pub fn document() -> Nid { + Nid(ffi::NID_document) + } + + pub fn room() -> Nid { + Nid(ffi::NID_room) + } + + pub fn documentSeries() -> Nid { + Nid(ffi::NID_documentSeries) + } + + pub fn Domain() -> Nid { + Nid(ffi::NID_Domain) + } + + pub fn rFC822localPart() -> Nid { + Nid(ffi::NID_rFC822localPart) + } + + pub fn dNSDomain() -> Nid { + Nid(ffi::NID_dNSDomain) + } + + pub fn domainRelatedObject() -> Nid { + Nid(ffi::NID_domainRelatedObject) + } + + pub fn friendlyCountry() -> Nid { + Nid(ffi::NID_friendlyCountry) + } + + pub fn simpleSecurityObject() -> Nid { + Nid(ffi::NID_simpleSecurityObject) + } + + pub fn pilotOrganization() -> Nid { + Nid(ffi::NID_pilotOrganization) + } + + pub fn pilotDSA() -> Nid { + Nid(ffi::NID_pilotDSA) + } + + pub fn qualityLabelledData() -> Nid { + Nid(ffi::NID_qualityLabelledData) + } + + pub fn userId() -> Nid { + Nid(ffi::NID_userId) + } + + pub fn textEncodedORAddress() -> Nid { + Nid(ffi::NID_textEncodedORAddress) + } + + pub fn rfc822Mailbox() -> Nid { + Nid(ffi::NID_rfc822Mailbox) + } + + pub fn info() -> Nid { + Nid(ffi::NID_info) + } + + pub fn favouriteDrink() -> Nid { + Nid(ffi::NID_favouriteDrink) + } + + pub fn roomNumber() -> Nid { + Nid(ffi::NID_roomNumber) + } + + pub fn photo() -> Nid { + Nid(ffi::NID_photo) + } + + pub fn userClass() -> Nid { + Nid(ffi::NID_userClass) + } + + pub fn host() -> Nid { + Nid(ffi::NID_host) + } + + pub fn manager() -> Nid { + Nid(ffi::NID_manager) + } + + pub fn documentIdentifier() -> Nid { + Nid(ffi::NID_documentIdentifier) + } + + pub fn documentTitle() -> Nid { + Nid(ffi::NID_documentTitle) + } + + pub fn documentVersion() -> Nid { + Nid(ffi::NID_documentVersion) + } + + pub fn documentAuthor() -> Nid { + Nid(ffi::NID_documentAuthor) + } + + pub fn documentLocation() -> Nid { + Nid(ffi::NID_documentLocation) + } + + pub fn homeTelephoneNumber() -> Nid { + Nid(ffi::NID_homeTelephoneNumber) + } + + pub fn secretary() -> Nid { + Nid(ffi::NID_secretary) + } + + pub fn otherMailbox() -> Nid { + Nid(ffi::NID_otherMailbox) + } + + pub fn lastModifiedTime() -> Nid { + Nid(ffi::NID_lastModifiedTime) + } + + pub fn lastModifiedBy() -> Nid { + Nid(ffi::NID_lastModifiedBy) + } + + pub fn domainComponent() -> Nid { + Nid(ffi::NID_domainComponent) + } + + pub fn aRecord() -> Nid { + Nid(ffi::NID_aRecord) + } + + pub fn pilotAttributeType27() -> Nid { + Nid(ffi::NID_pilotAttributeType27) + } + + pub fn mXRecord() -> Nid { + Nid(ffi::NID_mXRecord) + } + + pub fn nSRecord() -> Nid { + Nid(ffi::NID_nSRecord) + } + + pub fn sOARecord() -> Nid { + Nid(ffi::NID_sOARecord) + } + + pub fn cNAMERecord() -> Nid { + Nid(ffi::NID_cNAMERecord) + } + + pub fn associatedDomain() -> Nid { + Nid(ffi::NID_associatedDomain) + } + + pub fn associatedName() -> Nid { + Nid(ffi::NID_associatedName) + } + + pub fn homePostalAddress() -> Nid { + Nid(ffi::NID_homePostalAddress) + } + + pub fn personalTitle() -> Nid { + Nid(ffi::NID_personalTitle) + } + + pub fn mobileTelephoneNumber() -> Nid { + Nid(ffi::NID_mobileTelephoneNumber) + } + + pub fn pagerTelephoneNumber() -> Nid { + Nid(ffi::NID_pagerTelephoneNumber) + } + + pub fn friendlyCountryName() -> Nid { + Nid(ffi::NID_friendlyCountryName) + } + + pub fn organizationalStatus() -> Nid { + Nid(ffi::NID_organizationalStatus) + } + + pub fn janetMailbox() -> Nid { + Nid(ffi::NID_janetMailbox) + } + + pub fn mailPreferenceOption() -> Nid { + Nid(ffi::NID_mailPreferenceOption) + } + + pub fn buildingName() -> Nid { + Nid(ffi::NID_buildingName) + } + + pub fn dSAQuality() -> Nid { + Nid(ffi::NID_dSAQuality) + } + + pub fn singleLevelQuality() -> Nid { + Nid(ffi::NID_singleLevelQuality) + } + + pub fn subtreeMinimumQuality() -> Nid { + Nid(ffi::NID_subtreeMinimumQuality) + } + + pub fn subtreeMaximumQuality() -> Nid { + Nid(ffi::NID_subtreeMaximumQuality) + } + + pub fn personalSignature() -> Nid { + Nid(ffi::NID_personalSignature) + } + + pub fn dITRedirect() -> Nid { + Nid(ffi::NID_dITRedirect) + } + + pub fn audio() -> Nid { + Nid(ffi::NID_audio) + } + + pub fn documentPublisher() -> Nid { + Nid(ffi::NID_documentPublisher) + } + + pub fn id_set() -> Nid { + Nid(ffi::NID_id_set) + } + + pub fn set_ctype() -> Nid { + Nid(ffi::NID_set_ctype) + } + + pub fn set_msgExt() -> Nid { + Nid(ffi::NID_set_msgExt) + } + + pub fn set_attr() -> Nid { + Nid(ffi::NID_set_attr) + } + + pub fn set_policy() -> Nid { + Nid(ffi::NID_set_policy) + } + + pub fn set_certExt() -> Nid { + Nid(ffi::NID_set_certExt) + } + + pub fn set_brand() -> Nid { + Nid(ffi::NID_set_brand) + } + + pub fn setct_PANData() -> Nid { + Nid(ffi::NID_setct_PANData) + } + + pub fn setct_PANToken() -> Nid { + Nid(ffi::NID_setct_PANToken) + } + + pub fn setct_PANOnly() -> Nid { + Nid(ffi::NID_setct_PANOnly) + } + + pub fn setct_OIData() -> Nid { + Nid(ffi::NID_setct_OIData) + } + + pub fn setct_PI() -> Nid { + Nid(ffi::NID_setct_PI) + } + + pub fn setct_PIData() -> Nid { + Nid(ffi::NID_setct_PIData) + } + + pub fn setct_PIDataUnsigned() -> Nid { + Nid(ffi::NID_setct_PIDataUnsigned) + } + + pub fn setct_HODInput() -> Nid { + Nid(ffi::NID_setct_HODInput) + } + + pub fn setct_AuthResBaggage() -> Nid { + Nid(ffi::NID_setct_AuthResBaggage) + } + + pub fn setct_AuthRevReqBaggage() -> Nid { + Nid(ffi::NID_setct_AuthRevReqBaggage) + } + + pub fn setct_AuthRevResBaggage() -> Nid { + Nid(ffi::NID_setct_AuthRevResBaggage) + } + + pub fn setct_CapTokenSeq() -> Nid { + Nid(ffi::NID_setct_CapTokenSeq) + } + + pub fn setct_PInitResData() -> Nid { + Nid(ffi::NID_setct_PInitResData) + } + + pub fn setct_PI_TBS() -> Nid { + Nid(ffi::NID_setct_PI_TBS) + } + + pub fn setct_PResData() -> Nid { + Nid(ffi::NID_setct_PResData) + } + + pub fn setct_AuthReqTBS() -> Nid { + Nid(ffi::NID_setct_AuthReqTBS) + } + + pub fn setct_AuthResTBS() -> Nid { + Nid(ffi::NID_setct_AuthResTBS) + } + + pub fn setct_AuthResTBSX() -> Nid { + Nid(ffi::NID_setct_AuthResTBSX) + } + + pub fn setct_AuthTokenTBS() -> Nid { + Nid(ffi::NID_setct_AuthTokenTBS) + } + + pub fn setct_CapTokenData() -> Nid { + Nid(ffi::NID_setct_CapTokenData) + } + + pub fn setct_CapTokenTBS() -> Nid { + Nid(ffi::NID_setct_CapTokenTBS) + } + + pub fn setct_AcqCardCodeMsg() -> Nid { + Nid(ffi::NID_setct_AcqCardCodeMsg) + } + + pub fn setct_AuthRevReqTBS() -> Nid { + Nid(ffi::NID_setct_AuthRevReqTBS) + } + + pub fn setct_AuthRevResData() -> Nid { + Nid(ffi::NID_setct_AuthRevResData) + } + + pub fn setct_AuthRevResTBS() -> Nid { + Nid(ffi::NID_setct_AuthRevResTBS) + } + + pub fn setct_CapReqTBS() -> Nid { + Nid(ffi::NID_setct_CapReqTBS) + } + + pub fn setct_CapReqTBSX() -> Nid { + Nid(ffi::NID_setct_CapReqTBSX) + } + + pub fn setct_CapResData() -> Nid { + Nid(ffi::NID_setct_CapResData) + } + + pub fn setct_CapRevReqTBS() -> Nid { + Nid(ffi::NID_setct_CapRevReqTBS) + } + + pub fn setct_CapRevReqTBSX() -> Nid { + Nid(ffi::NID_setct_CapRevReqTBSX) + } + + pub fn setct_CapRevResData() -> Nid { + Nid(ffi::NID_setct_CapRevResData) + } + + pub fn setct_CredReqTBS() -> Nid { + Nid(ffi::NID_setct_CredReqTBS) + } + + pub fn setct_CredReqTBSX() -> Nid { + Nid(ffi::NID_setct_CredReqTBSX) + } + + pub fn setct_CredResData() -> Nid { + Nid(ffi::NID_setct_CredResData) + } + + pub fn setct_CredRevReqTBS() -> Nid { + Nid(ffi::NID_setct_CredRevReqTBS) + } + + pub fn setct_CredRevReqTBSX() -> Nid { + Nid(ffi::NID_setct_CredRevReqTBSX) + } + + pub fn setct_CredRevResData() -> Nid { + Nid(ffi::NID_setct_CredRevResData) + } + + pub fn setct_PCertReqData() -> Nid { + Nid(ffi::NID_setct_PCertReqData) + } + + pub fn setct_PCertResTBS() -> Nid { + Nid(ffi::NID_setct_PCertResTBS) + } + + pub fn setct_BatchAdminReqData() -> Nid { + Nid(ffi::NID_setct_BatchAdminReqData) + } + + pub fn setct_BatchAdminResData() -> Nid { + Nid(ffi::NID_setct_BatchAdminResData) + } + + pub fn setct_CardCInitResTBS() -> Nid { + Nid(ffi::NID_setct_CardCInitResTBS) + } + + pub fn setct_MeAqCInitResTBS() -> Nid { + Nid(ffi::NID_setct_MeAqCInitResTBS) + } + + pub fn setct_RegFormResTBS() -> Nid { + Nid(ffi::NID_setct_RegFormResTBS) + } + + pub fn setct_CertReqData() -> Nid { + Nid(ffi::NID_setct_CertReqData) + } + + pub fn setct_CertReqTBS() -> Nid { + Nid(ffi::NID_setct_CertReqTBS) + } + + pub fn setct_CertResData() -> Nid { + Nid(ffi::NID_setct_CertResData) + } + + pub fn setct_CertInqReqTBS() -> Nid { + Nid(ffi::NID_setct_CertInqReqTBS) + } + + pub fn setct_ErrorTBS() -> Nid { + Nid(ffi::NID_setct_ErrorTBS) + } + + pub fn setct_PIDualSignedTBE() -> Nid { + Nid(ffi::NID_setct_PIDualSignedTBE) + } + + pub fn setct_PIUnsignedTBE() -> Nid { + Nid(ffi::NID_setct_PIUnsignedTBE) + } + + pub fn setct_AuthReqTBE() -> Nid { + Nid(ffi::NID_setct_AuthReqTBE) + } + + pub fn setct_AuthResTBE() -> Nid { + Nid(ffi::NID_setct_AuthResTBE) + } + + pub fn setct_AuthResTBEX() -> Nid { + Nid(ffi::NID_setct_AuthResTBEX) + } + + pub fn setct_AuthTokenTBE() -> Nid { + Nid(ffi::NID_setct_AuthTokenTBE) + } + + pub fn setct_CapTokenTBE() -> Nid { + Nid(ffi::NID_setct_CapTokenTBE) + } + + pub fn setct_CapTokenTBEX() -> Nid { + Nid(ffi::NID_setct_CapTokenTBEX) + } + + pub fn setct_AcqCardCodeMsgTBE() -> Nid { + Nid(ffi::NID_setct_AcqCardCodeMsgTBE) + } + + pub fn setct_AuthRevReqTBE() -> Nid { + Nid(ffi::NID_setct_AuthRevReqTBE) + } + + pub fn setct_AuthRevResTBE() -> Nid { + Nid(ffi::NID_setct_AuthRevResTBE) + } + + pub fn setct_AuthRevResTBEB() -> Nid { + Nid(ffi::NID_setct_AuthRevResTBEB) + } + + pub fn setct_CapReqTBE() -> Nid { + Nid(ffi::NID_setct_CapReqTBE) + } + + pub fn setct_CapReqTBEX() -> Nid { + Nid(ffi::NID_setct_CapReqTBEX) + } + + pub fn setct_CapResTBE() -> Nid { + Nid(ffi::NID_setct_CapResTBE) + } + + pub fn setct_CapRevReqTBE() -> Nid { + Nid(ffi::NID_setct_CapRevReqTBE) + } + + pub fn setct_CapRevReqTBEX() -> Nid { + Nid(ffi::NID_setct_CapRevReqTBEX) + } + + pub fn setct_CapRevResTBE() -> Nid { + Nid(ffi::NID_setct_CapRevResTBE) + } + + pub fn setct_CredReqTBE() -> Nid { + Nid(ffi::NID_setct_CredReqTBE) + } + + pub fn setct_CredReqTBEX() -> Nid { + Nid(ffi::NID_setct_CredReqTBEX) + } + + pub fn setct_CredResTBE() -> Nid { + Nid(ffi::NID_setct_CredResTBE) + } + + pub fn setct_CredRevReqTBE() -> Nid { + Nid(ffi::NID_setct_CredRevReqTBE) + } + + pub fn setct_CredRevReqTBEX() -> Nid { + Nid(ffi::NID_setct_CredRevReqTBEX) + } + + pub fn setct_CredRevResTBE() -> Nid { + Nid(ffi::NID_setct_CredRevResTBE) + } + + pub fn setct_BatchAdminReqTBE() -> Nid { + Nid(ffi::NID_setct_BatchAdminReqTBE) + } + + pub fn setct_BatchAdminResTBE() -> Nid { + Nid(ffi::NID_setct_BatchAdminResTBE) + } + + pub fn setct_RegFormReqTBE() -> Nid { + Nid(ffi::NID_setct_RegFormReqTBE) + } + + pub fn setct_CertReqTBE() -> Nid { + Nid(ffi::NID_setct_CertReqTBE) + } + + pub fn setct_CertReqTBEX() -> Nid { + Nid(ffi::NID_setct_CertReqTBEX) + } + + pub fn setct_CertResTBE() -> Nid { + Nid(ffi::NID_setct_CertResTBE) + } + + pub fn setct_CRLNotificationTBS() -> Nid { + Nid(ffi::NID_setct_CRLNotificationTBS) + } + + pub fn setct_CRLNotificationResTBS() -> Nid { + Nid(ffi::NID_setct_CRLNotificationResTBS) + } + + pub fn setct_BCIDistributionTBS() -> Nid { + Nid(ffi::NID_setct_BCIDistributionTBS) + } + + pub fn setext_genCrypt() -> Nid { + Nid(ffi::NID_setext_genCrypt) + } + + pub fn setext_miAuth() -> Nid { + Nid(ffi::NID_setext_miAuth) + } + + pub fn setext_pinSecure() -> Nid { + Nid(ffi::NID_setext_pinSecure) + } + + pub fn setext_pinAny() -> Nid { + Nid(ffi::NID_setext_pinAny) + } + + pub fn setext_track2() -> Nid { + Nid(ffi::NID_setext_track2) + } + + pub fn setext_cv() -> Nid { + Nid(ffi::NID_setext_cv) + } + + pub fn set_policy_root() -> Nid { + Nid(ffi::NID_set_policy_root) + } + + pub fn setCext_hashedRoot() -> Nid { + Nid(ffi::NID_setCext_hashedRoot) + } + + pub fn setCext_certType() -> Nid { + Nid(ffi::NID_setCext_certType) + } + + pub fn setCext_merchData() -> Nid { + Nid(ffi::NID_setCext_merchData) + } + + pub fn setCext_cCertRequired() -> Nid { + Nid(ffi::NID_setCext_cCertRequired) + } + + pub fn setCext_tunneling() -> Nid { + Nid(ffi::NID_setCext_tunneling) + } + + pub fn setCext_setExt() -> Nid { + Nid(ffi::NID_setCext_setExt) + } + + pub fn setCext_setQualf() -> Nid { + Nid(ffi::NID_setCext_setQualf) + } + + pub fn setCext_PGWYcapabilities() -> Nid { + Nid(ffi::NID_setCext_PGWYcapabilities) + } + + pub fn setCext_TokenIdentifier() -> Nid { + Nid(ffi::NID_setCext_TokenIdentifier) + } + + pub fn setCext_Track2Data() -> Nid { + Nid(ffi::NID_setCext_Track2Data) + } + + pub fn setCext_TokenType() -> Nid { + Nid(ffi::NID_setCext_TokenType) + } + + pub fn setCext_IssuerCapabilities() -> Nid { + Nid(ffi::NID_setCext_IssuerCapabilities) + } + + pub fn setAttr_Cert() -> Nid { + Nid(ffi::NID_setAttr_Cert) + } + + pub fn setAttr_PGWYcap() -> Nid { + Nid(ffi::NID_setAttr_PGWYcap) + } + + pub fn setAttr_TokenType() -> Nid { + Nid(ffi::NID_setAttr_TokenType) + } + + pub fn setAttr_IssCap() -> Nid { + Nid(ffi::NID_setAttr_IssCap) + } + + pub fn set_rootKeyThumb() -> Nid { + Nid(ffi::NID_set_rootKeyThumb) + } + + pub fn set_addPolicy() -> Nid { + Nid(ffi::NID_set_addPolicy) + } + + pub fn setAttr_Token_EMV() -> Nid { + Nid(ffi::NID_setAttr_Token_EMV) + } + + pub fn setAttr_Token_B0Prime() -> Nid { + Nid(ffi::NID_setAttr_Token_B0Prime) + } + + pub fn setAttr_IssCap_CVM() -> Nid { + Nid(ffi::NID_setAttr_IssCap_CVM) + } + + pub fn setAttr_IssCap_T2() -> Nid { + Nid(ffi::NID_setAttr_IssCap_T2) + } + + pub fn setAttr_IssCap_Sig() -> Nid { + Nid(ffi::NID_setAttr_IssCap_Sig) + } + + pub fn setAttr_GenCryptgrm() -> Nid { + Nid(ffi::NID_setAttr_GenCryptgrm) + } + + pub fn setAttr_T2Enc() -> Nid { + Nid(ffi::NID_setAttr_T2Enc) + } + + pub fn setAttr_T2cleartxt() -> Nid { + Nid(ffi::NID_setAttr_T2cleartxt) + } + + pub fn setAttr_TokICCsig() -> Nid { + Nid(ffi::NID_setAttr_TokICCsig) + } + + pub fn setAttr_SecDevSig() -> Nid { + Nid(ffi::NID_setAttr_SecDevSig) + } + + pub fn set_brand_IATA_ATA() -> Nid { + Nid(ffi::NID_set_brand_IATA_ATA) + } + + pub fn set_brand_Diners() -> Nid { + Nid(ffi::NID_set_brand_Diners) + } + + pub fn set_brand_AmericanExpress() -> Nid { + Nid(ffi::NID_set_brand_AmericanExpress) + } + + pub fn set_brand_JCB() -> Nid { + Nid(ffi::NID_set_brand_JCB) + } + + pub fn set_brand_Visa() -> Nid { + Nid(ffi::NID_set_brand_Visa) + } + + pub fn set_brand_MasterCard() -> Nid { + Nid(ffi::NID_set_brand_MasterCard) + } + + pub fn set_brand_Novus() -> Nid { + Nid(ffi::NID_set_brand_Novus) + } + + pub fn des_cdmf() -> Nid { + Nid(ffi::NID_des_cdmf) + } + + pub fn rsaOAEPEncryptionSET() -> Nid { + Nid(ffi::NID_rsaOAEPEncryptionSET) + } + + pub fn ipsec3() -> Nid { + Nid(ffi::NID_ipsec3) + } + + pub fn ipsec4() -> Nid { + Nid(ffi::NID_ipsec4) + } + + pub fn whirlpool() -> Nid { + Nid(ffi::NID_whirlpool) + } + + pub fn cryptopro() -> Nid { + Nid(ffi::NID_cryptopro) + } + + pub fn cryptocom() -> Nid { + Nid(ffi::NID_cryptocom) + } + + pub fn id_GostR3411_94_with_GostR3410_2001() -> Nid { + Nid(ffi::NID_id_GostR3411_94_with_GostR3410_2001) + } + + pub fn id_GostR3411_94_with_GostR3410_94() -> Nid { + Nid(ffi::NID_id_GostR3411_94_with_GostR3410_94) + } + + pub fn id_GostR3411_94() -> Nid { + Nid(ffi::NID_id_GostR3411_94) + } + + pub fn id_HMACGostR3411_94() -> Nid { + Nid(ffi::NID_id_HMACGostR3411_94) + } + + pub fn id_GostR3410_2001() -> Nid { + Nid(ffi::NID_id_GostR3410_2001) + } + + pub fn id_GostR3410_94() -> Nid { + Nid(ffi::NID_id_GostR3410_94) + } + + pub fn id_Gost28147_89() -> Nid { + Nid(ffi::NID_id_Gost28147_89) + } + + pub fn gost89_cnt() -> Nid { + Nid(ffi::NID_gost89_cnt) + } + + pub fn id_Gost28147_89_MAC() -> Nid { + Nid(ffi::NID_id_Gost28147_89_MAC) + } + + pub fn id_GostR3411_94_prf() -> Nid { + Nid(ffi::NID_id_GostR3411_94_prf) + } + + pub fn id_GostR3410_2001DH() -> Nid { + Nid(ffi::NID_id_GostR3410_2001DH) + } + + pub fn id_GostR3410_94DH() -> Nid { + Nid(ffi::NID_id_GostR3410_94DH) + } + + pub fn id_Gost28147_89_CryptoPro_KeyMeshing() -> Nid { + Nid(ffi::NID_id_Gost28147_89_CryptoPro_KeyMeshing) + } + + pub fn id_Gost28147_89_None_KeyMeshing() -> Nid { + Nid(ffi::NID_id_Gost28147_89_None_KeyMeshing) + } + + pub fn id_GostR3411_94_TestParamSet() -> Nid { + Nid(ffi::NID_id_GostR3411_94_TestParamSet) + } + + pub fn id_GostR3411_94_CryptoProParamSet() -> Nid { + Nid(ffi::NID_id_GostR3411_94_CryptoProParamSet) + } + + pub fn id_Gost28147_89_TestParamSet() -> Nid { + Nid(ffi::NID_id_Gost28147_89_TestParamSet) + } + + pub fn id_Gost28147_89_CryptoPro_A_ParamSet() -> Nid { + Nid(ffi::NID_id_Gost28147_89_CryptoPro_A_ParamSet) + } + + pub fn id_Gost28147_89_CryptoPro_B_ParamSet() -> Nid { + Nid(ffi::NID_id_Gost28147_89_CryptoPro_B_ParamSet) + } + + pub fn id_Gost28147_89_CryptoPro_C_ParamSet() -> Nid { + Nid(ffi::NID_id_Gost28147_89_CryptoPro_C_ParamSet) + } + + pub fn id_Gost28147_89_CryptoPro_D_ParamSet() -> Nid { + Nid(ffi::NID_id_Gost28147_89_CryptoPro_D_ParamSet) + } + + pub fn id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet() -> Nid { + Nid(ffi::NID_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet) + } + + pub fn id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet() -> Nid { + Nid(ffi::NID_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet) + } + + pub fn id_Gost28147_89_CryptoPro_RIC_1_ParamSet() -> Nid { + Nid(ffi::NID_id_Gost28147_89_CryptoPro_RIC_1_ParamSet) + } + + pub fn id_GostR3410_94_TestParamSet() -> Nid { + Nid(ffi::NID_id_GostR3410_94_TestParamSet) + } + + pub fn id_GostR3410_94_CryptoPro_A_ParamSet() -> Nid { + Nid(ffi::NID_id_GostR3410_94_CryptoPro_A_ParamSet) + } + + pub fn id_GostR3410_94_CryptoPro_B_ParamSet() -> Nid { + Nid(ffi::NID_id_GostR3410_94_CryptoPro_B_ParamSet) + } + + pub fn id_GostR3410_94_CryptoPro_C_ParamSet() -> Nid { + Nid(ffi::NID_id_GostR3410_94_CryptoPro_C_ParamSet) + } + + pub fn id_GostR3410_94_CryptoPro_D_ParamSet() -> Nid { + Nid(ffi::NID_id_GostR3410_94_CryptoPro_D_ParamSet) + } + + pub fn id_GostR3410_94_CryptoPro_XchA_ParamSet() -> Nid { + Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchA_ParamSet) + } + + pub fn id_GostR3410_94_CryptoPro_XchB_ParamSet() -> Nid { + Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchB_ParamSet) + } + + pub fn id_GostR3410_94_CryptoPro_XchC_ParamSet() -> Nid { + Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchC_ParamSet) + } + + pub fn id_GostR3410_2001_TestParamSet() -> Nid { + Nid(ffi::NID_id_GostR3410_2001_TestParamSet) + } + + pub fn id_GostR3410_2001_CryptoPro_A_ParamSet() -> Nid { + Nid(ffi::NID_id_GostR3410_2001_CryptoPro_A_ParamSet) + } + + pub fn id_GostR3410_2001_CryptoPro_B_ParamSet() -> Nid { + Nid(ffi::NID_id_GostR3410_2001_CryptoPro_B_ParamSet) + } + + pub fn id_GostR3410_2001_CryptoPro_C_ParamSet() -> Nid { + Nid(ffi::NID_id_GostR3410_2001_CryptoPro_C_ParamSet) + } + + pub fn id_GostR3410_2001_CryptoPro_XchA_ParamSet() -> Nid { + Nid(ffi::NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet) + } + + pub fn id_GostR3410_2001_CryptoPro_XchB_ParamSet() -> Nid { + Nid(ffi::NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet) + } + + pub fn id_GostR3410_94_a() -> Nid { + Nid(ffi::NID_id_GostR3410_94_a) + } + + pub fn id_GostR3410_94_aBis() -> Nid { + Nid(ffi::NID_id_GostR3410_94_aBis) + } + + pub fn id_GostR3410_94_b() -> Nid { + Nid(ffi::NID_id_GostR3410_94_b) + } + + pub fn id_GostR3410_94_bBis() -> Nid { + Nid(ffi::NID_id_GostR3410_94_bBis) + } + + pub fn id_Gost28147_89_cc() -> Nid { + Nid(ffi::NID_id_Gost28147_89_cc) + } + + pub fn id_GostR3410_94_cc() -> Nid { + Nid(ffi::NID_id_GostR3410_94_cc) + } + + pub fn id_GostR3410_2001_cc() -> Nid { + Nid(ffi::NID_id_GostR3410_2001_cc) + } + + pub fn id_GostR3411_94_with_GostR3410_94_cc() -> Nid { + Nid(ffi::NID_id_GostR3411_94_with_GostR3410_94_cc) + } + + pub fn id_GostR3411_94_with_GostR3410_2001_cc() -> Nid { + Nid(ffi::NID_id_GostR3411_94_with_GostR3410_2001_cc) + } + + pub fn id_GostR3410_2001_ParamSet_cc() -> Nid { + Nid(ffi::NID_id_GostR3410_2001_ParamSet_cc) + } + + pub fn camellia_128_cbc() -> Nid { + Nid(ffi::NID_camellia_128_cbc) + } + + pub fn camellia_192_cbc() -> Nid { + Nid(ffi::NID_camellia_192_cbc) + } + + pub fn camellia_256_cbc() -> Nid { + Nid(ffi::NID_camellia_256_cbc) + } + + pub fn id_camellia128_wrap() -> Nid { + Nid(ffi::NID_id_camellia128_wrap) + } + + pub fn id_camellia192_wrap() -> Nid { + Nid(ffi::NID_id_camellia192_wrap) + } + + pub fn id_camellia256_wrap() -> Nid { + Nid(ffi::NID_id_camellia256_wrap) + } + + pub fn camellia_128_ecb() -> Nid { + Nid(ffi::NID_camellia_128_ecb) + } + + pub fn camellia_128_ofb128() -> Nid { + Nid(ffi::NID_camellia_128_ofb128) + } + + pub fn camellia_128_cfb128() -> Nid { + Nid(ffi::NID_camellia_128_cfb128) + } + + pub fn camellia_192_ecb() -> Nid { + Nid(ffi::NID_camellia_192_ecb) + } + + pub fn camellia_192_ofb128() -> Nid { + Nid(ffi::NID_camellia_192_ofb128) + } + + pub fn camellia_192_cfb128() -> Nid { + Nid(ffi::NID_camellia_192_cfb128) + } + + pub fn camellia_256_ecb() -> Nid { + Nid(ffi::NID_camellia_256_ecb) + } + + pub fn camellia_256_ofb128() -> Nid { + Nid(ffi::NID_camellia_256_ofb128) + } + + pub fn camellia_256_cfb128() -> Nid { + Nid(ffi::NID_camellia_256_cfb128) + } + + pub fn camellia_128_cfb1() -> Nid { + Nid(ffi::NID_camellia_128_cfb1) + } + + pub fn camellia_192_cfb1() -> Nid { + Nid(ffi::NID_camellia_192_cfb1) + } + + pub fn camellia_256_cfb1() -> Nid { + Nid(ffi::NID_camellia_256_cfb1) + } + + pub fn camellia_128_cfb8() -> Nid { + Nid(ffi::NID_camellia_128_cfb8) + } + + pub fn camellia_192_cfb8() -> Nid { + Nid(ffi::NID_camellia_192_cfb8) + } + + pub fn camellia_256_cfb8() -> Nid { + Nid(ffi::NID_camellia_256_cfb8) + } + + pub fn kisa() -> Nid { + Nid(ffi::NID_kisa) + } + + pub fn seed_ecb() -> Nid { + Nid(ffi::NID_seed_ecb) + } + + pub fn seed_cbc() -> Nid { + Nid(ffi::NID_seed_cbc) + } + + pub fn seed_cfb128() -> Nid { + Nid(ffi::NID_seed_cfb128) + } + + pub fn seed_ofb128() -> Nid { + Nid(ffi::NID_seed_ofb128) + } + + pub fn hmac() -> Nid { + Nid(ffi::NID_hmac) + } + + pub fn cmac() -> Nid { + Nid(ffi::NID_cmac) + } + + pub fn rc4_hmac_md5() -> Nid { + Nid(ffi::NID_rc4_hmac_md5) + } + + pub fn aes_128_cbc_hmac_sha1() -> Nid { + Nid(ffi::NID_aes_128_cbc_hmac_sha1) + } + + pub fn aes_192_cbc_hmac_sha1() -> Nid { + Nid(ffi::NID_aes_192_cbc_hmac_sha1) + } + + pub fn aes_256_cbc_hmac_sha1() -> Nid { + Nid(ffi::NID_aes_256_cbc_hmac_sha1) + } + + pub fn aes_128_cbc_hmac_sha256() -> Nid { + Nid(ffi::NID_aes_128_cbc_hmac_sha256) + } + + pub fn aes_192_cbc_hmac_sha256() -> Nid { + Nid(ffi::NID_aes_192_cbc_hmac_sha256) + } + + pub fn aes_256_cbc_hmac_sha256() -> Nid { + Nid(ffi::NID_aes_256_cbc_hmac_sha256) + } + + pub fn dhpublicnumber() -> Nid { + Nid(ffi::NID_dhpublicnumber) + } + + pub fn brainpoolP160r1() -> Nid { + Nid(ffi::NID_brainpoolP160r1) + } + + pub fn brainpoolP160t1() -> Nid { + Nid(ffi::NID_brainpoolP160t1) + } + + pub fn brainpoolP192r1() -> Nid { + Nid(ffi::NID_brainpoolP192r1) + } + + pub fn brainpoolP192t1() -> Nid { + Nid(ffi::NID_brainpoolP192t1) + } + + pub fn brainpoolP224r1() -> Nid { + Nid(ffi::NID_brainpoolP224r1) + } + + pub fn brainpoolP224t1() -> Nid { + Nid(ffi::NID_brainpoolP224t1) + } + + pub fn brainpoolP256r1() -> Nid { + Nid(ffi::NID_brainpoolP256r1) + } + + pub fn brainpoolP256t1() -> Nid { + Nid(ffi::NID_brainpoolP256t1) + } + + pub fn brainpoolP320r1() -> Nid { + Nid(ffi::NID_brainpoolP320r1) + } + + pub fn brainpoolP320t1() -> Nid { + Nid(ffi::NID_brainpoolP320t1) + } + + pub fn brainpoolP384r1() -> Nid { + Nid(ffi::NID_brainpoolP384r1) + } + + pub fn brainpoolP384t1() -> Nid { + Nid(ffi::NID_brainpoolP384t1) + } + + pub fn brainpoolP512r1() -> Nid { + Nid(ffi::NID_brainpoolP512r1) + } + + pub fn brainpoolP512t1() -> Nid { + Nid(ffi::NID_brainpoolP512t1) + } + + pub fn dhSinglePass_stdDH_sha1kdf_scheme() -> Nid { + Nid(ffi::NID_dhSinglePass_stdDH_sha1kdf_scheme) + } + + pub fn dhSinglePass_stdDH_sha224kdf_scheme() -> Nid { + Nid(ffi::NID_dhSinglePass_stdDH_sha224kdf_scheme) + } + + pub fn dhSinglePass_stdDH_sha256kdf_scheme() -> Nid { + Nid(ffi::NID_dhSinglePass_stdDH_sha256kdf_scheme) + } + + pub fn dhSinglePass_stdDH_sha384kdf_scheme() -> Nid { + Nid(ffi::NID_dhSinglePass_stdDH_sha384kdf_scheme) + } + + pub fn dhSinglePass_stdDH_sha512kdf_scheme() -> Nid { + Nid(ffi::NID_dhSinglePass_stdDH_sha512kdf_scheme) + } + + pub fn dhSinglePass_cofactorDH_sha1kdf_scheme() -> Nid { + Nid(ffi::NID_dhSinglePass_cofactorDH_sha1kdf_scheme) + } + + pub fn dhSinglePass_cofactorDH_sha224kdf_scheme() -> Nid { + Nid(ffi::NID_dhSinglePass_cofactorDH_sha224kdf_scheme) + } + + pub fn dhSinglePass_cofactorDH_sha256kdf_scheme() -> Nid { + Nid(ffi::NID_dhSinglePass_cofactorDH_sha256kdf_scheme) + } + + pub fn dhSinglePass_cofactorDH_sha384kdf_scheme() -> Nid { + Nid(ffi::NID_dhSinglePass_cofactorDH_sha384kdf_scheme) + } + + pub fn dhSinglePass_cofactorDH_sha512kdf_scheme() -> Nid { + Nid(ffi::NID_dhSinglePass_cofactorDH_sha512kdf_scheme) + } + + pub fn dh_std_kdf() -> Nid { + Nid(ffi::NID_dh_std_kdf) + } + + pub fn dh_cofactor_kdf() -> Nid { + Nid(ffi::NID_dh_cofactor_kdf) + } + + pub fn ct_precert_scts() -> Nid { + Nid(ffi::NID_ct_precert_scts) + } + + pub fn ct_precert_poison() -> Nid { + Nid(ffi::NID_ct_precert_poison) + } + + pub fn ct_precert_signer() -> Nid { + Nid(ffi::NID_ct_precert_signer) + } + + pub fn ct_cert_scts() -> Nid { + Nid(ffi::NID_ct_cert_scts) + } + + pub fn jurisdictionLocalityName() -> Nid { + Nid(ffi::NID_jurisdictionLocalityName) + } + + pub fn jurisdictionStateOrProvinceName() -> Nid { + Nid(ffi::NID_jurisdictionStateOrProvinceName) + } + + pub fn jurisdictionCountryName() -> Nid { + Nid(ffi::NID_jurisdictionCountryName) + } +} \ No newline at end of file diff --git a/openssl/src/x509/extension.rs b/openssl/src/x509/extension.rs index 99ef62c1..fc6b3c3b 100644 --- a/openssl/src/x509/extension.rs +++ b/openssl/src/x509/extension.rs @@ -71,10 +71,10 @@ impl Extension { impl ExtensionType { pub fn get_nid(&self) -> Option { match self { - &ExtensionType::KeyUsage => Some(Nid::KeyUsage), - &ExtensionType::ExtKeyUsage => Some(Nid::ExtendedKeyUsage), - &ExtensionType::SubjectAltName => Some(Nid::SubjectAltName), - &ExtensionType::IssuerAltName => Some(Nid::IssuerAltName), + &ExtensionType::KeyUsage => Some(Nid::key_usage()), + &ExtensionType::ExtKeyUsage => Some(Nid::ext_key_usage()), + &ExtensionType::SubjectAltName => Some(Nid::subject_alt_name()), + &ExtensionType::IssuerAltName => Some(Nid::issuer_alt_name()), &ExtensionType::OtherNid(nid) => Some(nid), &ExtensionType::OtherStr(_) => None, } diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index dfd61cac..8653b44e 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -257,7 +257,7 @@ impl X509Generator { Some(nid) => { try!(cvt_p(ffi::X509V3_EXT_conf_nid(ptr::null_mut(), mem::transmute(&ctx), - nid as c_int, + nid.as_raw(), value.as_ptr() as *mut c_char))) } None => { @@ -414,7 +414,7 @@ impl X509Ref { pub fn subject_alt_names(&self) -> Option { unsafe { let stack = ffi::X509_get_ext_d2i(self.as_ptr(), - Nid::SubjectAltName as c_int, + ffi::NID_subject_alt_name, ptr::null_mut(), ptr::null_mut()); if stack.is_null() { @@ -553,7 +553,7 @@ impl X509NameRef { pub fn text_by_nid(&self, nid: Nid) -> Option { unsafe { - let loc = ffi::X509_NAME_get_index_by_NID(self.as_ptr(), nid as c_int, -1); + let loc = ffi::X509_NAME_get_index_by_NID(self.as_ptr(), nid.as_raw(), -1); if loc == -1 { return None; } diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index a5eb04e7..2a5d51a2 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -20,7 +20,7 @@ fn get_generator() -> X509Generator { ServerAuth, ExtKeyUsageOption::Other("2.999.1".to_owned())])) .add_extension(SubjectAltName(vec![(SAN::DNS, "example.com".to_owned())])) - .add_extension(OtherNid(Nid::BasicConstraints, "critical,CA:TRUE".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())) } @@ -48,8 +48,8 @@ fn test_cert_gen() { fn test_cert_gen_extension_ordering() { let pkey = pkey(); get_generator() - .add_extension(OtherNid(Nid::SubjectKeyIdentifier, "hash".to_owned())) - .add_extension(OtherNid(Nid::AuthorityKeyIdentifier, "keyid:always".to_owned())) + .add_extension(OtherNid(Nid::subject_key_identifier(), "hash".to_owned())) + .add_extension(OtherNid(Nid::authority_key_identifier(), "keyid:always".to_owned())) .sign(&pkey) .expect("Failed to generate cert with order-dependent extensions"); } @@ -60,9 +60,9 @@ fn test_cert_gen_extension_ordering() { fn test_cert_gen_extension_bad_ordering() { let pkey = pkey(); let result = get_generator() - .add_extension(OtherNid(Nid::AuthorityKeyIdentifier, + .add_extension(OtherNid(Nid::authority_key_identifier(), "keyid:always".to_owned())) - .add_extension(OtherNid(Nid::SubjectKeyIdentifier, "hash".to_owned())) + .add_extension(OtherNid(Nid::subject_key_identifier(), "hash".to_owned())) .sign(&pkey); assert!(result.is_err()); @@ -116,7 +116,7 @@ fn test_subject_read_cn() { let cert = include_bytes!("../../test/cert.pem"); let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); let subject = cert.subject_name(); - let cn = match subject.text_by_nid(Nid::CN) { + let cn = match subject.text_by_nid(Nid::commonName()) { Some(x) => x, None => panic!("Failed to read CN from cert"), }; @@ -130,19 +130,19 @@ fn test_nid_values() { let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); let subject = cert.subject_name(); - let cn = match subject.text_by_nid(Nid::CN) { + let cn = match subject.text_by_nid(Nid::commonName()) { Some(x) => x, None => panic!("Failed to read CN from cert"), }; assert_eq!(&cn as &str, "example.com"); - let email = match subject.text_by_nid(Nid::Email) { + let email = match subject.text_by_nid(Nid::pkcs9_emailAddress()) { Some(x) => x, None => panic!("Failed to read subject email address from cert"), }; assert_eq!(&email as &str, "test@example.com"); - let friendly = match subject.text_by_nid(Nid::FriendlyName) { + let friendly = match subject.text_by_nid(Nid::friendlyName()) { Some(x) => x, None => panic!("Failed to read subject friendly name from cert"), }; @@ -155,7 +155,7 @@ fn test_nid_uid_value() { let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); let subject = cert.subject_name(); - let cn = match subject.text_by_nid(Nid::UserId) { + let cn = match subject.text_by_nid(Nid::userId()) { Some(x) => x, None => panic!("Failed to read UID from cert"), }; From b619c4e88505751e6f57c742a11520e65bcc237d Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 22 Oct 2016 10:16:49 -0700 Subject: [PATCH 081/186] Camel case Dsa --- openssl/src/dsa.rs | 46 ++++++++++++++++++++++----------------------- openssl/src/pkey.rs | 4 ++-- openssl/src/sign.rs | 10 +++++----- 3 files changed, 30 insertions(+), 30 deletions(-) diff --git a/openssl/src/dsa.rs b/openssl/src/dsa.rs index fc005574..46bdfaff 100644 --- a/openssl/src/dsa.rs +++ b/openssl/src/dsa.rs @@ -10,12 +10,12 @@ use bio::{MemBio, MemBioSlice}; use util::{CallbackState, invoke_passwd_cb}; /// Builder for upfront DSA parameter generation -pub struct DSAParams(*mut ffi::DSA); +pub struct DsaParams(*mut ffi::DSA); -impl DSAParams { - pub fn with_size(size: u32) -> Result { +impl DsaParams { + pub fn with_size(size: u32) -> Result { unsafe { - let dsa = DSAParams(try!(cvt_p(ffi::DSA_new()))); + let dsa = DsaParams(try!(cvt_p(ffi::DSA_new()))); try!(cvt(ffi::DSA_generate_parameters_ex(dsa.0, size as c_int, ptr::null(), @@ -28,17 +28,17 @@ impl DSAParams { } /// Generate a key pair from the initialized parameters - pub fn generate(self) -> Result { + pub fn generate(self) -> Result { unsafe { try!(cvt(ffi::DSA_generate_key(self.0))); - let dsa = DSA(self.0); + let dsa = Dsa(self.0); ::std::mem::forget(self); Ok(dsa) } } } -impl Drop for DSAParams { +impl Drop for DsaParams { fn drop(&mut self) { unsafe { ffi::DSA_free(self.0); @@ -46,9 +46,9 @@ impl Drop for DSAParams { } } -pub struct DSA(*mut ffi::DSA); +pub struct Dsa(*mut ffi::DSA); -impl Drop for DSA { +impl Drop for Dsa { fn drop(&mut self) { unsafe { ffi::DSA_free(self.0); @@ -56,20 +56,20 @@ impl Drop for DSA { } } -impl DSA { - pub unsafe fn from_ptr(dsa: *mut ffi::DSA) -> DSA { - DSA(dsa) +impl Dsa { + pub unsafe fn from_ptr(dsa: *mut ffi::DSA) -> Dsa { + Dsa(dsa) } /// Generate a DSA key pair /// For more complicated key generation scenarios see the `DSAParams` type - pub fn generate(size: u32) -> Result { - let params = try!(DSAParams::with_size(size)); + pub fn generate(size: u32) -> Result { + let params = try!(DsaParams::with_size(size)); params.generate() } /// Reads a DSA private key from PEM formatted data. - pub fn private_key_from_pem(buf: &[u8]) -> Result { + pub fn private_key_from_pem(buf: &[u8]) -> Result { ffi::init(); let mem_bio = try!(MemBioSlice::new(buf)); @@ -78,7 +78,7 @@ impl DSA { ptr::null_mut(), None, ptr::null_mut()))); - Ok(DSA(dsa)) + Ok(Dsa(dsa)) } } @@ -87,7 +87,7 @@ impl DSA { /// /// The callback will be passed the password buffer and should return the number of characters /// placed into the buffer. - pub fn private_key_from_pem_cb(buf: &[u8], pass_cb: F) -> Result + pub fn private_key_from_pem_cb(buf: &[u8], pass_cb: F) -> Result where F: FnOnce(&mut [c_char]) -> usize { ffi::init(); @@ -100,7 +100,7 @@ impl DSA { ptr::null_mut(), Some(invoke_passwd_cb::), cb_ptr))); - Ok(DSA(dsa)) + Ok(Dsa(dsa)) } } @@ -120,7 +120,7 @@ impl DSA { } /// Reads an DSA public key from PEM formatted data. - pub fn public_key_from_pem(buf: &[u8]) -> Result + pub fn public_key_from_pem(buf: &[u8]) -> Result { ffi::init(); @@ -130,7 +130,7 @@ impl DSA { ptr::null_mut(), None, ptr::null_mut()))); - Ok(DSA(dsa)) + Ok(Dsa(dsa)) } } @@ -228,7 +228,7 @@ mod compat { } } -impl fmt::Debug for DSA { +impl fmt::Debug for Dsa { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "DSA") } @@ -242,14 +242,14 @@ mod test { #[test] pub fn test_generate() { - DSA::generate(1024).unwrap(); + Dsa::generate(1024).unwrap(); } #[test] pub fn test_password() { let mut password_queried = false; let key = include_bytes!("../test/dsa-encrypted.pem"); - DSA::private_key_from_pem_cb(key, |password| { + Dsa::private_key_from_pem_cb(key, |password| { password_queried = true; password[0] = b'm' as c_char; password[1] = b'y' as c_char; diff --git a/openssl/src/pkey.rs b/openssl/src/pkey.rs index d91acb36..c581c980 100644 --- a/openssl/src/pkey.rs +++ b/openssl/src/pkey.rs @@ -5,7 +5,7 @@ use ffi; use {cvt, cvt_p}; use bio::{MemBio, MemBioSlice}; -use dsa::DSA; +use dsa::Dsa; use rsa::RSA; use error::ErrorStack; use util::{CallbackState, invoke_passwd_cb}; @@ -29,7 +29,7 @@ impl PKey { } /// Create a new `PKey` containing a DSA key. - pub fn from_dsa(dsa: DSA) -> Result { + pub fn from_dsa(dsa: Dsa) -> Result { unsafe { let evp = try!(cvt_p(ffi::EVP_PKEY_new())); let pkey = PKey(evp); diff --git a/openssl/src/sign.rs b/openssl/src/sign.rs index 8fb27427..1fded7d3 100644 --- a/openssl/src/sign.rs +++ b/openssl/src/sign.rs @@ -211,7 +211,7 @@ mod test { use hash::MessageDigest; use sign::{Signer, Verifier}; use rsa::RSA; - use dsa::DSA; + use dsa::Dsa; use pkey::PKey; static INPUT: &'static [u8] = @@ -280,12 +280,12 @@ mod test { let private_key = { let key = include_bytes!("../test/dsa.pem"); - PKey::from_dsa(DSA::private_key_from_pem(key).unwrap()).unwrap() + PKey::from_dsa(Dsa::private_key_from_pem(key).unwrap()).unwrap() }; let public_key = { let key = include_bytes!("../test/dsa.pem.pub"); - PKey::from_dsa(DSA::public_key_from_pem(key).unwrap()).unwrap() + PKey::from_dsa(Dsa::public_key_from_pem(key).unwrap()).unwrap() }; let mut signer = Signer::new(MessageDigest::sha1(), &private_key).unwrap(); @@ -303,12 +303,12 @@ mod test { let private_key = { let key = include_bytes!("../test/dsa.pem"); - PKey::from_dsa(DSA::private_key_from_pem(key).unwrap()).unwrap() + PKey::from_dsa(Dsa::private_key_from_pem(key).unwrap()).unwrap() }; let public_key = { let key = include_bytes!("../test/dsa.pem.pub"); - PKey::from_dsa(DSA::public_key_from_pem(key).unwrap()).unwrap() + PKey::from_dsa(Dsa::public_key_from_pem(key).unwrap()).unwrap() }; let mut signer = Signer::new(MessageDigest::sha1(), &private_key).unwrap(); From 3c50c74444e841c9178758fe18dcef38f56da243 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 22 Oct 2016 10:21:16 -0700 Subject: [PATCH 082/186] Camel case Rsa --- openssl/src/pkey.rs | 10 ++++---- openssl/src/rsa.rs | 50 +++++++++++++++++++-------------------- openssl/src/sign.rs | 8 +++---- openssl/src/x509/tests.rs | 4 ++-- 4 files changed, 36 insertions(+), 36 deletions(-) diff --git a/openssl/src/pkey.rs b/openssl/src/pkey.rs index c581c980..e62bbbd9 100644 --- a/openssl/src/pkey.rs +++ b/openssl/src/pkey.rs @@ -6,7 +6,7 @@ use ffi; use {cvt, cvt_p}; use bio::{MemBio, MemBioSlice}; use dsa::Dsa; -use rsa::RSA; +use rsa::Rsa; use error::ErrorStack; use util::{CallbackState, invoke_passwd_cb}; @@ -18,7 +18,7 @@ unsafe impl Sync for PKey {} /// Represents a public key, optionally with a private key attached. impl PKey { /// Create a new `PKey` containing an RSA key. - pub fn from_rsa(rsa: RSA) -> Result { + pub fn from_rsa(rsa: Rsa) -> Result { unsafe { let evp = try!(cvt_p(ffi::EVP_PKEY_new())); let pkey = PKey(evp); @@ -102,7 +102,7 @@ impl PKey { } /// assign RSA key to this pkey - pub fn set_rsa(&mut self, rsa: &RSA) -> Result<(), ErrorStack> { + pub fn set_rsa(&mut self, rsa: &Rsa) -> Result<(), ErrorStack> { unsafe { // this needs to be a reference as the set1_RSA ups the reference count let rsa_ptr = rsa.as_ptr(); @@ -112,11 +112,11 @@ impl PKey { } /// Get a reference to the interal RSA key for direct access to the key components - pub fn rsa(&self) -> Result { + pub fn rsa(&self) -> Result { unsafe { let rsa = try!(cvt_p(ffi::EVP_PKEY_get1_RSA(self.0))); // this is safe as the ffi increments a reference counter to the internal key - Ok(RSA::from_ptr(rsa)) + Ok(Rsa::from_ptr(rsa)) } } diff --git a/openssl/src/rsa.rs b/openssl/src/rsa.rs index b8702f97..550ce6e4 100644 --- a/openssl/src/rsa.rs +++ b/openssl/src/rsa.rs @@ -28,9 +28,9 @@ impl Padding { } } -pub struct RSA(*mut ffi::RSA); +pub struct Rsa(*mut ffi::RSA); -impl Drop for RSA { +impl Drop for Rsa { fn drop(&mut self) { unsafe { ffi::RSA_free(self.0); @@ -38,12 +38,12 @@ impl Drop for RSA { } } -impl RSA { +impl Rsa { /// only useful for associating the key material directly with the key, it's safer to use /// the supplied load and save methods for DER formatted keys. - pub fn from_public_components(n: BigNum, e: BigNum) -> Result { + pub fn from_public_components(n: BigNum, e: BigNum) -> Result { unsafe { - let rsa = RSA(try!(cvt_p(ffi::RSA_new()))); + let rsa = Rsa(try!(cvt_p(ffi::RSA_new()))); try!(cvt(compat::set_key(rsa.0, n.as_ptr(), e.as_ptr(), @@ -61,9 +61,9 @@ impl RSA { dp: BigNum, dq: BigNum, qi: BigNum) - -> Result { + -> Result { unsafe { - let rsa = RSA(try!(cvt_p(ffi::RSA_new()))); + let rsa = Rsa(try!(cvt_p(ffi::RSA_new()))); try!(cvt(compat::set_key(rsa.0, n.as_ptr(), e.as_ptr(), d.as_ptr()))); mem::forget((n, e, d)); try!(cvt(compat::set_factors(rsa.0, p.as_ptr(), q.as_ptr()))); @@ -75,16 +75,16 @@ impl RSA { } } - pub unsafe fn from_ptr(rsa: *mut ffi::RSA) -> RSA { - RSA(rsa) + pub unsafe fn from_ptr(rsa: *mut ffi::RSA) -> Rsa { + Rsa(rsa) } /// Generates a public/private key pair with the specified size. /// /// The public exponent will be 65537. - pub fn generate(bits: u32) -> Result { + pub fn generate(bits: u32) -> Result { unsafe { - let rsa = RSA(try!(cvt_p(ffi::RSA_new()))); + let rsa = Rsa(try!(cvt_p(ffi::RSA_new()))); let e = try!(BigNum::from_u32(ffi::RSA_F4 as u32)); try!(cvt(ffi::RSA_generate_key_ex(rsa.0, bits as c_int, e.as_ptr(), ptr::null_mut()))); Ok(rsa) @@ -92,19 +92,19 @@ impl RSA { } /// Reads an RSA private key from PEM formatted data. - pub fn private_key_from_pem(buf: &[u8]) -> Result { + pub fn private_key_from_pem(buf: &[u8]) -> Result { let mem_bio = try!(MemBioSlice::new(buf)); unsafe { let rsa = try!(cvt_p(ffi::PEM_read_bio_RSAPrivateKey(mem_bio.as_ptr(), ptr::null_mut(), None, ptr::null_mut()))); - Ok(RSA(rsa)) + Ok(Rsa(rsa)) } } /// Reads an RSA private key from PEM formatted data and supplies a password callback. - pub fn private_key_from_pem_cb(buf: &[u8], pass_cb: F) -> Result + pub fn private_key_from_pem_cb(buf: &[u8], pass_cb: F) -> Result where F: FnOnce(&mut [c_char]) -> usize { let mut cb = CallbackState::new(pass_cb); @@ -116,19 +116,19 @@ impl RSA { ptr::null_mut(), Some(invoke_passwd_cb::), cb_ptr))); - Ok(RSA(rsa)) + Ok(Rsa(rsa)) } } /// Reads an RSA public key from PEM formatted data. - pub fn public_key_from_pem(buf: &[u8]) -> Result { + pub fn public_key_from_pem(buf: &[u8]) -> Result { let mem_bio = try!(MemBioSlice::new(buf)); unsafe { let rsa = try!(cvt_p(ffi::PEM_read_bio_RSA_PUBKEY(mem_bio.as_ptr(), ptr::null_mut(), None, ptr::null_mut()))); - Ok(RSA(rsa)) + Ok(Rsa(rsa)) } } @@ -323,7 +323,7 @@ impl RSA { } } -impl fmt::Debug for RSA { +impl fmt::Debug for Rsa { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "RSA") } @@ -422,7 +422,7 @@ mod test { pub fn test_password() { let mut password_queried = false; let key = include_bytes!("../test/rsa-encrypted.pem"); - RSA::private_key_from_pem_cb(key, |password| { + Rsa::private_key_from_pem_cb(key, |password| { password_queried = true; password[0] = b'm' as c_char; password[1] = b'y' as c_char; @@ -439,7 +439,7 @@ mod test { #[test] pub fn test_public_encrypt_private_decrypt_with_padding() { let key = include_bytes!("../test/rsa.pem.pub"); - let public_key = RSA::public_key_from_pem(key).unwrap(); + let public_key = Rsa::public_key_from_pem(key).unwrap(); let mut result = vec![0; public_key.size()]; let original_data = b"This is test"; @@ -447,7 +447,7 @@ mod test { assert_eq!(len, 256); let pkey = include_bytes!("../test/rsa.pem"); - let private_key = RSA::private_key_from_pem(pkey).unwrap(); + let private_key = Rsa::private_key_from_pem(pkey).unwrap(); let mut dec_result = vec![0; private_key.size()]; let len = private_key.private_decrypt(&result, &mut dec_result, Padding::pkcs1()).unwrap(); @@ -456,9 +456,9 @@ mod test { #[test] fn test_private_encrypt() { - let k0 = super::RSA::generate(512).unwrap(); + let k0 = super::Rsa::generate(512).unwrap(); let k0pkey = k0.public_key_to_pem().unwrap(); - let k1 = super::RSA::public_key_from_pem(&k0pkey).unwrap(); + let k1 = super::Rsa::public_key_from_pem(&k0pkey).unwrap(); let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; @@ -471,9 +471,9 @@ mod test { #[test] fn test_public_encrypt() { - let k0 = super::RSA::generate(512).unwrap(); + let k0 = super::Rsa::generate(512).unwrap(); let k0pkey = k0.private_key_to_pem().unwrap(); - let k1 = super::RSA::private_key_from_pem(&k0pkey).unwrap(); + let k1 = super::Rsa::private_key_from_pem(&k0pkey).unwrap(); let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; diff --git a/openssl/src/sign.rs b/openssl/src/sign.rs index 1fded7d3..2e88f38f 100644 --- a/openssl/src/sign.rs +++ b/openssl/src/sign.rs @@ -210,7 +210,7 @@ mod test { use hash::MessageDigest; use sign::{Signer, Verifier}; - use rsa::RSA; + use rsa::Rsa; use dsa::Dsa; use pkey::PKey; @@ -241,7 +241,7 @@ mod test { #[test] fn rsa_sign() { let key = include_bytes!("../test/rsa.pem"); - let private_key = RSA::private_key_from_pem(key).unwrap(); + let private_key = Rsa::private_key_from_pem(key).unwrap(); let pkey = PKey::from_rsa(private_key).unwrap(); let mut signer = Signer::new(MessageDigest::sha256(), &pkey).unwrap(); @@ -254,7 +254,7 @@ mod test { #[test] fn rsa_verify_ok() { let key = include_bytes!("../test/rsa.pem"); - let private_key = RSA::private_key_from_pem(key).unwrap(); + let private_key = Rsa::private_key_from_pem(key).unwrap(); let pkey = PKey::from_rsa(private_key).unwrap(); let mut verifier = Verifier::new(MessageDigest::sha256(), &pkey).unwrap(); @@ -265,7 +265,7 @@ mod test { #[test] fn rsa_verify_invalid() { let key = include_bytes!("../test/rsa.pem"); - let private_key = RSA::private_key_from_pem(key).unwrap(); + let private_key = Rsa::private_key_from_pem(key).unwrap(); let pkey = PKey::from_rsa(private_key).unwrap(); let mut verifier = Verifier::new(MessageDigest::sha256(), &pkey).unwrap(); diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index 2a5d51a2..c0c7ce87 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -2,7 +2,7 @@ use serialize::hex::FromHex; use hash::MessageDigest; use pkey::PKey; -use rsa::RSA; +use rsa::Rsa; use x509::{X509, X509Generator}; use x509::extension::Extension::{KeyUsage, ExtKeyUsage, SubjectAltName, OtherNid, OtherStr}; use x509::extension::AltNameOption as SAN; @@ -25,7 +25,7 @@ fn get_generator() -> X509Generator { } fn pkey() -> PKey { - let rsa = RSA::generate(2048).unwrap(); + let rsa = Rsa::generate(2048).unwrap(); PKey::from_rsa(rsa).unwrap() } From 787cad3c8225b0c09135305477d5a962fc64d9bb Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 22 Oct 2016 15:58:06 -0700 Subject: [PATCH 083/186] Use constants rather than constructors for Nid --- openssl/src/memcmp.rs | 2 +- openssl/src/nid.rs | 4758 +++++++-------------------------- openssl/src/x509/extension.rs | 10 +- openssl/src/x509/tests.rs | 22 +- 4 files changed, 970 insertions(+), 3822 deletions(-) diff --git a/openssl/src/memcmp.rs b/openssl/src/memcmp.rs index cf08bdb5..0a7124bd 100644 --- a/openssl/src/memcmp.rs +++ b/openssl/src/memcmp.rs @@ -6,7 +6,7 @@ use ffi; /// This operation takes an amount of time dependent on the length of the two /// arrays given, but is independent of the contents of a and b. /// -/// # Failure +/// # Panics /// /// This function will panic the current task if `a` and `b` do not have the same /// length. diff --git a/openssl/src/nid.rs b/openssl/src/nid.rs index abc377da..480aa91a 100644 --- a/openssl/src/nid.rs +++ b/openssl/src/nid.rs @@ -13,3808 +13,956 @@ impl Nid { pub fn as_raw(&self) -> c_int { self.0 } - - pub fn undef() -> Nid { - Nid(ffi::NID_undef) - } - - pub fn itu_t() -> Nid { - Nid(ffi::NID_itu_t) - } - - pub fn ccitt() -> Nid { - Nid(ffi::NID_ccitt) - } - - pub fn iso() -> Nid { - Nid(ffi::NID_iso) - } - - pub fn joint_iso_itu_t() -> Nid { - Nid(ffi::NID_joint_iso_itu_t) - } - - pub fn joint_iso_ccitt() -> Nid { - Nid(ffi::NID_joint_iso_ccitt) - } - - pub fn member_body() -> Nid { - Nid(ffi::NID_member_body) - } - - pub fn identified_organization() -> Nid { - Nid(ffi::NID_identified_organization) - } - - pub fn hmac_md5() -> Nid { - Nid(ffi::NID_hmac_md5) - } - - pub fn hmac_sha1() -> Nid { - Nid(ffi::NID_hmac_sha1) - } - - pub fn certicom_arc() -> Nid { - Nid(ffi::NID_certicom_arc) - } - - pub fn international_organizations() -> Nid { - Nid(ffi::NID_international_organizations) - } - - pub fn wap() -> Nid { - Nid(ffi::NID_wap) - } - - pub fn wap_wsg() -> Nid { - Nid(ffi::NID_wap_wsg) - } - - pub fn selected_attribute_types() -> Nid { - Nid(ffi::NID_selected_attribute_types) - } - - pub fn clearance() -> Nid { - Nid(ffi::NID_clearance) - } - - pub fn ISO_US() -> Nid { - Nid(ffi::NID_ISO_US) - } - - pub fn X9_57() -> Nid { - Nid(ffi::NID_X9_57) - } - - pub fn X9cm() -> Nid { - Nid(ffi::NID_X9cm) - } - - pub fn dsa() -> Nid { - Nid(ffi::NID_dsa) - } - - pub fn dsaWithSHA1() -> Nid { - Nid(ffi::NID_dsaWithSHA1) - } - - pub fn ansi_X9_62() -> Nid { - Nid(ffi::NID_ansi_X9_62) - } - - pub fn X9_62_prime_field() -> Nid { - Nid(ffi::NID_X9_62_prime_field) - } - - pub fn X9_62_characteristic_two_field() -> Nid { - Nid(ffi::NID_X9_62_characteristic_two_field) - } - - pub fn X9_62_id_characteristic_two_basis() -> Nid { - Nid(ffi::NID_X9_62_id_characteristic_two_basis) - } - - pub fn X9_62_onBasis() -> Nid { - Nid(ffi::NID_X9_62_onBasis) - } - - pub fn X9_62_tpBasis() -> Nid { - Nid(ffi::NID_X9_62_tpBasis) - } - - pub fn X9_62_ppBasis() -> Nid { - Nid(ffi::NID_X9_62_ppBasis) - } - - pub fn X9_62_id_ecPublicKey() -> Nid { - Nid(ffi::NID_X9_62_id_ecPublicKey) - } - - pub fn X9_62_c2pnb163v1() -> Nid { - Nid(ffi::NID_X9_62_c2pnb163v1) - } - - pub fn X9_62_c2pnb163v2() -> Nid { - Nid(ffi::NID_X9_62_c2pnb163v2) - } - - pub fn X9_62_c2pnb163v3() -> Nid { - Nid(ffi::NID_X9_62_c2pnb163v3) - } - - pub fn X9_62_c2pnb176v1() -> Nid { - Nid(ffi::NID_X9_62_c2pnb176v1) - } - - pub fn X9_62_c2tnb191v1() -> Nid { - Nid(ffi::NID_X9_62_c2tnb191v1) - } - - pub fn X9_62_c2tnb191v2() -> Nid { - Nid(ffi::NID_X9_62_c2tnb191v2) - } - - pub fn X9_62_c2tnb191v3() -> Nid { - Nid(ffi::NID_X9_62_c2tnb191v3) - } - - pub fn X9_62_c2onb191v4() -> Nid { - Nid(ffi::NID_X9_62_c2onb191v4) - } - - pub fn X9_62_c2onb191v5() -> Nid { - Nid(ffi::NID_X9_62_c2onb191v5) - } - - pub fn X9_62_c2pnb208w1() -> Nid { - Nid(ffi::NID_X9_62_c2pnb208w1) - } - - pub fn X9_62_c2tnb239v1() -> Nid { - Nid(ffi::NID_X9_62_c2tnb239v1) - } - - pub fn X9_62_c2tnb239v2() -> Nid { - Nid(ffi::NID_X9_62_c2tnb239v2) - } - - pub fn X9_62_c2tnb239v3() -> Nid { - Nid(ffi::NID_X9_62_c2tnb239v3) - } - - pub fn X9_62_c2onb239v4() -> Nid { - Nid(ffi::NID_X9_62_c2onb239v4) - } - - pub fn X9_62_c2onb239v5() -> Nid { - Nid(ffi::NID_X9_62_c2onb239v5) - } - - pub fn X9_62_c2pnb272w1() -> Nid { - Nid(ffi::NID_X9_62_c2pnb272w1) - } - - pub fn X9_62_c2pnb304w1() -> Nid { - Nid(ffi::NID_X9_62_c2pnb304w1) - } - - pub fn X9_62_c2tnb359v1() -> Nid { - Nid(ffi::NID_X9_62_c2tnb359v1) - } - - pub fn X9_62_c2pnb368w1() -> Nid { - Nid(ffi::NID_X9_62_c2pnb368w1) - } - - pub fn X9_62_c2tnb431r1() -> Nid { - Nid(ffi::NID_X9_62_c2tnb431r1) - } - - pub fn X9_62_prime192v1() -> Nid { - Nid(ffi::NID_X9_62_prime192v1) - } - - pub fn X9_62_prime192v2() -> Nid { - Nid(ffi::NID_X9_62_prime192v2) - } - - pub fn X9_62_prime192v3() -> Nid { - Nid(ffi::NID_X9_62_prime192v3) - } - - pub fn X9_62_prime239v1() -> Nid { - Nid(ffi::NID_X9_62_prime239v1) - } - - pub fn X9_62_prime239v2() -> Nid { - Nid(ffi::NID_X9_62_prime239v2) - } - - pub fn X9_62_prime239v3() -> Nid { - Nid(ffi::NID_X9_62_prime239v3) - } - - pub fn X9_62_prime256v1() -> Nid { - Nid(ffi::NID_X9_62_prime256v1) - } - - pub fn ecdsa_with_SHA1() -> Nid { - Nid(ffi::NID_ecdsa_with_SHA1) - } - - pub fn ecdsa_with_Recommended() -> Nid { - Nid(ffi::NID_ecdsa_with_Recommended) - } - - pub fn ecdsa_with_Specified() -> Nid { - Nid(ffi::NID_ecdsa_with_Specified) - } - - pub fn ecdsa_with_SHA224() -> Nid { - Nid(ffi::NID_ecdsa_with_SHA224) - } - - pub fn ecdsa_with_SHA256() -> Nid { - Nid(ffi::NID_ecdsa_with_SHA256) - } - - pub fn ecdsa_with_SHA384() -> Nid { - Nid(ffi::NID_ecdsa_with_SHA384) - } - - pub fn ecdsa_with_SHA512() -> Nid { - Nid(ffi::NID_ecdsa_with_SHA512) - } - - pub fn secp112r1() -> Nid { - Nid(ffi::NID_secp112r1) - } - - pub fn secp112r2() -> Nid { - Nid(ffi::NID_secp112r2) - } - - pub fn secp128r1() -> Nid { - Nid(ffi::NID_secp128r1) - } - - pub fn secp128r2() -> Nid { - Nid(ffi::NID_secp128r2) - } - - pub fn secp160k1() -> Nid { - Nid(ffi::NID_secp160k1) - } - - pub fn secp160r1() -> Nid { - Nid(ffi::NID_secp160r1) - } - - pub fn secp160r2() -> Nid { - Nid(ffi::NID_secp160r2) - } - - pub fn secp192k1() -> Nid { - Nid(ffi::NID_secp192k1) - } - - pub fn secp224k1() -> Nid { - Nid(ffi::NID_secp224k1) - } - - pub fn secp224r1() -> Nid { - Nid(ffi::NID_secp224r1) - } - - pub fn secp256k1() -> Nid { - Nid(ffi::NID_secp256k1) - } - - pub fn secp384r1() -> Nid { - Nid(ffi::NID_secp384r1) - } - - pub fn secp521r1() -> Nid { - Nid(ffi::NID_secp521r1) - } - - pub fn sect113r1() -> Nid { - Nid(ffi::NID_sect113r1) - } - - pub fn sect113r2() -> Nid { - Nid(ffi::NID_sect113r2) - } - - pub fn sect131r1() -> Nid { - Nid(ffi::NID_sect131r1) - } - - pub fn sect131r2() -> Nid { - Nid(ffi::NID_sect131r2) - } - - pub fn sect163k1() -> Nid { - Nid(ffi::NID_sect163k1) - } - - pub fn sect163r1() -> Nid { - Nid(ffi::NID_sect163r1) - } - - pub fn sect163r2() -> Nid { - Nid(ffi::NID_sect163r2) - } - - pub fn sect193r1() -> Nid { - Nid(ffi::NID_sect193r1) - } - - pub fn sect193r2() -> Nid { - Nid(ffi::NID_sect193r2) - } - - pub fn sect233k1() -> Nid { - Nid(ffi::NID_sect233k1) - } - - pub fn sect233r1() -> Nid { - Nid(ffi::NID_sect233r1) - } - - pub fn sect239k1() -> Nid { - Nid(ffi::NID_sect239k1) - } - - pub fn sect283k1() -> Nid { - Nid(ffi::NID_sect283k1) - } - - pub fn sect283r1() -> Nid { - Nid(ffi::NID_sect283r1) - } - - pub fn sect409k1() -> Nid { - Nid(ffi::NID_sect409k1) - } - - pub fn sect409r1() -> Nid { - Nid(ffi::NID_sect409r1) - } - - pub fn sect571k1() -> Nid { - Nid(ffi::NID_sect571k1) - } - - pub fn sect571r1() -> Nid { - Nid(ffi::NID_sect571r1) - } - - pub fn wap_wsg_idm_ecid_wtls1() -> Nid { - Nid(ffi::NID_wap_wsg_idm_ecid_wtls1) - } - - pub fn wap_wsg_idm_ecid_wtls3() -> Nid { - Nid(ffi::NID_wap_wsg_idm_ecid_wtls3) - } - - pub fn wap_wsg_idm_ecid_wtls4() -> Nid { - Nid(ffi::NID_wap_wsg_idm_ecid_wtls4) - } - - pub fn wap_wsg_idm_ecid_wtls5() -> Nid { - Nid(ffi::NID_wap_wsg_idm_ecid_wtls5) - } - - pub fn wap_wsg_idm_ecid_wtls6() -> Nid { - Nid(ffi::NID_wap_wsg_idm_ecid_wtls6) - } - - pub fn wap_wsg_idm_ecid_wtls7() -> Nid { - Nid(ffi::NID_wap_wsg_idm_ecid_wtls7) - } - - pub fn wap_wsg_idm_ecid_wtls8() -> Nid { - Nid(ffi::NID_wap_wsg_idm_ecid_wtls8) - } - - pub fn wap_wsg_idm_ecid_wtls9() -> Nid { - Nid(ffi::NID_wap_wsg_idm_ecid_wtls9) - } - - pub fn wap_wsg_idm_ecid_wtls10() -> Nid { - Nid(ffi::NID_wap_wsg_idm_ecid_wtls10) - } - - pub fn wap_wsg_idm_ecid_wtls11() -> Nid { - Nid(ffi::NID_wap_wsg_idm_ecid_wtls11) - } - - pub fn wap_wsg_idm_ecid_wtls12() -> Nid { - Nid(ffi::NID_wap_wsg_idm_ecid_wtls12) - } - - pub fn cast5_cbc() -> Nid { - Nid(ffi::NID_cast5_cbc) - } - - pub fn cast5_ecb() -> Nid { - Nid(ffi::NID_cast5_ecb) - } - - pub fn cast5_cfb64() -> Nid { - Nid(ffi::NID_cast5_cfb64) - } - - pub fn cast5_ofb64() -> Nid { - Nid(ffi::NID_cast5_ofb64) - } - - pub fn pbeWithMD5AndCast5_CBC() -> Nid { - Nid(ffi::NID_pbeWithMD5AndCast5_CBC) - } - - pub fn id_PasswordBasedMAC() -> Nid { - Nid(ffi::NID_id_PasswordBasedMAC) - } - - pub fn id_DHBasedMac() -> Nid { - Nid(ffi::NID_id_DHBasedMac) - } - - pub fn rsadsi() -> Nid { - Nid(ffi::NID_rsadsi) - } - - pub fn pkcs() -> Nid { - Nid(ffi::NID_pkcs) - } - - pub fn pkcs1() -> Nid { - Nid(ffi::NID_pkcs1) - } - - pub fn rsaEncryption() -> Nid { - Nid(ffi::NID_rsaEncryption) - } - - pub fn md2WithRSAEncryption() -> Nid { - Nid(ffi::NID_md2WithRSAEncryption) - } - - pub fn md4WithRSAEncryption() -> Nid { - Nid(ffi::NID_md4WithRSAEncryption) - } - - pub fn md5WithRSAEncryption() -> Nid { - Nid(ffi::NID_md5WithRSAEncryption) - } - - pub fn sha1WithRSAEncryption() -> Nid { - Nid(ffi::NID_sha1WithRSAEncryption) - } - - pub fn rsaesOaep() -> Nid { - Nid(ffi::NID_rsaesOaep) - } - - pub fn mgf1() -> Nid { - Nid(ffi::NID_mgf1) - } - - pub fn pSpecified() -> Nid { - Nid(ffi::NID_pSpecified) - } - - pub fn rsassaPss() -> Nid { - Nid(ffi::NID_rsassaPss) - } - - pub fn sha256WithRSAEncryption() -> Nid { - Nid(ffi::NID_sha256WithRSAEncryption) - } - - pub fn sha384WithRSAEncryption() -> Nid { - Nid(ffi::NID_sha384WithRSAEncryption) - } - - pub fn sha512WithRSAEncryption() -> Nid { - Nid(ffi::NID_sha512WithRSAEncryption) - } - - pub fn sha224WithRSAEncryption() -> Nid { - Nid(ffi::NID_sha224WithRSAEncryption) - } - - pub fn pkcs3() -> Nid { - Nid(ffi::NID_pkcs3) - } - - pub fn dhKeyAgreement() -> Nid { - Nid(ffi::NID_dhKeyAgreement) - } - - pub fn pkcs5() -> Nid { - Nid(ffi::NID_pkcs5) - } - - pub fn pbeWithMD2AndDES_CBC() -> Nid { - Nid(ffi::NID_pbeWithMD2AndDES_CBC) - } - - pub fn pbeWithMD5AndDES_CBC() -> Nid { - Nid(ffi::NID_pbeWithMD5AndDES_CBC) - } - - pub fn pbeWithMD2AndRC2_CBC() -> Nid { - Nid(ffi::NID_pbeWithMD2AndRC2_CBC) - } - - pub fn pbeWithMD5AndRC2_CBC() -> Nid { - Nid(ffi::NID_pbeWithMD5AndRC2_CBC) - } - - pub fn pbeWithSHA1AndDES_CBC() -> Nid { - Nid(ffi::NID_pbeWithSHA1AndDES_CBC) - } - - pub fn pbeWithSHA1AndRC2_CBC() -> Nid { - Nid(ffi::NID_pbeWithSHA1AndRC2_CBC) - } - - pub fn id_pbkdf2() -> Nid { - Nid(ffi::NID_id_pbkdf2) - } - - pub fn pbes2() -> Nid { - Nid(ffi::NID_pbes2) - } - - pub fn pbmac1() -> Nid { - Nid(ffi::NID_pbmac1) - } - - pub fn pkcs7() -> Nid { - Nid(ffi::NID_pkcs7) - } - - pub fn pkcs7_data() -> Nid { - Nid(ffi::NID_pkcs7_data) - } - - pub fn pkcs7_signed() -> Nid { - Nid(ffi::NID_pkcs7_signed) - } - - pub fn pkcs7_enveloped() -> Nid { - Nid(ffi::NID_pkcs7_enveloped) - } - - pub fn pkcs7_signedAndEnveloped() -> Nid { - Nid(ffi::NID_pkcs7_signedAndEnveloped) - } - - pub fn pkcs7_digest() -> Nid { - Nid(ffi::NID_pkcs7_digest) - } - - pub fn pkcs7_encrypted() -> Nid { - Nid(ffi::NID_pkcs7_encrypted) - } - - pub fn pkcs9() -> Nid { - Nid(ffi::NID_pkcs9) - } - - pub fn pkcs9_emailAddress() -> Nid { - Nid(ffi::NID_pkcs9_emailAddress) - } - - pub fn pkcs9_unstructuredName() -> Nid { - Nid(ffi::NID_pkcs9_unstructuredName) - } - - pub fn pkcs9_contentType() -> Nid { - Nid(ffi::NID_pkcs9_contentType) - } - - pub fn pkcs9_messageDigest() -> Nid { - Nid(ffi::NID_pkcs9_messageDigest) - } - - pub fn pkcs9_signingTime() -> Nid { - Nid(ffi::NID_pkcs9_signingTime) - } - - pub fn pkcs9_countersignature() -> Nid { - Nid(ffi::NID_pkcs9_countersignature) - } - - pub fn pkcs9_challengePassword() -> Nid { - Nid(ffi::NID_pkcs9_challengePassword) - } - - pub fn pkcs9_unstructuredAddress() -> Nid { - Nid(ffi::NID_pkcs9_unstructuredAddress) - } - - pub fn pkcs9_extCertAttributes() -> Nid { - Nid(ffi::NID_pkcs9_extCertAttributes) - } - - pub fn ext_req() -> Nid { - Nid(ffi::NID_ext_req) - } - - pub fn SMIMECapabilities() -> Nid { - Nid(ffi::NID_SMIMECapabilities) - } - - pub fn SMIME() -> Nid { - Nid(ffi::NID_SMIME) - } - - pub fn id_smime_mod() -> Nid { - Nid(ffi::NID_id_smime_mod) - } - - pub fn id_smime_ct() -> Nid { - Nid(ffi::NID_id_smime_ct) - } - - pub fn id_smime_aa() -> Nid { - Nid(ffi::NID_id_smime_aa) - } - - pub fn id_smime_alg() -> Nid { - Nid(ffi::NID_id_smime_alg) - } - - pub fn id_smime_cd() -> Nid { - Nid(ffi::NID_id_smime_cd) - } - - pub fn id_smime_spq() -> Nid { - Nid(ffi::NID_id_smime_spq) - } - - pub fn id_smime_cti() -> Nid { - Nid(ffi::NID_id_smime_cti) - } - - pub fn id_smime_mod_cms() -> Nid { - Nid(ffi::NID_id_smime_mod_cms) - } - - pub fn id_smime_mod_ess() -> Nid { - Nid(ffi::NID_id_smime_mod_ess) - } - - pub fn id_smime_mod_oid() -> Nid { - Nid(ffi::NID_id_smime_mod_oid) - } - - pub fn id_smime_mod_msg_v3() -> Nid { - Nid(ffi::NID_id_smime_mod_msg_v3) - } - - pub fn id_smime_mod_ets_eSignature_88() -> Nid { - Nid(ffi::NID_id_smime_mod_ets_eSignature_88) - } - - pub fn id_smime_mod_ets_eSignature_97() -> Nid { - Nid(ffi::NID_id_smime_mod_ets_eSignature_97) - } - - pub fn id_smime_mod_ets_eSigPolicy_88() -> Nid { - Nid(ffi::NID_id_smime_mod_ets_eSigPolicy_88) - } - - pub fn id_smime_mod_ets_eSigPolicy_97() -> Nid { - Nid(ffi::NID_id_smime_mod_ets_eSigPolicy_97) - } - - pub fn id_smime_ct_receipt() -> Nid { - Nid(ffi::NID_id_smime_ct_receipt) - } - - pub fn id_smime_ct_authData() -> Nid { - Nid(ffi::NID_id_smime_ct_authData) - } - - pub fn id_smime_ct_publishCert() -> Nid { - Nid(ffi::NID_id_smime_ct_publishCert) - } - - pub fn id_smime_ct_TSTInfo() -> Nid { - Nid(ffi::NID_id_smime_ct_TSTInfo) - } - - pub fn id_smime_ct_TDTInfo() -> Nid { - Nid(ffi::NID_id_smime_ct_TDTInfo) - } - - pub fn id_smime_ct_contentInfo() -> Nid { - Nid(ffi::NID_id_smime_ct_contentInfo) - } - - pub fn id_smime_ct_DVCSRequestData() -> Nid { - Nid(ffi::NID_id_smime_ct_DVCSRequestData) - } - - pub fn id_smime_ct_DVCSResponseData() -> Nid { - Nid(ffi::NID_id_smime_ct_DVCSResponseData) - } - - pub fn id_smime_ct_compressedData() -> Nid { - Nid(ffi::NID_id_smime_ct_compressedData) - } - - pub fn id_ct_asciiTextWithCRLF() -> Nid { - Nid(ffi::NID_id_ct_asciiTextWithCRLF) - } - - pub fn id_smime_aa_receiptRequest() -> Nid { - Nid(ffi::NID_id_smime_aa_receiptRequest) - } - - pub fn id_smime_aa_securityLabel() -> Nid { - Nid(ffi::NID_id_smime_aa_securityLabel) - } - - pub fn id_smime_aa_mlExpandHistory() -> Nid { - Nid(ffi::NID_id_smime_aa_mlExpandHistory) - } - - pub fn id_smime_aa_contentHint() -> Nid { - Nid(ffi::NID_id_smime_aa_contentHint) - } - - pub fn id_smime_aa_msgSigDigest() -> Nid { - Nid(ffi::NID_id_smime_aa_msgSigDigest) - } - - pub fn id_smime_aa_encapContentType() -> Nid { - Nid(ffi::NID_id_smime_aa_encapContentType) - } - - pub fn id_smime_aa_contentIdentifier() -> Nid { - Nid(ffi::NID_id_smime_aa_contentIdentifier) - } - - pub fn id_smime_aa_macValue() -> Nid { - Nid(ffi::NID_id_smime_aa_macValue) - } - - pub fn id_smime_aa_equivalentLabels() -> Nid { - Nid(ffi::NID_id_smime_aa_equivalentLabels) - } - - pub fn id_smime_aa_contentReference() -> Nid { - Nid(ffi::NID_id_smime_aa_contentReference) - } - - pub fn id_smime_aa_encrypKeyPref() -> Nid { - Nid(ffi::NID_id_smime_aa_encrypKeyPref) - } - - pub fn id_smime_aa_signingCertificate() -> Nid { - Nid(ffi::NID_id_smime_aa_signingCertificate) - } - - pub fn id_smime_aa_smimeEncryptCerts() -> Nid { - Nid(ffi::NID_id_smime_aa_smimeEncryptCerts) - } - - pub fn id_smime_aa_timeStampToken() -> Nid { - Nid(ffi::NID_id_smime_aa_timeStampToken) - } - - pub fn id_smime_aa_ets_sigPolicyId() -> Nid { - Nid(ffi::NID_id_smime_aa_ets_sigPolicyId) - } - - pub fn id_smime_aa_ets_commitmentType() -> Nid { - Nid(ffi::NID_id_smime_aa_ets_commitmentType) - } - - pub fn id_smime_aa_ets_signerLocation() -> Nid { - Nid(ffi::NID_id_smime_aa_ets_signerLocation) - } - - pub fn id_smime_aa_ets_signerAttr() -> Nid { - Nid(ffi::NID_id_smime_aa_ets_signerAttr) - } - - pub fn id_smime_aa_ets_otherSigCert() -> Nid { - Nid(ffi::NID_id_smime_aa_ets_otherSigCert) - } - - pub fn id_smime_aa_ets_contentTimestamp() -> Nid { - Nid(ffi::NID_id_smime_aa_ets_contentTimestamp) - } - - pub fn id_smime_aa_ets_CertificateRefs() -> Nid { - Nid(ffi::NID_id_smime_aa_ets_CertificateRefs) - } - - pub fn id_smime_aa_ets_RevocationRefs() -> Nid { - Nid(ffi::NID_id_smime_aa_ets_RevocationRefs) - } - - pub fn id_smime_aa_ets_certValues() -> Nid { - Nid(ffi::NID_id_smime_aa_ets_certValues) - } - - pub fn id_smime_aa_ets_revocationValues() -> Nid { - Nid(ffi::NID_id_smime_aa_ets_revocationValues) - } - - pub fn id_smime_aa_ets_escTimeStamp() -> Nid { - Nid(ffi::NID_id_smime_aa_ets_escTimeStamp) - } - - pub fn id_smime_aa_ets_certCRLTimestamp() -> Nid { - Nid(ffi::NID_id_smime_aa_ets_certCRLTimestamp) - } - - pub fn id_smime_aa_ets_archiveTimeStamp() -> Nid { - Nid(ffi::NID_id_smime_aa_ets_archiveTimeStamp) - } - - pub fn id_smime_aa_signatureType() -> Nid { - Nid(ffi::NID_id_smime_aa_signatureType) - } - - pub fn id_smime_aa_dvcs_dvc() -> Nid { - Nid(ffi::NID_id_smime_aa_dvcs_dvc) - } - - pub fn id_smime_alg_ESDHwith3DES() -> Nid { - Nid(ffi::NID_id_smime_alg_ESDHwith3DES) - } - - pub fn id_smime_alg_ESDHwithRC2() -> Nid { - Nid(ffi::NID_id_smime_alg_ESDHwithRC2) - } - - pub fn id_smime_alg_3DESwrap() -> Nid { - Nid(ffi::NID_id_smime_alg_3DESwrap) - } - - pub fn id_smime_alg_RC2wrap() -> Nid { - Nid(ffi::NID_id_smime_alg_RC2wrap) - } - - pub fn id_smime_alg_ESDH() -> Nid { - Nid(ffi::NID_id_smime_alg_ESDH) - } - - pub fn id_smime_alg_CMS3DESwrap() -> Nid { - Nid(ffi::NID_id_smime_alg_CMS3DESwrap) - } - - pub fn id_smime_alg_CMSRC2wrap() -> Nid { - Nid(ffi::NID_id_smime_alg_CMSRC2wrap) - } - - pub fn id_alg_PWRI_KEK() -> Nid { - Nid(ffi::NID_id_alg_PWRI_KEK) - } - - pub fn id_smime_cd_ldap() -> Nid { - Nid(ffi::NID_id_smime_cd_ldap) - } - - pub fn id_smime_spq_ets_sqt_uri() -> Nid { - Nid(ffi::NID_id_smime_spq_ets_sqt_uri) - } - - pub fn id_smime_spq_ets_sqt_unotice() -> Nid { - Nid(ffi::NID_id_smime_spq_ets_sqt_unotice) - } - - pub fn id_smime_cti_ets_proofOfOrigin() -> Nid { - Nid(ffi::NID_id_smime_cti_ets_proofOfOrigin) - } - - pub fn id_smime_cti_ets_proofOfReceipt() -> Nid { - Nid(ffi::NID_id_smime_cti_ets_proofOfReceipt) - } - - pub fn id_smime_cti_ets_proofOfDelivery() -> Nid { - Nid(ffi::NID_id_smime_cti_ets_proofOfDelivery) - } - - pub fn id_smime_cti_ets_proofOfSender() -> Nid { - Nid(ffi::NID_id_smime_cti_ets_proofOfSender) - } - - pub fn id_smime_cti_ets_proofOfApproval() -> Nid { - Nid(ffi::NID_id_smime_cti_ets_proofOfApproval) - } - - pub fn id_smime_cti_ets_proofOfCreation() -> Nid { - Nid(ffi::NID_id_smime_cti_ets_proofOfCreation) - } - - pub fn friendlyName() -> Nid { - Nid(ffi::NID_friendlyName) - } - - pub fn localKeyID() -> Nid { - Nid(ffi::NID_localKeyID) - } - - pub fn ms_csp_name() -> Nid { - Nid(ffi::NID_ms_csp_name) - } - - pub fn LocalKeySet() -> Nid { - Nid(ffi::NID_LocalKeySet) - } - - pub fn x509Certificate() -> Nid { - Nid(ffi::NID_x509Certificate) - } - - pub fn sdsiCertificate() -> Nid { - Nid(ffi::NID_sdsiCertificate) - } - - pub fn x509Crl() -> Nid { - Nid(ffi::NID_x509Crl) - } - - pub fn pbe_WithSHA1And128BitRC4() -> Nid { - Nid(ffi::NID_pbe_WithSHA1And128BitRC4) - } - - pub fn pbe_WithSHA1And40BitRC4() -> Nid { - Nid(ffi::NID_pbe_WithSHA1And40BitRC4) - } - - pub fn pbe_WithSHA1And3_Key_TripleDES_CBC() -> Nid { - Nid(ffi::NID_pbe_WithSHA1And3_Key_TripleDES_CBC) - } - - pub fn pbe_WithSHA1And2_Key_TripleDES_CBC() -> Nid { - Nid(ffi::NID_pbe_WithSHA1And2_Key_TripleDES_CBC) - } - - pub fn pbe_WithSHA1And128BitRC2_CBC() -> Nid { - Nid(ffi::NID_pbe_WithSHA1And128BitRC2_CBC) - } - - pub fn pbe_WithSHA1And40BitRC2_CBC() -> Nid { - Nid(ffi::NID_pbe_WithSHA1And40BitRC2_CBC) - } - - pub fn keyBag() -> Nid { - Nid(ffi::NID_keyBag) - } - - pub fn pkcs8ShroudedKeyBag() -> Nid { - Nid(ffi::NID_pkcs8ShroudedKeyBag) - } - - pub fn certBag() -> Nid { - Nid(ffi::NID_certBag) - } - - pub fn crlBag() -> Nid { - Nid(ffi::NID_crlBag) - } - - pub fn secretBag() -> Nid { - Nid(ffi::NID_secretBag) - } - - pub fn safeContentsBag() -> Nid { - Nid(ffi::NID_safeContentsBag) - } - - pub fn md2() -> Nid { - Nid(ffi::NID_md2) - } - - pub fn md4() -> Nid { - Nid(ffi::NID_md4) - } - - pub fn md5() -> Nid { - Nid(ffi::NID_md5) - } - - pub fn md5_sha1() -> Nid { - Nid(ffi::NID_md5_sha1) - } - - pub fn hmacWithMD5() -> Nid { - Nid(ffi::NID_hmacWithMD5) - } - - pub fn hmacWithSHA1() -> Nid { - Nid(ffi::NID_hmacWithSHA1) - } - - pub fn hmacWithSHA224() -> Nid { - Nid(ffi::NID_hmacWithSHA224) - } - - pub fn hmacWithSHA256() -> Nid { - Nid(ffi::NID_hmacWithSHA256) - } - - pub fn hmacWithSHA384() -> Nid { - Nid(ffi::NID_hmacWithSHA384) - } - - pub fn hmacWithSHA512() -> Nid { - Nid(ffi::NID_hmacWithSHA512) - } - - pub fn rc2_cbc() -> Nid { - Nid(ffi::NID_rc2_cbc) - } - - pub fn rc2_ecb() -> Nid { - Nid(ffi::NID_rc2_ecb) - } - - pub fn rc2_cfb64() -> Nid { - Nid(ffi::NID_rc2_cfb64) - } - - pub fn rc2_ofb64() -> Nid { - Nid(ffi::NID_rc2_ofb64) - } - - pub fn rc2_40_cbc() -> Nid { - Nid(ffi::NID_rc2_40_cbc) - } - - pub fn rc2_64_cbc() -> Nid { - Nid(ffi::NID_rc2_64_cbc) - } - - pub fn rc4() -> Nid { - Nid(ffi::NID_rc4) - } - - pub fn rc4_40() -> Nid { - Nid(ffi::NID_rc4_40) - } - - pub fn des_ede3_cbc() -> Nid { - Nid(ffi::NID_des_ede3_cbc) - } - - pub fn rc5_cbc() -> Nid { - Nid(ffi::NID_rc5_cbc) - } - - pub fn rc5_ecb() -> Nid { - Nid(ffi::NID_rc5_ecb) - } - - pub fn rc5_cfb64() -> Nid { - Nid(ffi::NID_rc5_cfb64) - } - - pub fn rc5_ofb64() -> Nid { - Nid(ffi::NID_rc5_ofb64) - } - - pub fn ms_ext_req() -> Nid { - Nid(ffi::NID_ms_ext_req) - } - - pub fn ms_code_ind() -> Nid { - Nid(ffi::NID_ms_code_ind) - } - - pub fn ms_code_com() -> Nid { - Nid(ffi::NID_ms_code_com) - } - - pub fn ms_ctl_sign() -> Nid { - Nid(ffi::NID_ms_ctl_sign) - } - - pub fn ms_sgc() -> Nid { - Nid(ffi::NID_ms_sgc) - } - - pub fn ms_efs() -> Nid { - Nid(ffi::NID_ms_efs) - } - - pub fn ms_smartcard_login() -> Nid { - Nid(ffi::NID_ms_smartcard_login) - } - - pub fn ms_upn() -> Nid { - Nid(ffi::NID_ms_upn) - } - - pub fn idea_cbc() -> Nid { - Nid(ffi::NID_idea_cbc) - } - - pub fn idea_ecb() -> Nid { - Nid(ffi::NID_idea_ecb) - } - - pub fn idea_cfb64() -> Nid { - Nid(ffi::NID_idea_cfb64) - } - - pub fn idea_ofb64() -> Nid { - Nid(ffi::NID_idea_ofb64) - } - - pub fn bf_cbc() -> Nid { - Nid(ffi::NID_bf_cbc) - } - - pub fn bf_ecb() -> Nid { - Nid(ffi::NID_bf_ecb) - } - - pub fn bf_cfb64() -> Nid { - Nid(ffi::NID_bf_cfb64) - } - - pub fn bf_ofb64() -> Nid { - Nid(ffi::NID_bf_ofb64) - } - - pub fn id_pkix() -> Nid { - Nid(ffi::NID_id_pkix) - } - - pub fn id_pkix_mod() -> Nid { - Nid(ffi::NID_id_pkix_mod) - } - - pub fn id_pe() -> Nid { - Nid(ffi::NID_id_pe) - } - - pub fn id_qt() -> Nid { - Nid(ffi::NID_id_qt) - } - - pub fn id_kp() -> Nid { - Nid(ffi::NID_id_kp) - } - - pub fn id_it() -> Nid { - Nid(ffi::NID_id_it) - } - - pub fn id_pkip() -> Nid { - Nid(ffi::NID_id_pkip) - } - - pub fn id_alg() -> Nid { - Nid(ffi::NID_id_alg) - } - - pub fn id_cmc() -> Nid { - Nid(ffi::NID_id_cmc) - } - - pub fn id_on() -> Nid { - Nid(ffi::NID_id_on) - } - - pub fn id_pda() -> Nid { - Nid(ffi::NID_id_pda) - } - - pub fn id_aca() -> Nid { - Nid(ffi::NID_id_aca) - } - - pub fn id_qcs() -> Nid { - Nid(ffi::NID_id_qcs) - } - - pub fn id_cct() -> Nid { - Nid(ffi::NID_id_cct) - } - - pub fn id_ppl() -> Nid { - Nid(ffi::NID_id_ppl) - } - - pub fn id_ad() -> Nid { - Nid(ffi::NID_id_ad) - } - - pub fn id_pkix1_explicit_88() -> Nid { - Nid(ffi::NID_id_pkix1_explicit_88) - } - - pub fn id_pkix1_implicit_88() -> Nid { - Nid(ffi::NID_id_pkix1_implicit_88) - } - - pub fn id_pkix1_explicit_93() -> Nid { - Nid(ffi::NID_id_pkix1_explicit_93) - } - - pub fn id_pkix1_implicit_93() -> Nid { - Nid(ffi::NID_id_pkix1_implicit_93) - } - - pub fn id_mod_crmf() -> Nid { - Nid(ffi::NID_id_mod_crmf) - } - - pub fn id_mod_cmc() -> Nid { - Nid(ffi::NID_id_mod_cmc) - } - - pub fn id_mod_kea_profile_88() -> Nid { - Nid(ffi::NID_id_mod_kea_profile_88) - } - - pub fn id_mod_kea_profile_93() -> Nid { - Nid(ffi::NID_id_mod_kea_profile_93) - } - - pub fn id_mod_cmp() -> Nid { - Nid(ffi::NID_id_mod_cmp) - } - - pub fn id_mod_qualified_cert_88() -> Nid { - Nid(ffi::NID_id_mod_qualified_cert_88) - } - - pub fn id_mod_qualified_cert_93() -> Nid { - Nid(ffi::NID_id_mod_qualified_cert_93) - } - - pub fn id_mod_attribute_cert() -> Nid { - Nid(ffi::NID_id_mod_attribute_cert) - } - - pub fn id_mod_timestamp_protocol() -> Nid { - Nid(ffi::NID_id_mod_timestamp_protocol) - } - - pub fn id_mod_ocsp() -> Nid { - Nid(ffi::NID_id_mod_ocsp) - } - - pub fn id_mod_dvcs() -> Nid { - Nid(ffi::NID_id_mod_dvcs) - } - - pub fn id_mod_cmp2000() -> Nid { - Nid(ffi::NID_id_mod_cmp2000) - } - - pub fn info_access() -> Nid { - Nid(ffi::NID_info_access) - } - - pub fn biometricInfo() -> Nid { - Nid(ffi::NID_biometricInfo) - } - - pub fn qcStatements() -> Nid { - Nid(ffi::NID_qcStatements) - } - - pub fn ac_auditEntity() -> Nid { - Nid(ffi::NID_ac_auditEntity) - } - - pub fn ac_targeting() -> Nid { - Nid(ffi::NID_ac_targeting) - } - - pub fn aaControls() -> Nid { - Nid(ffi::NID_aaControls) - } - - pub fn sbgp_ipAddrBlock() -> Nid { - Nid(ffi::NID_sbgp_ipAddrBlock) - } - - pub fn sbgp_autonomousSysNum() -> Nid { - Nid(ffi::NID_sbgp_autonomousSysNum) - } - - pub fn sbgp_routerIdentifier() -> Nid { - Nid(ffi::NID_sbgp_routerIdentifier) - } - - pub fn ac_proxying() -> Nid { - Nid(ffi::NID_ac_proxying) - } - - pub fn sinfo_access() -> Nid { - Nid(ffi::NID_sinfo_access) - } - - pub fn proxyCertInfo() -> Nid { - Nid(ffi::NID_proxyCertInfo) - } - - pub fn id_qt_cps() -> Nid { - Nid(ffi::NID_id_qt_cps) - } - - pub fn id_qt_unotice() -> Nid { - Nid(ffi::NID_id_qt_unotice) - } - - pub fn textNotice() -> Nid { - Nid(ffi::NID_textNotice) - } - - pub fn server_auth() -> Nid { - Nid(ffi::NID_server_auth) - } - - pub fn client_auth() -> Nid { - Nid(ffi::NID_client_auth) - } - - pub fn code_sign() -> Nid { - Nid(ffi::NID_code_sign) - } - - pub fn email_protect() -> Nid { - Nid(ffi::NID_email_protect) - } - - pub fn ipsecEndSystem() -> Nid { - Nid(ffi::NID_ipsecEndSystem) - } - - pub fn ipsecTunnel() -> Nid { - Nid(ffi::NID_ipsecTunnel) - } - - pub fn ipsecUser() -> Nid { - Nid(ffi::NID_ipsecUser) - } - - pub fn time_stamp() -> Nid { - Nid(ffi::NID_time_stamp) - } - - pub fn OCSP_sign() -> Nid { - Nid(ffi::NID_OCSP_sign) - } - - pub fn dvcs() -> Nid { - Nid(ffi::NID_dvcs) - } - - pub fn id_it_caProtEncCert() -> Nid { - Nid(ffi::NID_id_it_caProtEncCert) - } - - pub fn id_it_signKeyPairTypes() -> Nid { - Nid(ffi::NID_id_it_signKeyPairTypes) - } - - pub fn id_it_encKeyPairTypes() -> Nid { - Nid(ffi::NID_id_it_encKeyPairTypes) - } - - pub fn id_it_preferredSymmAlg() -> Nid { - Nid(ffi::NID_id_it_preferredSymmAlg) - } - - pub fn id_it_caKeyUpdateInfo() -> Nid { - Nid(ffi::NID_id_it_caKeyUpdateInfo) - } - - pub fn id_it_currentCRL() -> Nid { - Nid(ffi::NID_id_it_currentCRL) - } - - pub fn id_it_unsupportedOIDs() -> Nid { - Nid(ffi::NID_id_it_unsupportedOIDs) - } - - pub fn id_it_subscriptionRequest() -> Nid { - Nid(ffi::NID_id_it_subscriptionRequest) - } - - pub fn id_it_subscriptionResponse() -> Nid { - Nid(ffi::NID_id_it_subscriptionResponse) - } - - pub fn id_it_keyPairParamReq() -> Nid { - Nid(ffi::NID_id_it_keyPairParamReq) - } - - pub fn id_it_keyPairParamRep() -> Nid { - Nid(ffi::NID_id_it_keyPairParamRep) - } - - pub fn id_it_revPassphrase() -> Nid { - Nid(ffi::NID_id_it_revPassphrase) - } - - pub fn id_it_implicitConfirm() -> Nid { - Nid(ffi::NID_id_it_implicitConfirm) - } - - pub fn id_it_confirmWaitTime() -> Nid { - Nid(ffi::NID_id_it_confirmWaitTime) - } - - pub fn id_it_origPKIMessage() -> Nid { - Nid(ffi::NID_id_it_origPKIMessage) - } - - pub fn id_it_suppLangTags() -> Nid { - Nid(ffi::NID_id_it_suppLangTags) - } - - pub fn id_regCtrl() -> Nid { - Nid(ffi::NID_id_regCtrl) - } - - pub fn id_regInfo() -> Nid { - Nid(ffi::NID_id_regInfo) - } - - pub fn id_regCtrl_regToken() -> Nid { - Nid(ffi::NID_id_regCtrl_regToken) - } - - pub fn id_regCtrl_authenticator() -> Nid { - Nid(ffi::NID_id_regCtrl_authenticator) - } - - pub fn id_regCtrl_pkiPublicationInfo() -> Nid { - Nid(ffi::NID_id_regCtrl_pkiPublicationInfo) - } - - pub fn id_regCtrl_pkiArchiveOptions() -> Nid { - Nid(ffi::NID_id_regCtrl_pkiArchiveOptions) - } - - pub fn id_regCtrl_oldCertID() -> Nid { - Nid(ffi::NID_id_regCtrl_oldCertID) - } - - pub fn id_regCtrl_protocolEncrKey() -> Nid { - Nid(ffi::NID_id_regCtrl_protocolEncrKey) - } - - pub fn id_regInfo_utf8Pairs() -> Nid { - Nid(ffi::NID_id_regInfo_utf8Pairs) - } - - pub fn id_regInfo_certReq() -> Nid { - Nid(ffi::NID_id_regInfo_certReq) - } - - pub fn id_alg_des40() -> Nid { - Nid(ffi::NID_id_alg_des40) - } - - pub fn id_alg_noSignature() -> Nid { - Nid(ffi::NID_id_alg_noSignature) - } - - pub fn id_alg_dh_sig_hmac_sha1() -> Nid { - Nid(ffi::NID_id_alg_dh_sig_hmac_sha1) - } - - pub fn id_alg_dh_pop() -> Nid { - Nid(ffi::NID_id_alg_dh_pop) - } - - pub fn id_cmc_statusInfo() -> Nid { - Nid(ffi::NID_id_cmc_statusInfo) - } - - pub fn id_cmc_identification() -> Nid { - Nid(ffi::NID_id_cmc_identification) - } - - pub fn id_cmc_identityProof() -> Nid { - Nid(ffi::NID_id_cmc_identityProof) - } - - pub fn id_cmc_dataReturn() -> Nid { - Nid(ffi::NID_id_cmc_dataReturn) - } - - pub fn id_cmc_transactionId() -> Nid { - Nid(ffi::NID_id_cmc_transactionId) - } - - pub fn id_cmc_senderNonce() -> Nid { - Nid(ffi::NID_id_cmc_senderNonce) - } - - pub fn id_cmc_recipientNonce() -> Nid { - Nid(ffi::NID_id_cmc_recipientNonce) - } - - pub fn id_cmc_addExtensions() -> Nid { - Nid(ffi::NID_id_cmc_addExtensions) - } - - pub fn id_cmc_encryptedPOP() -> Nid { - Nid(ffi::NID_id_cmc_encryptedPOP) - } - - pub fn id_cmc_decryptedPOP() -> Nid { - Nid(ffi::NID_id_cmc_decryptedPOP) - } - - pub fn id_cmc_lraPOPWitness() -> Nid { - Nid(ffi::NID_id_cmc_lraPOPWitness) - } - - pub fn id_cmc_getCert() -> Nid { - Nid(ffi::NID_id_cmc_getCert) - } - - pub fn id_cmc_getCRL() -> Nid { - Nid(ffi::NID_id_cmc_getCRL) - } - - pub fn id_cmc_revokeRequest() -> Nid { - Nid(ffi::NID_id_cmc_revokeRequest) - } - - pub fn id_cmc_regInfo() -> Nid { - Nid(ffi::NID_id_cmc_regInfo) - } - - pub fn id_cmc_responseInfo() -> Nid { - Nid(ffi::NID_id_cmc_responseInfo) - } - - pub fn id_cmc_queryPending() -> Nid { - Nid(ffi::NID_id_cmc_queryPending) - } - - pub fn id_cmc_popLinkRandom() -> Nid { - Nid(ffi::NID_id_cmc_popLinkRandom) - } - - pub fn id_cmc_popLinkWitness() -> Nid { - Nid(ffi::NID_id_cmc_popLinkWitness) - } - - pub fn id_cmc_confirmCertAcceptance() -> Nid { - Nid(ffi::NID_id_cmc_confirmCertAcceptance) - } - - pub fn id_on_personalData() -> Nid { - Nid(ffi::NID_id_on_personalData) - } - - pub fn id_on_permanentIdentifier() -> Nid { - Nid(ffi::NID_id_on_permanentIdentifier) - } - - pub fn id_pda_dateOfBirth() -> Nid { - Nid(ffi::NID_id_pda_dateOfBirth) - } - - pub fn id_pda_placeOfBirth() -> Nid { - Nid(ffi::NID_id_pda_placeOfBirth) - } - - pub fn id_pda_gender() -> Nid { - Nid(ffi::NID_id_pda_gender) - } - - pub fn id_pda_countryOfCitizenship() -> Nid { - Nid(ffi::NID_id_pda_countryOfCitizenship) - } - - pub fn id_pda_countryOfResidence() -> Nid { - Nid(ffi::NID_id_pda_countryOfResidence) - } - - pub fn id_aca_authenticationInfo() -> Nid { - Nid(ffi::NID_id_aca_authenticationInfo) - } - - pub fn id_aca_accessIdentity() -> Nid { - Nid(ffi::NID_id_aca_accessIdentity) - } - - pub fn id_aca_chargingIdentity() -> Nid { - Nid(ffi::NID_id_aca_chargingIdentity) - } - - pub fn id_aca_group() -> Nid { - Nid(ffi::NID_id_aca_group) - } - - pub fn id_aca_role() -> Nid { - Nid(ffi::NID_id_aca_role) - } - - pub fn id_aca_encAttrs() -> Nid { - Nid(ffi::NID_id_aca_encAttrs) - } - - pub fn id_qcs_pkixQCSyntax_v1() -> Nid { - Nid(ffi::NID_id_qcs_pkixQCSyntax_v1) - } - - pub fn id_cct_crs() -> Nid { - Nid(ffi::NID_id_cct_crs) - } - - pub fn id_cct_PKIData() -> Nid { - Nid(ffi::NID_id_cct_PKIData) - } - - pub fn id_cct_PKIResponse() -> Nid { - Nid(ffi::NID_id_cct_PKIResponse) - } - - pub fn id_ppl_anyLanguage() -> Nid { - Nid(ffi::NID_id_ppl_anyLanguage) - } - - pub fn id_ppl_inheritAll() -> Nid { - Nid(ffi::NID_id_ppl_inheritAll) - } - - pub fn Independent() -> Nid { - Nid(ffi::NID_Independent) - } - - pub fn ad_OCSP() -> Nid { - Nid(ffi::NID_ad_OCSP) - } - - pub fn ad_ca_issuers() -> Nid { - Nid(ffi::NID_ad_ca_issuers) - } - - pub fn ad_timeStamping() -> Nid { - Nid(ffi::NID_ad_timeStamping) - } - - pub fn ad_dvcs() -> Nid { - Nid(ffi::NID_ad_dvcs) - } - - pub fn caRepository() -> Nid { - Nid(ffi::NID_caRepository) - } - - pub fn id_pkix_OCSP_basic() -> Nid { - Nid(ffi::NID_id_pkix_OCSP_basic) - } - - pub fn id_pkix_OCSP_Nonce() -> Nid { - Nid(ffi::NID_id_pkix_OCSP_Nonce) - } - - pub fn id_pkix_OCSP_CrlID() -> Nid { - Nid(ffi::NID_id_pkix_OCSP_CrlID) - } - - pub fn id_pkix_OCSP_acceptableResponses() -> Nid { - Nid(ffi::NID_id_pkix_OCSP_acceptableResponses) - } - - pub fn id_pkix_OCSP_noCheck() -> Nid { - Nid(ffi::NID_id_pkix_OCSP_noCheck) - } - - pub fn id_pkix_OCSP_archiveCutoff() -> Nid { - Nid(ffi::NID_id_pkix_OCSP_archiveCutoff) - } - - pub fn id_pkix_OCSP_serviceLocator() -> Nid { - Nid(ffi::NID_id_pkix_OCSP_serviceLocator) - } - - pub fn id_pkix_OCSP_extendedStatus() -> Nid { - Nid(ffi::NID_id_pkix_OCSP_extendedStatus) - } - - pub fn id_pkix_OCSP_valid() -> Nid { - Nid(ffi::NID_id_pkix_OCSP_valid) - } - - pub fn id_pkix_OCSP_path() -> Nid { - Nid(ffi::NID_id_pkix_OCSP_path) - } - - pub fn id_pkix_OCSP_trustRoot() -> Nid { - Nid(ffi::NID_id_pkix_OCSP_trustRoot) - } - - pub fn algorithm() -> Nid { - Nid(ffi::NID_algorithm) - } - - pub fn md5WithRSA() -> Nid { - Nid(ffi::NID_md5WithRSA) - } - - pub fn des_ecb() -> Nid { - Nid(ffi::NID_des_ecb) - } - - pub fn des_cbc() -> Nid { - Nid(ffi::NID_des_cbc) - } - - pub fn des_ofb64() -> Nid { - Nid(ffi::NID_des_ofb64) - } - - pub fn des_cfb64() -> Nid { - Nid(ffi::NID_des_cfb64) - } - - pub fn rsaSignature() -> Nid { - Nid(ffi::NID_rsaSignature) - } - - pub fn dsa_2() -> Nid { - Nid(ffi::NID_dsa_2) - } - - pub fn dsaWithSHA() -> Nid { - Nid(ffi::NID_dsaWithSHA) - } - - pub fn shaWithRSAEncryption() -> Nid { - Nid(ffi::NID_shaWithRSAEncryption) - } - - pub fn des_ede_ecb() -> Nid { - Nid(ffi::NID_des_ede_ecb) - } - - pub fn des_ede3_ecb() -> Nid { - Nid(ffi::NID_des_ede3_ecb) - } - - pub fn des_ede_cbc() -> Nid { - Nid(ffi::NID_des_ede_cbc) - } - - pub fn des_ede_cfb64() -> Nid { - Nid(ffi::NID_des_ede_cfb64) - } - - pub fn des_ede3_cfb64() -> Nid { - Nid(ffi::NID_des_ede3_cfb64) - } - - pub fn des_ede_ofb64() -> Nid { - Nid(ffi::NID_des_ede_ofb64) - } - - pub fn des_ede3_ofb64() -> Nid { - Nid(ffi::NID_des_ede3_ofb64) - } - - pub fn desx_cbc() -> Nid { - Nid(ffi::NID_desx_cbc) - } - - pub fn sha() -> Nid { - Nid(ffi::NID_sha) - } - - pub fn sha1() -> Nid { - Nid(ffi::NID_sha1) - } - - pub fn dsaWithSHA1_2() -> Nid { - Nid(ffi::NID_dsaWithSHA1_2) - } - - pub fn sha1WithRSA() -> Nid { - Nid(ffi::NID_sha1WithRSA) - } - - pub fn ripemd160() -> Nid { - Nid(ffi::NID_ripemd160) - } - - pub fn ripemd160WithRSA() -> Nid { - Nid(ffi::NID_ripemd160WithRSA) - } - - pub fn sxnet() -> Nid { - Nid(ffi::NID_sxnet) - } - - pub fn X500() -> Nid { - Nid(ffi::NID_X500) - } - - pub fn X509() -> Nid { - Nid(ffi::NID_X509) - } - - pub fn commonName() -> Nid { - Nid(ffi::NID_commonName) - } - - pub fn surname() -> Nid { - Nid(ffi::NID_surname) - } - - pub fn serialNumber() -> Nid { - Nid(ffi::NID_serialNumber) - } - - pub fn countryName() -> Nid { - Nid(ffi::NID_countryName) - } - - pub fn localityName() -> Nid { - Nid(ffi::NID_localityName) - } - - pub fn stateOrProvinceName() -> Nid { - Nid(ffi::NID_stateOrProvinceName) - } - - pub fn streetAddress() -> Nid { - Nid(ffi::NID_streetAddress) - } - - pub fn organizationName() -> Nid { - Nid(ffi::NID_organizationName) - } - - pub fn organizationalUnitName() -> Nid { - Nid(ffi::NID_organizationalUnitName) - } - - pub fn title() -> Nid { - Nid(ffi::NID_title) - } - - pub fn description() -> Nid { - Nid(ffi::NID_description) - } - - pub fn searchGuide() -> Nid { - Nid(ffi::NID_searchGuide) - } - - pub fn businessCategory() -> Nid { - Nid(ffi::NID_businessCategory) - } - - pub fn postalAddress() -> Nid { - Nid(ffi::NID_postalAddress) - } - - pub fn postalCode() -> Nid { - Nid(ffi::NID_postalCode) - } - - pub fn postOfficeBox() -> Nid { - Nid(ffi::NID_postOfficeBox) - } - - pub fn physicalDeliveryOfficeName() -> Nid { - Nid(ffi::NID_physicalDeliveryOfficeName) - } - - pub fn telephoneNumber() -> Nid { - Nid(ffi::NID_telephoneNumber) - } - - pub fn telexNumber() -> Nid { - Nid(ffi::NID_telexNumber) - } - - pub fn teletexTerminalIdentifier() -> Nid { - Nid(ffi::NID_teletexTerminalIdentifier) - } - - pub fn facsimileTelephoneNumber() -> Nid { - Nid(ffi::NID_facsimileTelephoneNumber) - } - - pub fn x121Address() -> Nid { - Nid(ffi::NID_x121Address) - } - - pub fn internationaliSDNNumber() -> Nid { - Nid(ffi::NID_internationaliSDNNumber) - } - - pub fn registeredAddress() -> Nid { - Nid(ffi::NID_registeredAddress) - } - - pub fn destinationIndicator() -> Nid { - Nid(ffi::NID_destinationIndicator) - } - - pub fn preferredDeliveryMethod() -> Nid { - Nid(ffi::NID_preferredDeliveryMethod) - } - - pub fn presentationAddress() -> Nid { - Nid(ffi::NID_presentationAddress) - } - - pub fn supportedApplicationContext() -> Nid { - Nid(ffi::NID_supportedApplicationContext) - } - - pub fn member() -> Nid { - Nid(ffi::NID_member) - } - - pub fn owner() -> Nid { - Nid(ffi::NID_owner) - } - - pub fn roleOccupant() -> Nid { - Nid(ffi::NID_roleOccupant) - } - - pub fn seeAlso() -> Nid { - Nid(ffi::NID_seeAlso) - } - - pub fn userPassword() -> Nid { - Nid(ffi::NID_userPassword) - } - - pub fn userCertificate() -> Nid { - Nid(ffi::NID_userCertificate) - } - - pub fn cACertificate() -> Nid { - Nid(ffi::NID_cACertificate) - } - - pub fn authorityRevocationList() -> Nid { - Nid(ffi::NID_authorityRevocationList) - } - - pub fn certificateRevocationList() -> Nid { - Nid(ffi::NID_certificateRevocationList) - } - - pub fn crossCertificatePair() -> Nid { - Nid(ffi::NID_crossCertificatePair) - } - - pub fn name() -> Nid { - Nid(ffi::NID_name) - } - - pub fn givenName() -> Nid { - Nid(ffi::NID_givenName) - } - - pub fn initials() -> Nid { - Nid(ffi::NID_initials) - } - - pub fn generationQualifier() -> Nid { - Nid(ffi::NID_generationQualifier) - } - - pub fn x500UniqueIdentifier() -> Nid { - Nid(ffi::NID_x500UniqueIdentifier) - } - - pub fn dnQualifier() -> Nid { - Nid(ffi::NID_dnQualifier) - } - - pub fn enhancedSearchGuide() -> Nid { - Nid(ffi::NID_enhancedSearchGuide) - } - - pub fn protocolInformation() -> Nid { - Nid(ffi::NID_protocolInformation) - } - - pub fn distinguishedName() -> Nid { - Nid(ffi::NID_distinguishedName) - } - - pub fn uniqueMember() -> Nid { - Nid(ffi::NID_uniqueMember) - } - - pub fn houseIdentifier() -> Nid { - Nid(ffi::NID_houseIdentifier) - } - - pub fn supportedAlgorithms() -> Nid { - Nid(ffi::NID_supportedAlgorithms) - } - - pub fn deltaRevocationList() -> Nid { - Nid(ffi::NID_deltaRevocationList) - } - - pub fn dmdName() -> Nid { - Nid(ffi::NID_dmdName) - } - - pub fn pseudonym() -> Nid { - Nid(ffi::NID_pseudonym) - } - - pub fn role() -> Nid { - Nid(ffi::NID_role) - } - - pub fn X500algorithms() -> Nid { - Nid(ffi::NID_X500algorithms) - } - - pub fn rsa() -> Nid { - Nid(ffi::NID_rsa) - } - - pub fn mdc2WithRSA() -> Nid { - Nid(ffi::NID_mdc2WithRSA) - } - - pub fn mdc2() -> Nid { - Nid(ffi::NID_mdc2) - } - - pub fn id_ce() -> Nid { - Nid(ffi::NID_id_ce) - } - - pub fn subject_directory_attributes() -> Nid { - Nid(ffi::NID_subject_directory_attributes) - } - - pub fn subject_key_identifier() -> Nid { - Nid(ffi::NID_subject_key_identifier) - } - - pub fn key_usage() -> Nid { - Nid(ffi::NID_key_usage) - } - - pub fn private_key_usage_period() -> Nid { - Nid(ffi::NID_private_key_usage_period) - } - - pub fn subject_alt_name() -> Nid { - Nid(ffi::NID_subject_alt_name) - } - - pub fn issuer_alt_name() -> Nid { - Nid(ffi::NID_issuer_alt_name) - } - - pub fn basic_constraints() -> Nid { - Nid(ffi::NID_basic_constraints) - } - - pub fn crl_number() -> Nid { - Nid(ffi::NID_crl_number) - } - - pub fn crl_reason() -> Nid { - Nid(ffi::NID_crl_reason) - } - - pub fn invalidity_date() -> Nid { - Nid(ffi::NID_invalidity_date) - } - - pub fn delta_crl() -> Nid { - Nid(ffi::NID_delta_crl) - } - - pub fn issuing_distribution_point() -> Nid { - Nid(ffi::NID_issuing_distribution_point) - } - - pub fn certificate_issuer() -> Nid { - Nid(ffi::NID_certificate_issuer) - } - - pub fn name_constraints() -> Nid { - Nid(ffi::NID_name_constraints) - } - - pub fn crl_distribution_points() -> Nid { - Nid(ffi::NID_crl_distribution_points) - } - - pub fn certificate_policies() -> Nid { - Nid(ffi::NID_certificate_policies) - } - - pub fn any_policy() -> Nid { - Nid(ffi::NID_any_policy) - } - - pub fn policy_mappings() -> Nid { - Nid(ffi::NID_policy_mappings) - } - - pub fn authority_key_identifier() -> Nid { - Nid(ffi::NID_authority_key_identifier) - } - - pub fn policy_constraints() -> Nid { - Nid(ffi::NID_policy_constraints) - } - - pub fn ext_key_usage() -> Nid { - Nid(ffi::NID_ext_key_usage) - } - - pub fn freshest_crl() -> Nid { - Nid(ffi::NID_freshest_crl) - } - - pub fn inhibit_any_policy() -> Nid { - Nid(ffi::NID_inhibit_any_policy) - } - - pub fn target_information() -> Nid { - Nid(ffi::NID_target_information) - } - - pub fn no_rev_avail() -> Nid { - Nid(ffi::NID_no_rev_avail) - } - - pub fn anyExtendedKeyUsage() -> Nid { - Nid(ffi::NID_anyExtendedKeyUsage) - } - - pub fn netscape() -> Nid { - Nid(ffi::NID_netscape) - } - - pub fn netscape_cert_extension() -> Nid { - Nid(ffi::NID_netscape_cert_extension) - } - - pub fn netscape_data_type() -> Nid { - Nid(ffi::NID_netscape_data_type) - } - - pub fn netscape_cert_type() -> Nid { - Nid(ffi::NID_netscape_cert_type) - } - - pub fn netscape_base_url() -> Nid { - Nid(ffi::NID_netscape_base_url) - } - - pub fn netscape_revocation_url() -> Nid { - Nid(ffi::NID_netscape_revocation_url) - } - - pub fn netscape_ca_revocation_url() -> Nid { - Nid(ffi::NID_netscape_ca_revocation_url) - } - - pub fn netscape_renewal_url() -> Nid { - Nid(ffi::NID_netscape_renewal_url) - } - - pub fn netscape_ca_policy_url() -> Nid { - Nid(ffi::NID_netscape_ca_policy_url) - } - - pub fn netscape_ssl_server_name() -> Nid { - Nid(ffi::NID_netscape_ssl_server_name) - } - - pub fn netscape_comment() -> Nid { - Nid(ffi::NID_netscape_comment) - } - - pub fn netscape_cert_sequence() -> Nid { - Nid(ffi::NID_netscape_cert_sequence) - } - - pub fn ns_sgc() -> Nid { - Nid(ffi::NID_ns_sgc) - } - - pub fn org() -> Nid { - Nid(ffi::NID_org) - } - - pub fn dod() -> Nid { - Nid(ffi::NID_dod) - } - - pub fn iana() -> Nid { - Nid(ffi::NID_iana) - } - - pub fn Directory() -> Nid { - Nid(ffi::NID_Directory) - } - - pub fn Management() -> Nid { - Nid(ffi::NID_Management) - } - - pub fn Experimental() -> Nid { - Nid(ffi::NID_Experimental) - } - - pub fn Private() -> Nid { - Nid(ffi::NID_Private) - } - - pub fn Security() -> Nid { - Nid(ffi::NID_Security) - } - - pub fn SNMPv2() -> Nid { - Nid(ffi::NID_SNMPv2) - } - - pub fn Mail() -> Nid { - Nid(ffi::NID_Mail) - } - - pub fn Enterprises() -> Nid { - Nid(ffi::NID_Enterprises) - } - - pub fn dcObject() -> Nid { - Nid(ffi::NID_dcObject) - } - - pub fn mime_mhs() -> Nid { - Nid(ffi::NID_mime_mhs) - } - - pub fn mime_mhs_headings() -> Nid { - Nid(ffi::NID_mime_mhs_headings) - } - - pub fn mime_mhs_bodies() -> Nid { - Nid(ffi::NID_mime_mhs_bodies) - } - - pub fn id_hex_partial_message() -> Nid { - Nid(ffi::NID_id_hex_partial_message) - } - - pub fn id_hex_multipart_message() -> Nid { - Nid(ffi::NID_id_hex_multipart_message) - } - - pub fn rle_compression() -> Nid { - Nid(ffi::NID_rle_compression) - } - - pub fn zlib_compression() -> Nid { - Nid(ffi::NID_zlib_compression) - } - - pub fn aes_128_ecb() -> Nid { - Nid(ffi::NID_aes_128_ecb) - } - - pub fn aes_128_cbc() -> Nid { - Nid(ffi::NID_aes_128_cbc) - } - - pub fn aes_128_ofb128() -> Nid { - Nid(ffi::NID_aes_128_ofb128) - } - - pub fn aes_128_cfb128() -> Nid { - Nid(ffi::NID_aes_128_cfb128) - } - - pub fn id_aes128_wrap() -> Nid { - Nid(ffi::NID_id_aes128_wrap) - } - - pub fn aes_128_gcm() -> Nid { - Nid(ffi::NID_aes_128_gcm) - } - - pub fn aes_128_ccm() -> Nid { - Nid(ffi::NID_aes_128_ccm) - } - - pub fn id_aes128_wrap_pad() -> Nid { - Nid(ffi::NID_id_aes128_wrap_pad) - } - - pub fn aes_192_ecb() -> Nid { - Nid(ffi::NID_aes_192_ecb) - } - - pub fn aes_192_cbc() -> Nid { - Nid(ffi::NID_aes_192_cbc) - } - - pub fn aes_192_ofb128() -> Nid { - Nid(ffi::NID_aes_192_ofb128) - } - - pub fn aes_192_cfb128() -> Nid { - Nid(ffi::NID_aes_192_cfb128) - } - - pub fn id_aes192_wrap() -> Nid { - Nid(ffi::NID_id_aes192_wrap) - } - - pub fn aes_192_gcm() -> Nid { - Nid(ffi::NID_aes_192_gcm) - } - - pub fn aes_192_ccm() -> Nid { - Nid(ffi::NID_aes_192_ccm) - } - - pub fn id_aes192_wrap_pad() -> Nid { - Nid(ffi::NID_id_aes192_wrap_pad) - } - - pub fn aes_256_ecb() -> Nid { - Nid(ffi::NID_aes_256_ecb) - } - - pub fn aes_256_cbc() -> Nid { - Nid(ffi::NID_aes_256_cbc) - } - - pub fn aes_256_ofb128() -> Nid { - Nid(ffi::NID_aes_256_ofb128) - } - - pub fn aes_256_cfb128() -> Nid { - Nid(ffi::NID_aes_256_cfb128) - } - - pub fn id_aes256_wrap() -> Nid { - Nid(ffi::NID_id_aes256_wrap) - } - - pub fn aes_256_gcm() -> Nid { - Nid(ffi::NID_aes_256_gcm) - } - - pub fn aes_256_ccm() -> Nid { - Nid(ffi::NID_aes_256_ccm) - } - - pub fn id_aes256_wrap_pad() -> Nid { - Nid(ffi::NID_id_aes256_wrap_pad) - } - - pub fn aes_128_cfb1() -> Nid { - Nid(ffi::NID_aes_128_cfb1) - } - - pub fn aes_192_cfb1() -> Nid { - Nid(ffi::NID_aes_192_cfb1) - } - - pub fn aes_256_cfb1() -> Nid { - Nid(ffi::NID_aes_256_cfb1) - } - - pub fn aes_128_cfb8() -> Nid { - Nid(ffi::NID_aes_128_cfb8) - } - - pub fn aes_192_cfb8() -> Nid { - Nid(ffi::NID_aes_192_cfb8) - } - - pub fn aes_256_cfb8() -> Nid { - Nid(ffi::NID_aes_256_cfb8) - } - - pub fn aes_128_ctr() -> Nid { - Nid(ffi::NID_aes_128_ctr) - } - - pub fn aes_192_ctr() -> Nid { - Nid(ffi::NID_aes_192_ctr) - } - - pub fn aes_256_ctr() -> Nid { - Nid(ffi::NID_aes_256_ctr) - } - - pub fn aes_128_xts() -> Nid { - Nid(ffi::NID_aes_128_xts) - } - - pub fn aes_256_xts() -> Nid { - Nid(ffi::NID_aes_256_xts) - } - - pub fn des_cfb1() -> Nid { - Nid(ffi::NID_des_cfb1) - } - - pub fn des_cfb8() -> Nid { - Nid(ffi::NID_des_cfb8) - } - - pub fn des_ede3_cfb1() -> Nid { - Nid(ffi::NID_des_ede3_cfb1) - } - - pub fn des_ede3_cfb8() -> Nid { - Nid(ffi::NID_des_ede3_cfb8) - } - - pub fn sha256() -> Nid { - Nid(ffi::NID_sha256) - } - - pub fn sha384() -> Nid { - Nid(ffi::NID_sha384) - } - - pub fn sha512() -> Nid { - Nid(ffi::NID_sha512) - } - - pub fn sha224() -> Nid { - Nid(ffi::NID_sha224) - } - - pub fn dsa_with_SHA224() -> Nid { - Nid(ffi::NID_dsa_with_SHA224) - } - - pub fn dsa_with_SHA256() -> Nid { - Nid(ffi::NID_dsa_with_SHA256) - } - - pub fn hold_instruction_code() -> Nid { - Nid(ffi::NID_hold_instruction_code) - } - - pub fn hold_instruction_none() -> Nid { - Nid(ffi::NID_hold_instruction_none) - } - - pub fn hold_instruction_call_issuer() -> Nid { - Nid(ffi::NID_hold_instruction_call_issuer) - } - - pub fn hold_instruction_reject() -> Nid { - Nid(ffi::NID_hold_instruction_reject) - } - - pub fn data() -> Nid { - Nid(ffi::NID_data) - } - - pub fn pss() -> Nid { - Nid(ffi::NID_pss) - } - - pub fn ucl() -> Nid { - Nid(ffi::NID_ucl) - } - - pub fn pilot() -> Nid { - Nid(ffi::NID_pilot) - } - - pub fn pilotAttributeType() -> Nid { - Nid(ffi::NID_pilotAttributeType) - } - - pub fn pilotAttributeSyntax() -> Nid { - Nid(ffi::NID_pilotAttributeSyntax) - } - - pub fn pilotObjectClass() -> Nid { - Nid(ffi::NID_pilotObjectClass) - } - - pub fn pilotGroups() -> Nid { - Nid(ffi::NID_pilotGroups) - } - - pub fn iA5StringSyntax() -> Nid { - Nid(ffi::NID_iA5StringSyntax) - } - - pub fn caseIgnoreIA5StringSyntax() -> Nid { - Nid(ffi::NID_caseIgnoreIA5StringSyntax) - } - - pub fn pilotObject() -> Nid { - Nid(ffi::NID_pilotObject) - } - - pub fn pilotPerson() -> Nid { - Nid(ffi::NID_pilotPerson) - } - - pub fn account() -> Nid { - Nid(ffi::NID_account) - } - - pub fn document() -> Nid { - Nid(ffi::NID_document) - } - - pub fn room() -> Nid { - Nid(ffi::NID_room) - } - - pub fn documentSeries() -> Nid { - Nid(ffi::NID_documentSeries) - } - - pub fn Domain() -> Nid { - Nid(ffi::NID_Domain) - } - - pub fn rFC822localPart() -> Nid { - Nid(ffi::NID_rFC822localPart) - } - - pub fn dNSDomain() -> Nid { - Nid(ffi::NID_dNSDomain) - } - - pub fn domainRelatedObject() -> Nid { - Nid(ffi::NID_domainRelatedObject) - } - - pub fn friendlyCountry() -> Nid { - Nid(ffi::NID_friendlyCountry) - } - - pub fn simpleSecurityObject() -> Nid { - Nid(ffi::NID_simpleSecurityObject) - } - - pub fn pilotOrganization() -> Nid { - Nid(ffi::NID_pilotOrganization) - } - - pub fn pilotDSA() -> Nid { - Nid(ffi::NID_pilotDSA) - } - - pub fn qualityLabelledData() -> Nid { - Nid(ffi::NID_qualityLabelledData) - } - - pub fn userId() -> Nid { - Nid(ffi::NID_userId) - } - - pub fn textEncodedORAddress() -> Nid { - Nid(ffi::NID_textEncodedORAddress) - } - - pub fn rfc822Mailbox() -> Nid { - Nid(ffi::NID_rfc822Mailbox) - } - - pub fn info() -> Nid { - Nid(ffi::NID_info) - } - - pub fn favouriteDrink() -> Nid { - Nid(ffi::NID_favouriteDrink) - } - - pub fn roomNumber() -> Nid { - Nid(ffi::NID_roomNumber) - } - - pub fn photo() -> Nid { - Nid(ffi::NID_photo) - } - - pub fn userClass() -> Nid { - Nid(ffi::NID_userClass) - } - - pub fn host() -> Nid { - Nid(ffi::NID_host) - } - - pub fn manager() -> Nid { - Nid(ffi::NID_manager) - } - - pub fn documentIdentifier() -> Nid { - Nid(ffi::NID_documentIdentifier) - } - - pub fn documentTitle() -> Nid { - Nid(ffi::NID_documentTitle) - } - - pub fn documentVersion() -> Nid { - Nid(ffi::NID_documentVersion) - } - - pub fn documentAuthor() -> Nid { - Nid(ffi::NID_documentAuthor) - } - - pub fn documentLocation() -> Nid { - Nid(ffi::NID_documentLocation) - } - - pub fn homeTelephoneNumber() -> Nid { - Nid(ffi::NID_homeTelephoneNumber) - } - - pub fn secretary() -> Nid { - Nid(ffi::NID_secretary) - } - - pub fn otherMailbox() -> Nid { - Nid(ffi::NID_otherMailbox) - } - - pub fn lastModifiedTime() -> Nid { - Nid(ffi::NID_lastModifiedTime) - } - - pub fn lastModifiedBy() -> Nid { - Nid(ffi::NID_lastModifiedBy) - } - - pub fn domainComponent() -> Nid { - Nid(ffi::NID_domainComponent) - } - - pub fn aRecord() -> Nid { - Nid(ffi::NID_aRecord) - } - - pub fn pilotAttributeType27() -> Nid { - Nid(ffi::NID_pilotAttributeType27) - } - - pub fn mXRecord() -> Nid { - Nid(ffi::NID_mXRecord) - } - - pub fn nSRecord() -> Nid { - Nid(ffi::NID_nSRecord) - } - - pub fn sOARecord() -> Nid { - Nid(ffi::NID_sOARecord) - } - - pub fn cNAMERecord() -> Nid { - Nid(ffi::NID_cNAMERecord) - } - - pub fn associatedDomain() -> Nid { - Nid(ffi::NID_associatedDomain) - } - - pub fn associatedName() -> Nid { - Nid(ffi::NID_associatedName) - } - - pub fn homePostalAddress() -> Nid { - Nid(ffi::NID_homePostalAddress) - } - - pub fn personalTitle() -> Nid { - Nid(ffi::NID_personalTitle) - } - - pub fn mobileTelephoneNumber() -> Nid { - Nid(ffi::NID_mobileTelephoneNumber) - } - - pub fn pagerTelephoneNumber() -> Nid { - Nid(ffi::NID_pagerTelephoneNumber) - } - - pub fn friendlyCountryName() -> Nid { - Nid(ffi::NID_friendlyCountryName) - } - - pub fn organizationalStatus() -> Nid { - Nid(ffi::NID_organizationalStatus) - } - - pub fn janetMailbox() -> Nid { - Nid(ffi::NID_janetMailbox) - } - - pub fn mailPreferenceOption() -> Nid { - Nid(ffi::NID_mailPreferenceOption) - } - - pub fn buildingName() -> Nid { - Nid(ffi::NID_buildingName) - } - - pub fn dSAQuality() -> Nid { - Nid(ffi::NID_dSAQuality) - } - - pub fn singleLevelQuality() -> Nid { - Nid(ffi::NID_singleLevelQuality) - } - - pub fn subtreeMinimumQuality() -> Nid { - Nid(ffi::NID_subtreeMinimumQuality) - } - - pub fn subtreeMaximumQuality() -> Nid { - Nid(ffi::NID_subtreeMaximumQuality) - } - - pub fn personalSignature() -> Nid { - Nid(ffi::NID_personalSignature) - } - - pub fn dITRedirect() -> Nid { - Nid(ffi::NID_dITRedirect) - } - - pub fn audio() -> Nid { - Nid(ffi::NID_audio) - } - - pub fn documentPublisher() -> Nid { - Nid(ffi::NID_documentPublisher) - } - - pub fn id_set() -> Nid { - Nid(ffi::NID_id_set) - } - - pub fn set_ctype() -> Nid { - Nid(ffi::NID_set_ctype) - } - - pub fn set_msgExt() -> Nid { - Nid(ffi::NID_set_msgExt) - } - - pub fn set_attr() -> Nid { - Nid(ffi::NID_set_attr) - } - - pub fn set_policy() -> Nid { - Nid(ffi::NID_set_policy) - } - - pub fn set_certExt() -> Nid { - Nid(ffi::NID_set_certExt) - } - - pub fn set_brand() -> Nid { - Nid(ffi::NID_set_brand) - } - - pub fn setct_PANData() -> Nid { - Nid(ffi::NID_setct_PANData) - } - - pub fn setct_PANToken() -> Nid { - Nid(ffi::NID_setct_PANToken) - } - - pub fn setct_PANOnly() -> Nid { - Nid(ffi::NID_setct_PANOnly) - } - - pub fn setct_OIData() -> Nid { - Nid(ffi::NID_setct_OIData) - } - - pub fn setct_PI() -> Nid { - Nid(ffi::NID_setct_PI) - } - - pub fn setct_PIData() -> Nid { - Nid(ffi::NID_setct_PIData) - } - - pub fn setct_PIDataUnsigned() -> Nid { - Nid(ffi::NID_setct_PIDataUnsigned) - } - - pub fn setct_HODInput() -> Nid { - Nid(ffi::NID_setct_HODInput) - } - - pub fn setct_AuthResBaggage() -> Nid { - Nid(ffi::NID_setct_AuthResBaggage) - } - - pub fn setct_AuthRevReqBaggage() -> Nid { - Nid(ffi::NID_setct_AuthRevReqBaggage) - } - - pub fn setct_AuthRevResBaggage() -> Nid { - Nid(ffi::NID_setct_AuthRevResBaggage) - } - - pub fn setct_CapTokenSeq() -> Nid { - Nid(ffi::NID_setct_CapTokenSeq) - } - - pub fn setct_PInitResData() -> Nid { - Nid(ffi::NID_setct_PInitResData) - } - - pub fn setct_PI_TBS() -> Nid { - Nid(ffi::NID_setct_PI_TBS) - } - - pub fn setct_PResData() -> Nid { - Nid(ffi::NID_setct_PResData) - } - - pub fn setct_AuthReqTBS() -> Nid { - Nid(ffi::NID_setct_AuthReqTBS) - } - - pub fn setct_AuthResTBS() -> Nid { - Nid(ffi::NID_setct_AuthResTBS) - } - - pub fn setct_AuthResTBSX() -> Nid { - Nid(ffi::NID_setct_AuthResTBSX) - } - - pub fn setct_AuthTokenTBS() -> Nid { - Nid(ffi::NID_setct_AuthTokenTBS) - } - - pub fn setct_CapTokenData() -> Nid { - Nid(ffi::NID_setct_CapTokenData) - } - - pub fn setct_CapTokenTBS() -> Nid { - Nid(ffi::NID_setct_CapTokenTBS) - } - - pub fn setct_AcqCardCodeMsg() -> Nid { - Nid(ffi::NID_setct_AcqCardCodeMsg) - } - - pub fn setct_AuthRevReqTBS() -> Nid { - Nid(ffi::NID_setct_AuthRevReqTBS) - } - - pub fn setct_AuthRevResData() -> Nid { - Nid(ffi::NID_setct_AuthRevResData) - } - - pub fn setct_AuthRevResTBS() -> Nid { - Nid(ffi::NID_setct_AuthRevResTBS) - } - - pub fn setct_CapReqTBS() -> Nid { - Nid(ffi::NID_setct_CapReqTBS) - } - - pub fn setct_CapReqTBSX() -> Nid { - Nid(ffi::NID_setct_CapReqTBSX) - } - - pub fn setct_CapResData() -> Nid { - Nid(ffi::NID_setct_CapResData) - } - - pub fn setct_CapRevReqTBS() -> Nid { - Nid(ffi::NID_setct_CapRevReqTBS) - } - - pub fn setct_CapRevReqTBSX() -> Nid { - Nid(ffi::NID_setct_CapRevReqTBSX) - } - - pub fn setct_CapRevResData() -> Nid { - Nid(ffi::NID_setct_CapRevResData) - } - - pub fn setct_CredReqTBS() -> Nid { - Nid(ffi::NID_setct_CredReqTBS) - } - - pub fn setct_CredReqTBSX() -> Nid { - Nid(ffi::NID_setct_CredReqTBSX) - } - - pub fn setct_CredResData() -> Nid { - Nid(ffi::NID_setct_CredResData) - } - - pub fn setct_CredRevReqTBS() -> Nid { - Nid(ffi::NID_setct_CredRevReqTBS) - } - - pub fn setct_CredRevReqTBSX() -> Nid { - Nid(ffi::NID_setct_CredRevReqTBSX) - } - - pub fn setct_CredRevResData() -> Nid { - Nid(ffi::NID_setct_CredRevResData) - } - - pub fn setct_PCertReqData() -> Nid { - Nid(ffi::NID_setct_PCertReqData) - } - - pub fn setct_PCertResTBS() -> Nid { - Nid(ffi::NID_setct_PCertResTBS) - } - - pub fn setct_BatchAdminReqData() -> Nid { - Nid(ffi::NID_setct_BatchAdminReqData) - } - - pub fn setct_BatchAdminResData() -> Nid { - Nid(ffi::NID_setct_BatchAdminResData) - } - - pub fn setct_CardCInitResTBS() -> Nid { - Nid(ffi::NID_setct_CardCInitResTBS) - } - - pub fn setct_MeAqCInitResTBS() -> Nid { - Nid(ffi::NID_setct_MeAqCInitResTBS) - } - - pub fn setct_RegFormResTBS() -> Nid { - Nid(ffi::NID_setct_RegFormResTBS) - } - - pub fn setct_CertReqData() -> Nid { - Nid(ffi::NID_setct_CertReqData) - } - - pub fn setct_CertReqTBS() -> Nid { - Nid(ffi::NID_setct_CertReqTBS) - } - - pub fn setct_CertResData() -> Nid { - Nid(ffi::NID_setct_CertResData) - } - - pub fn setct_CertInqReqTBS() -> Nid { - Nid(ffi::NID_setct_CertInqReqTBS) - } - - pub fn setct_ErrorTBS() -> Nid { - Nid(ffi::NID_setct_ErrorTBS) - } - - pub fn setct_PIDualSignedTBE() -> Nid { - Nid(ffi::NID_setct_PIDualSignedTBE) - } - - pub fn setct_PIUnsignedTBE() -> Nid { - Nid(ffi::NID_setct_PIUnsignedTBE) - } - - pub fn setct_AuthReqTBE() -> Nid { - Nid(ffi::NID_setct_AuthReqTBE) - } - - pub fn setct_AuthResTBE() -> Nid { - Nid(ffi::NID_setct_AuthResTBE) - } - - pub fn setct_AuthResTBEX() -> Nid { - Nid(ffi::NID_setct_AuthResTBEX) - } - - pub fn setct_AuthTokenTBE() -> Nid { - Nid(ffi::NID_setct_AuthTokenTBE) - } - - pub fn setct_CapTokenTBE() -> Nid { - Nid(ffi::NID_setct_CapTokenTBE) - } - - pub fn setct_CapTokenTBEX() -> Nid { - Nid(ffi::NID_setct_CapTokenTBEX) - } - - pub fn setct_AcqCardCodeMsgTBE() -> Nid { - Nid(ffi::NID_setct_AcqCardCodeMsgTBE) - } - - pub fn setct_AuthRevReqTBE() -> Nid { - Nid(ffi::NID_setct_AuthRevReqTBE) - } - - pub fn setct_AuthRevResTBE() -> Nid { - Nid(ffi::NID_setct_AuthRevResTBE) - } - - pub fn setct_AuthRevResTBEB() -> Nid { - Nid(ffi::NID_setct_AuthRevResTBEB) - } - - pub fn setct_CapReqTBE() -> Nid { - Nid(ffi::NID_setct_CapReqTBE) - } - - pub fn setct_CapReqTBEX() -> Nid { - Nid(ffi::NID_setct_CapReqTBEX) - } - - pub fn setct_CapResTBE() -> Nid { - Nid(ffi::NID_setct_CapResTBE) - } - - pub fn setct_CapRevReqTBE() -> Nid { - Nid(ffi::NID_setct_CapRevReqTBE) - } - - pub fn setct_CapRevReqTBEX() -> Nid { - Nid(ffi::NID_setct_CapRevReqTBEX) - } - - pub fn setct_CapRevResTBE() -> Nid { - Nid(ffi::NID_setct_CapRevResTBE) - } - - pub fn setct_CredReqTBE() -> Nid { - Nid(ffi::NID_setct_CredReqTBE) - } - - pub fn setct_CredReqTBEX() -> Nid { - Nid(ffi::NID_setct_CredReqTBEX) - } - - pub fn setct_CredResTBE() -> Nid { - Nid(ffi::NID_setct_CredResTBE) - } - - pub fn setct_CredRevReqTBE() -> Nid { - Nid(ffi::NID_setct_CredRevReqTBE) - } - - pub fn setct_CredRevReqTBEX() -> Nid { - Nid(ffi::NID_setct_CredRevReqTBEX) - } - - pub fn setct_CredRevResTBE() -> Nid { - Nid(ffi::NID_setct_CredRevResTBE) - } - - pub fn setct_BatchAdminReqTBE() -> Nid { - Nid(ffi::NID_setct_BatchAdminReqTBE) - } - - pub fn setct_BatchAdminResTBE() -> Nid { - Nid(ffi::NID_setct_BatchAdminResTBE) - } - - pub fn setct_RegFormReqTBE() -> Nid { - Nid(ffi::NID_setct_RegFormReqTBE) - } - - pub fn setct_CertReqTBE() -> Nid { - Nid(ffi::NID_setct_CertReqTBE) - } - - pub fn setct_CertReqTBEX() -> Nid { - Nid(ffi::NID_setct_CertReqTBEX) - } - - pub fn setct_CertResTBE() -> Nid { - Nid(ffi::NID_setct_CertResTBE) - } - - pub fn setct_CRLNotificationTBS() -> Nid { - Nid(ffi::NID_setct_CRLNotificationTBS) - } - - pub fn setct_CRLNotificationResTBS() -> Nid { - Nid(ffi::NID_setct_CRLNotificationResTBS) - } - - pub fn setct_BCIDistributionTBS() -> Nid { - Nid(ffi::NID_setct_BCIDistributionTBS) - } - - pub fn setext_genCrypt() -> Nid { - Nid(ffi::NID_setext_genCrypt) - } - - pub fn setext_miAuth() -> Nid { - Nid(ffi::NID_setext_miAuth) - } - - pub fn setext_pinSecure() -> Nid { - Nid(ffi::NID_setext_pinSecure) - } - - pub fn setext_pinAny() -> Nid { - Nid(ffi::NID_setext_pinAny) - } - - pub fn setext_track2() -> Nid { - Nid(ffi::NID_setext_track2) - } - - pub fn setext_cv() -> Nid { - Nid(ffi::NID_setext_cv) - } - - pub fn set_policy_root() -> Nid { - Nid(ffi::NID_set_policy_root) - } - - pub fn setCext_hashedRoot() -> Nid { - Nid(ffi::NID_setCext_hashedRoot) - } - - pub fn setCext_certType() -> Nid { - Nid(ffi::NID_setCext_certType) - } - - pub fn setCext_merchData() -> Nid { - Nid(ffi::NID_setCext_merchData) - } - - pub fn setCext_cCertRequired() -> Nid { - Nid(ffi::NID_setCext_cCertRequired) - } - - pub fn setCext_tunneling() -> Nid { - Nid(ffi::NID_setCext_tunneling) - } - - pub fn setCext_setExt() -> Nid { - Nid(ffi::NID_setCext_setExt) - } - - pub fn setCext_setQualf() -> Nid { - Nid(ffi::NID_setCext_setQualf) - } - - pub fn setCext_PGWYcapabilities() -> Nid { - Nid(ffi::NID_setCext_PGWYcapabilities) - } - - pub fn setCext_TokenIdentifier() -> Nid { - Nid(ffi::NID_setCext_TokenIdentifier) - } - - pub fn setCext_Track2Data() -> Nid { - Nid(ffi::NID_setCext_Track2Data) - } - - pub fn setCext_TokenType() -> Nid { - Nid(ffi::NID_setCext_TokenType) - } - - pub fn setCext_IssuerCapabilities() -> Nid { - Nid(ffi::NID_setCext_IssuerCapabilities) - } - - pub fn setAttr_Cert() -> Nid { - Nid(ffi::NID_setAttr_Cert) - } - - pub fn setAttr_PGWYcap() -> Nid { - Nid(ffi::NID_setAttr_PGWYcap) - } - - pub fn setAttr_TokenType() -> Nid { - Nid(ffi::NID_setAttr_TokenType) - } - - pub fn setAttr_IssCap() -> Nid { - Nid(ffi::NID_setAttr_IssCap) - } - - pub fn set_rootKeyThumb() -> Nid { - Nid(ffi::NID_set_rootKeyThumb) - } - - pub fn set_addPolicy() -> Nid { - Nid(ffi::NID_set_addPolicy) - } - - pub fn setAttr_Token_EMV() -> Nid { - Nid(ffi::NID_setAttr_Token_EMV) - } - - pub fn setAttr_Token_B0Prime() -> Nid { - Nid(ffi::NID_setAttr_Token_B0Prime) - } - - pub fn setAttr_IssCap_CVM() -> Nid { - Nid(ffi::NID_setAttr_IssCap_CVM) - } - - pub fn setAttr_IssCap_T2() -> Nid { - Nid(ffi::NID_setAttr_IssCap_T2) - } - - pub fn setAttr_IssCap_Sig() -> Nid { - Nid(ffi::NID_setAttr_IssCap_Sig) - } - - pub fn setAttr_GenCryptgrm() -> Nid { - Nid(ffi::NID_setAttr_GenCryptgrm) - } - - pub fn setAttr_T2Enc() -> Nid { - Nid(ffi::NID_setAttr_T2Enc) - } - - pub fn setAttr_T2cleartxt() -> Nid { - Nid(ffi::NID_setAttr_T2cleartxt) - } - - pub fn setAttr_TokICCsig() -> Nid { - Nid(ffi::NID_setAttr_TokICCsig) - } - - pub fn setAttr_SecDevSig() -> Nid { - Nid(ffi::NID_setAttr_SecDevSig) - } - - pub fn set_brand_IATA_ATA() -> Nid { - Nid(ffi::NID_set_brand_IATA_ATA) - } - - pub fn set_brand_Diners() -> Nid { - Nid(ffi::NID_set_brand_Diners) - } - - pub fn set_brand_AmericanExpress() -> Nid { - Nid(ffi::NID_set_brand_AmericanExpress) - } - - pub fn set_brand_JCB() -> Nid { - Nid(ffi::NID_set_brand_JCB) - } - - pub fn set_brand_Visa() -> Nid { - Nid(ffi::NID_set_brand_Visa) - } - - pub fn set_brand_MasterCard() -> Nid { - Nid(ffi::NID_set_brand_MasterCard) - } - - pub fn set_brand_Novus() -> Nid { - Nid(ffi::NID_set_brand_Novus) - } - - pub fn des_cdmf() -> Nid { - Nid(ffi::NID_des_cdmf) - } - - pub fn rsaOAEPEncryptionSET() -> Nid { - Nid(ffi::NID_rsaOAEPEncryptionSET) - } - - pub fn ipsec3() -> Nid { - Nid(ffi::NID_ipsec3) - } - - pub fn ipsec4() -> Nid { - Nid(ffi::NID_ipsec4) - } - - pub fn whirlpool() -> Nid { - Nid(ffi::NID_whirlpool) - } - - pub fn cryptopro() -> Nid { - Nid(ffi::NID_cryptopro) - } - - pub fn cryptocom() -> Nid { - Nid(ffi::NID_cryptocom) - } - - pub fn id_GostR3411_94_with_GostR3410_2001() -> Nid { - Nid(ffi::NID_id_GostR3411_94_with_GostR3410_2001) - } - - pub fn id_GostR3411_94_with_GostR3410_94() -> Nid { - Nid(ffi::NID_id_GostR3411_94_with_GostR3410_94) - } - - pub fn id_GostR3411_94() -> Nid { - Nid(ffi::NID_id_GostR3411_94) - } - - pub fn id_HMACGostR3411_94() -> Nid { - Nid(ffi::NID_id_HMACGostR3411_94) - } - - pub fn id_GostR3410_2001() -> Nid { - Nid(ffi::NID_id_GostR3410_2001) - } - - pub fn id_GostR3410_94() -> Nid { - Nid(ffi::NID_id_GostR3410_94) - } - - pub fn id_Gost28147_89() -> Nid { - Nid(ffi::NID_id_Gost28147_89) - } - - pub fn gost89_cnt() -> Nid { - Nid(ffi::NID_gost89_cnt) - } - - pub fn id_Gost28147_89_MAC() -> Nid { - Nid(ffi::NID_id_Gost28147_89_MAC) - } - - pub fn id_GostR3411_94_prf() -> Nid { - Nid(ffi::NID_id_GostR3411_94_prf) - } - - pub fn id_GostR3410_2001DH() -> Nid { - Nid(ffi::NID_id_GostR3410_2001DH) - } - - pub fn id_GostR3410_94DH() -> Nid { - Nid(ffi::NID_id_GostR3410_94DH) - } - - pub fn id_Gost28147_89_CryptoPro_KeyMeshing() -> Nid { - Nid(ffi::NID_id_Gost28147_89_CryptoPro_KeyMeshing) - } - - pub fn id_Gost28147_89_None_KeyMeshing() -> Nid { - Nid(ffi::NID_id_Gost28147_89_None_KeyMeshing) - } - - pub fn id_GostR3411_94_TestParamSet() -> Nid { - Nid(ffi::NID_id_GostR3411_94_TestParamSet) - } - - pub fn id_GostR3411_94_CryptoProParamSet() -> Nid { - Nid(ffi::NID_id_GostR3411_94_CryptoProParamSet) - } - - pub fn id_Gost28147_89_TestParamSet() -> Nid { - Nid(ffi::NID_id_Gost28147_89_TestParamSet) - } - - pub fn id_Gost28147_89_CryptoPro_A_ParamSet() -> Nid { - Nid(ffi::NID_id_Gost28147_89_CryptoPro_A_ParamSet) - } - - pub fn id_Gost28147_89_CryptoPro_B_ParamSet() -> Nid { - Nid(ffi::NID_id_Gost28147_89_CryptoPro_B_ParamSet) - } - - pub fn id_Gost28147_89_CryptoPro_C_ParamSet() -> Nid { - Nid(ffi::NID_id_Gost28147_89_CryptoPro_C_ParamSet) - } - - pub fn id_Gost28147_89_CryptoPro_D_ParamSet() -> Nid { - Nid(ffi::NID_id_Gost28147_89_CryptoPro_D_ParamSet) - } - - pub fn id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet() -> Nid { - Nid(ffi::NID_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet) - } - - pub fn id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet() -> Nid { - Nid(ffi::NID_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet) - } - - pub fn id_Gost28147_89_CryptoPro_RIC_1_ParamSet() -> Nid { - Nid(ffi::NID_id_Gost28147_89_CryptoPro_RIC_1_ParamSet) - } - - pub fn id_GostR3410_94_TestParamSet() -> Nid { - Nid(ffi::NID_id_GostR3410_94_TestParamSet) - } - - pub fn id_GostR3410_94_CryptoPro_A_ParamSet() -> Nid { - Nid(ffi::NID_id_GostR3410_94_CryptoPro_A_ParamSet) - } - - pub fn id_GostR3410_94_CryptoPro_B_ParamSet() -> Nid { - Nid(ffi::NID_id_GostR3410_94_CryptoPro_B_ParamSet) - } - - pub fn id_GostR3410_94_CryptoPro_C_ParamSet() -> Nid { - Nid(ffi::NID_id_GostR3410_94_CryptoPro_C_ParamSet) - } - - pub fn id_GostR3410_94_CryptoPro_D_ParamSet() -> Nid { - Nid(ffi::NID_id_GostR3410_94_CryptoPro_D_ParamSet) - } - - pub fn id_GostR3410_94_CryptoPro_XchA_ParamSet() -> Nid { - Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchA_ParamSet) - } - - pub fn id_GostR3410_94_CryptoPro_XchB_ParamSet() -> Nid { - Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchB_ParamSet) - } - - pub fn id_GostR3410_94_CryptoPro_XchC_ParamSet() -> Nid { - Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchC_ParamSet) - } - - pub fn id_GostR3410_2001_TestParamSet() -> Nid { - Nid(ffi::NID_id_GostR3410_2001_TestParamSet) - } - - pub fn id_GostR3410_2001_CryptoPro_A_ParamSet() -> Nid { - Nid(ffi::NID_id_GostR3410_2001_CryptoPro_A_ParamSet) - } - - pub fn id_GostR3410_2001_CryptoPro_B_ParamSet() -> Nid { - Nid(ffi::NID_id_GostR3410_2001_CryptoPro_B_ParamSet) - } - - pub fn id_GostR3410_2001_CryptoPro_C_ParamSet() -> Nid { - Nid(ffi::NID_id_GostR3410_2001_CryptoPro_C_ParamSet) - } - - pub fn id_GostR3410_2001_CryptoPro_XchA_ParamSet() -> Nid { - Nid(ffi::NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet) - } - - pub fn id_GostR3410_2001_CryptoPro_XchB_ParamSet() -> Nid { - Nid(ffi::NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet) - } - - pub fn id_GostR3410_94_a() -> Nid { - Nid(ffi::NID_id_GostR3410_94_a) - } - - pub fn id_GostR3410_94_aBis() -> Nid { - Nid(ffi::NID_id_GostR3410_94_aBis) - } - - pub fn id_GostR3410_94_b() -> Nid { - Nid(ffi::NID_id_GostR3410_94_b) - } - - pub fn id_GostR3410_94_bBis() -> Nid { - Nid(ffi::NID_id_GostR3410_94_bBis) - } - - pub fn id_Gost28147_89_cc() -> Nid { - Nid(ffi::NID_id_Gost28147_89_cc) - } - - pub fn id_GostR3410_94_cc() -> Nid { - Nid(ffi::NID_id_GostR3410_94_cc) - } - - pub fn id_GostR3410_2001_cc() -> Nid { - Nid(ffi::NID_id_GostR3410_2001_cc) - } - - pub fn id_GostR3411_94_with_GostR3410_94_cc() -> Nid { - Nid(ffi::NID_id_GostR3411_94_with_GostR3410_94_cc) - } - - pub fn id_GostR3411_94_with_GostR3410_2001_cc() -> Nid { - Nid(ffi::NID_id_GostR3411_94_with_GostR3410_2001_cc) - } - - pub fn id_GostR3410_2001_ParamSet_cc() -> Nid { - Nid(ffi::NID_id_GostR3410_2001_ParamSet_cc) - } - - pub fn camellia_128_cbc() -> Nid { - Nid(ffi::NID_camellia_128_cbc) - } - - pub fn camellia_192_cbc() -> Nid { - Nid(ffi::NID_camellia_192_cbc) - } - - pub fn camellia_256_cbc() -> Nid { - Nid(ffi::NID_camellia_256_cbc) - } - - pub fn id_camellia128_wrap() -> Nid { - Nid(ffi::NID_id_camellia128_wrap) - } - - pub fn id_camellia192_wrap() -> Nid { - Nid(ffi::NID_id_camellia192_wrap) - } - - pub fn id_camellia256_wrap() -> Nid { - Nid(ffi::NID_id_camellia256_wrap) - } - - pub fn camellia_128_ecb() -> Nid { - Nid(ffi::NID_camellia_128_ecb) - } - - pub fn camellia_128_ofb128() -> Nid { - Nid(ffi::NID_camellia_128_ofb128) - } - - pub fn camellia_128_cfb128() -> Nid { - Nid(ffi::NID_camellia_128_cfb128) - } - - pub fn camellia_192_ecb() -> Nid { - Nid(ffi::NID_camellia_192_ecb) - } - - pub fn camellia_192_ofb128() -> Nid { - Nid(ffi::NID_camellia_192_ofb128) - } - - pub fn camellia_192_cfb128() -> Nid { - Nid(ffi::NID_camellia_192_cfb128) - } - - pub fn camellia_256_ecb() -> Nid { - Nid(ffi::NID_camellia_256_ecb) - } - - pub fn camellia_256_ofb128() -> Nid { - Nid(ffi::NID_camellia_256_ofb128) - } - - pub fn camellia_256_cfb128() -> Nid { - Nid(ffi::NID_camellia_256_cfb128) - } - - pub fn camellia_128_cfb1() -> Nid { - Nid(ffi::NID_camellia_128_cfb1) - } - - pub fn camellia_192_cfb1() -> Nid { - Nid(ffi::NID_camellia_192_cfb1) - } - - pub fn camellia_256_cfb1() -> Nid { - Nid(ffi::NID_camellia_256_cfb1) - } - - pub fn camellia_128_cfb8() -> Nid { - Nid(ffi::NID_camellia_128_cfb8) - } - - pub fn camellia_192_cfb8() -> Nid { - Nid(ffi::NID_camellia_192_cfb8) - } - - pub fn camellia_256_cfb8() -> Nid { - Nid(ffi::NID_camellia_256_cfb8) - } - - pub fn kisa() -> Nid { - Nid(ffi::NID_kisa) - } - - pub fn seed_ecb() -> Nid { - Nid(ffi::NID_seed_ecb) - } - - pub fn seed_cbc() -> Nid { - Nid(ffi::NID_seed_cbc) - } - - pub fn seed_cfb128() -> Nid { - Nid(ffi::NID_seed_cfb128) - } - - pub fn seed_ofb128() -> Nid { - Nid(ffi::NID_seed_ofb128) - } - - pub fn hmac() -> Nid { - Nid(ffi::NID_hmac) - } - - pub fn cmac() -> Nid { - Nid(ffi::NID_cmac) - } - - pub fn rc4_hmac_md5() -> Nid { - Nid(ffi::NID_rc4_hmac_md5) - } - - pub fn aes_128_cbc_hmac_sha1() -> Nid { - Nid(ffi::NID_aes_128_cbc_hmac_sha1) - } - - pub fn aes_192_cbc_hmac_sha1() -> Nid { - Nid(ffi::NID_aes_192_cbc_hmac_sha1) - } - - pub fn aes_256_cbc_hmac_sha1() -> Nid { - Nid(ffi::NID_aes_256_cbc_hmac_sha1) - } - - pub fn aes_128_cbc_hmac_sha256() -> Nid { - Nid(ffi::NID_aes_128_cbc_hmac_sha256) - } - - pub fn aes_192_cbc_hmac_sha256() -> Nid { - Nid(ffi::NID_aes_192_cbc_hmac_sha256) - } - - pub fn aes_256_cbc_hmac_sha256() -> Nid { - Nid(ffi::NID_aes_256_cbc_hmac_sha256) - } - - pub fn dhpublicnumber() -> Nid { - Nid(ffi::NID_dhpublicnumber) - } - - pub fn brainpoolP160r1() -> Nid { - Nid(ffi::NID_brainpoolP160r1) - } - - pub fn brainpoolP160t1() -> Nid { - Nid(ffi::NID_brainpoolP160t1) - } - - pub fn brainpoolP192r1() -> Nid { - Nid(ffi::NID_brainpoolP192r1) - } - - pub fn brainpoolP192t1() -> Nid { - Nid(ffi::NID_brainpoolP192t1) - } - - pub fn brainpoolP224r1() -> Nid { - Nid(ffi::NID_brainpoolP224r1) - } - - pub fn brainpoolP224t1() -> Nid { - Nid(ffi::NID_brainpoolP224t1) - } - - pub fn brainpoolP256r1() -> Nid { - Nid(ffi::NID_brainpoolP256r1) - } - - pub fn brainpoolP256t1() -> Nid { - Nid(ffi::NID_brainpoolP256t1) - } - - pub fn brainpoolP320r1() -> Nid { - Nid(ffi::NID_brainpoolP320r1) - } - - pub fn brainpoolP320t1() -> Nid { - Nid(ffi::NID_brainpoolP320t1) - } - - pub fn brainpoolP384r1() -> Nid { - Nid(ffi::NID_brainpoolP384r1) - } - - pub fn brainpoolP384t1() -> Nid { - Nid(ffi::NID_brainpoolP384t1) - } - - pub fn brainpoolP512r1() -> Nid { - Nid(ffi::NID_brainpoolP512r1) - } - - pub fn brainpoolP512t1() -> Nid { - Nid(ffi::NID_brainpoolP512t1) - } - - pub fn dhSinglePass_stdDH_sha1kdf_scheme() -> Nid { - Nid(ffi::NID_dhSinglePass_stdDH_sha1kdf_scheme) - } - - pub fn dhSinglePass_stdDH_sha224kdf_scheme() -> Nid { - Nid(ffi::NID_dhSinglePass_stdDH_sha224kdf_scheme) - } - - pub fn dhSinglePass_stdDH_sha256kdf_scheme() -> Nid { - Nid(ffi::NID_dhSinglePass_stdDH_sha256kdf_scheme) - } - - pub fn dhSinglePass_stdDH_sha384kdf_scheme() -> Nid { - Nid(ffi::NID_dhSinglePass_stdDH_sha384kdf_scheme) - } - - pub fn dhSinglePass_stdDH_sha512kdf_scheme() -> Nid { - Nid(ffi::NID_dhSinglePass_stdDH_sha512kdf_scheme) - } - - pub fn dhSinglePass_cofactorDH_sha1kdf_scheme() -> Nid { - Nid(ffi::NID_dhSinglePass_cofactorDH_sha1kdf_scheme) - } - - pub fn dhSinglePass_cofactorDH_sha224kdf_scheme() -> Nid { - Nid(ffi::NID_dhSinglePass_cofactorDH_sha224kdf_scheme) - } - - pub fn dhSinglePass_cofactorDH_sha256kdf_scheme() -> Nid { - Nid(ffi::NID_dhSinglePass_cofactorDH_sha256kdf_scheme) - } - - pub fn dhSinglePass_cofactorDH_sha384kdf_scheme() -> Nid { - Nid(ffi::NID_dhSinglePass_cofactorDH_sha384kdf_scheme) - } - - pub fn dhSinglePass_cofactorDH_sha512kdf_scheme() -> Nid { - Nid(ffi::NID_dhSinglePass_cofactorDH_sha512kdf_scheme) - } - - pub fn dh_std_kdf() -> Nid { - Nid(ffi::NID_dh_std_kdf) - } - - pub fn dh_cofactor_kdf() -> Nid { - Nid(ffi::NID_dh_cofactor_kdf) - } - - pub fn ct_precert_scts() -> Nid { - Nid(ffi::NID_ct_precert_scts) - } - - pub fn ct_precert_poison() -> Nid { - Nid(ffi::NID_ct_precert_poison) - } - - pub fn ct_precert_signer() -> Nid { - Nid(ffi::NID_ct_precert_signer) - } - - pub fn ct_cert_scts() -> Nid { - Nid(ffi::NID_ct_cert_scts) - } - - pub fn jurisdictionLocalityName() -> Nid { - Nid(ffi::NID_jurisdictionLocalityName) - } - - pub fn jurisdictionStateOrProvinceName() -> Nid { - Nid(ffi::NID_jurisdictionStateOrProvinceName) - } - - pub fn jurisdictionCountryName() -> Nid { - Nid(ffi::NID_jurisdictionCountryName) - } -} \ No newline at end of file +} + +pub const UNDEF: Nid = Nid(ffi::NID_undef); +pub const ITU_T: Nid = Nid(ffi::NID_itu_t); +pub const CCITT: Nid = Nid(ffi::NID_ccitt); +pub const ISO: Nid = Nid(ffi::NID_iso); +pub const JOINT_ISO_ITU_T: Nid = Nid(ffi::NID_joint_iso_itu_t); +pub const JOINT_ISO_CCITT: Nid = Nid(ffi::NID_joint_iso_ccitt); +pub const MEMBER_BODY: Nid = Nid(ffi::NID_member_body); +pub const IDENTIFIED_ORGANIZATION: Nid = Nid(ffi::NID_identified_organization); +pub const HMAC_MD5: Nid = Nid(ffi::NID_hmac_md5); +pub const HMAC_SHA1: Nid = Nid(ffi::NID_hmac_sha1); +pub const CERTICOM_ARC: Nid = Nid(ffi::NID_certicom_arc); +pub const INTERNATIONAL_ORGANIZATIONS: Nid = Nid(ffi::NID_international_organizations); +pub const WAP: Nid = Nid(ffi::NID_wap); +pub const WAP_WSG: Nid = Nid(ffi::NID_wap_wsg); +pub const SELECTED_ATTRIBUTE_TYPES: Nid = Nid(ffi::NID_selected_attribute_types); +pub const CLEARANCE: Nid = Nid(ffi::NID_clearance); +pub const ISO_US: Nid = Nid(ffi::NID_ISO_US); +pub const X9_57: Nid = Nid(ffi::NID_X9_57); +pub const X9CM: Nid = Nid(ffi::NID_X9cm); +pub const DSA: Nid = Nid(ffi::NID_dsa); +pub const DSAWITHSHA1: Nid = Nid(ffi::NID_dsaWithSHA1); +pub const ANSI_X9_62: Nid = Nid(ffi::NID_ansi_X9_62); +pub const X9_62_PRIME_FIELD: Nid = Nid(ffi::NID_X9_62_prime_field); +pub const X9_62_CHARACTERISTIC_TWO_FIELD: Nid = Nid(ffi::NID_X9_62_characteristic_two_field); +pub const X9_62_ID_CHARACTERISTIC_TWO_BASIS: Nid = Nid(ffi::NID_X9_62_id_characteristic_two_basis); +pub const X9_62_ONBASIS: Nid = Nid(ffi::NID_X9_62_onBasis); +pub const X9_62_TPBASIS: Nid = Nid(ffi::NID_X9_62_tpBasis); +pub const X9_62_PPBASIS: Nid = Nid(ffi::NID_X9_62_ppBasis); +pub const X9_62_ID_ECPUBLICKEY: Nid = Nid(ffi::NID_X9_62_id_ecPublicKey); +pub const X9_62_C2PNB163V1: Nid = Nid(ffi::NID_X9_62_c2pnb163v1); +pub const X9_62_C2PNB163V2: Nid = Nid(ffi::NID_X9_62_c2pnb163v2); +pub const X9_62_C2PNB163V3: Nid = Nid(ffi::NID_X9_62_c2pnb163v3); +pub const X9_62_C2PNB176V1: Nid = Nid(ffi::NID_X9_62_c2pnb176v1); +pub const X9_62_C2TNB191V1: Nid = Nid(ffi::NID_X9_62_c2tnb191v1); +pub const X9_62_C2TNB191V2: Nid = Nid(ffi::NID_X9_62_c2tnb191v2); +pub const X9_62_C2TNB191V3: Nid = Nid(ffi::NID_X9_62_c2tnb191v3); +pub const X9_62_C2ONB191V4: Nid = Nid(ffi::NID_X9_62_c2onb191v4); +pub const X9_62_C2ONB191V5: Nid = Nid(ffi::NID_X9_62_c2onb191v5); +pub const X9_62_C2PNB208W1: Nid = Nid(ffi::NID_X9_62_c2pnb208w1); +pub const X9_62_C2TNB239V1: Nid = Nid(ffi::NID_X9_62_c2tnb239v1); +pub const X9_62_C2TNB239V2: Nid = Nid(ffi::NID_X9_62_c2tnb239v2); +pub const X9_62_C2TNB239V3: Nid = Nid(ffi::NID_X9_62_c2tnb239v3); +pub const X9_62_C2ONB239V4: Nid = Nid(ffi::NID_X9_62_c2onb239v4); +pub const X9_62_C2ONB239V5: Nid = Nid(ffi::NID_X9_62_c2onb239v5); +pub const X9_62_C2PNB272W1: Nid = Nid(ffi::NID_X9_62_c2pnb272w1); +pub const X9_62_C2PNB304W1: Nid = Nid(ffi::NID_X9_62_c2pnb304w1); +pub const X9_62_C2TNB359V1: Nid = Nid(ffi::NID_X9_62_c2tnb359v1); +pub const X9_62_C2PNB368W1: Nid = Nid(ffi::NID_X9_62_c2pnb368w1); +pub const X9_62_C2TNB431R1: Nid = Nid(ffi::NID_X9_62_c2tnb431r1); +pub const X9_62_PRIME192V1: Nid = Nid(ffi::NID_X9_62_prime192v1); +pub const X9_62_PRIME192V2: Nid = Nid(ffi::NID_X9_62_prime192v2); +pub const X9_62_PRIME192V3: Nid = Nid(ffi::NID_X9_62_prime192v3); +pub const X9_62_PRIME239V1: Nid = Nid(ffi::NID_X9_62_prime239v1); +pub const X9_62_PRIME239V2: Nid = Nid(ffi::NID_X9_62_prime239v2); +pub const X9_62_PRIME239V3: Nid = Nid(ffi::NID_X9_62_prime239v3); +pub const X9_62_PRIME256V1: Nid = Nid(ffi::NID_X9_62_prime256v1); +pub const ECDSA_WITH_SHA1: Nid = Nid(ffi::NID_ecdsa_with_SHA1); +pub const ECDSA_WITH_RECOMMENDED: Nid = Nid(ffi::NID_ecdsa_with_Recommended); +pub const ECDSA_WITH_SPECIFIED: Nid = Nid(ffi::NID_ecdsa_with_Specified); +pub const ECDSA_WITH_SHA224: Nid = Nid(ffi::NID_ecdsa_with_SHA224); +pub const ECDSA_WITH_SHA256: Nid = Nid(ffi::NID_ecdsa_with_SHA256); +pub const ECDSA_WITH_SHA384: Nid = Nid(ffi::NID_ecdsa_with_SHA384); +pub const ECDSA_WITH_SHA512: Nid = Nid(ffi::NID_ecdsa_with_SHA512); +pub const SECP112R1: Nid = Nid(ffi::NID_secp112r1); +pub const SECP112R2: Nid = Nid(ffi::NID_secp112r2); +pub const SECP128R1: Nid = Nid(ffi::NID_secp128r1); +pub const SECP128R2: Nid = Nid(ffi::NID_secp128r2); +pub const SECP160K1: Nid = Nid(ffi::NID_secp160k1); +pub const SECP160R1: Nid = Nid(ffi::NID_secp160r1); +pub const SECP160R2: Nid = Nid(ffi::NID_secp160r2); +pub const SECP192K1: Nid = Nid(ffi::NID_secp192k1); +pub const SECP224K1: Nid = Nid(ffi::NID_secp224k1); +pub const SECP224R1: Nid = Nid(ffi::NID_secp224r1); +pub const SECP256K1: Nid = Nid(ffi::NID_secp256k1); +pub const SECP384R1: Nid = Nid(ffi::NID_secp384r1); +pub const SECP521R1: Nid = Nid(ffi::NID_secp521r1); +pub const SECT113R1: Nid = Nid(ffi::NID_sect113r1); +pub const SECT113R2: Nid = Nid(ffi::NID_sect113r2); +pub const SECT131R1: Nid = Nid(ffi::NID_sect131r1); +pub const SECT131R2: Nid = Nid(ffi::NID_sect131r2); +pub const SECT163K1: Nid = Nid(ffi::NID_sect163k1); +pub const SECT163R1: Nid = Nid(ffi::NID_sect163r1); +pub const SECT163R2: Nid = Nid(ffi::NID_sect163r2); +pub const SECT193R1: Nid = Nid(ffi::NID_sect193r1); +pub const SECT193R2: Nid = Nid(ffi::NID_sect193r2); +pub const SECT233K1: Nid = Nid(ffi::NID_sect233k1); +pub const SECT233R1: Nid = Nid(ffi::NID_sect233r1); +pub const SECT239K1: Nid = Nid(ffi::NID_sect239k1); +pub const SECT283K1: Nid = Nid(ffi::NID_sect283k1); +pub const SECT283R1: Nid = Nid(ffi::NID_sect283r1); +pub const SECT409K1: Nid = Nid(ffi::NID_sect409k1); +pub const SECT409R1: Nid = Nid(ffi::NID_sect409r1); +pub const SECT571K1: Nid = Nid(ffi::NID_sect571k1); +pub const SECT571R1: Nid = Nid(ffi::NID_sect571r1); +pub const WAP_WSG_IDM_ECID_WTLS1: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls1); +pub const WAP_WSG_IDM_ECID_WTLS3: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls3); +pub const WAP_WSG_IDM_ECID_WTLS4: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls4); +pub const WAP_WSG_IDM_ECID_WTLS5: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls5); +pub const WAP_WSG_IDM_ECID_WTLS6: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls6); +pub const WAP_WSG_IDM_ECID_WTLS7: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls7); +pub const WAP_WSG_IDM_ECID_WTLS8: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls8); +pub const WAP_WSG_IDM_ECID_WTLS9: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls9); +pub const WAP_WSG_IDM_ECID_WTLS10: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls10); +pub const WAP_WSG_IDM_ECID_WTLS11: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls11); +pub const WAP_WSG_IDM_ECID_WTLS12: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls12); +pub const CAST5_CBC: Nid = Nid(ffi::NID_cast5_cbc); +pub const CAST5_ECB: Nid = Nid(ffi::NID_cast5_ecb); +pub const CAST5_CFB64: Nid = Nid(ffi::NID_cast5_cfb64); +pub const CAST5_OFB64: Nid = Nid(ffi::NID_cast5_ofb64); +pub const PBEWITHMD5ANDCAST5_CBC: Nid = Nid(ffi::NID_pbeWithMD5AndCast5_CBC); +pub const ID_PASSWORDBASEDMAC: Nid = Nid(ffi::NID_id_PasswordBasedMAC); +pub const ID_DHBASEDMAC: Nid = Nid(ffi::NID_id_DHBasedMac); +pub const RSADSI: Nid = Nid(ffi::NID_rsadsi); +pub const PKCS: Nid = Nid(ffi::NID_pkcs); +pub const PKCS1: Nid = Nid(ffi::NID_pkcs1); +pub const RSAENCRYPTION: Nid = Nid(ffi::NID_rsaEncryption); +pub const MD2WITHRSAENCRYPTION: Nid = Nid(ffi::NID_md2WithRSAEncryption); +pub const MD4WITHRSAENCRYPTION: Nid = Nid(ffi::NID_md4WithRSAEncryption); +pub const MD5WITHRSAENCRYPTION: Nid = Nid(ffi::NID_md5WithRSAEncryption); +pub const SHA1WITHRSAENCRYPTION: Nid = Nid(ffi::NID_sha1WithRSAEncryption); +pub const RSAESOAEP: Nid = Nid(ffi::NID_rsaesOaep); +pub const MGF1: Nid = Nid(ffi::NID_mgf1); +pub const PSPECIFIED: Nid = Nid(ffi::NID_pSpecified); +pub const RSASSAPSS: Nid = Nid(ffi::NID_rsassaPss); +pub const SHA256WITHRSAENCRYPTION: Nid = Nid(ffi::NID_sha256WithRSAEncryption); +pub const SHA384WITHRSAENCRYPTION: Nid = Nid(ffi::NID_sha384WithRSAEncryption); +pub const SHA512WITHRSAENCRYPTION: Nid = Nid(ffi::NID_sha512WithRSAEncryption); +pub const SHA224WITHRSAENCRYPTION: Nid = Nid(ffi::NID_sha224WithRSAEncryption); +pub const PKCS3: Nid = Nid(ffi::NID_pkcs3); +pub const DHKEYAGREEMENT: Nid = Nid(ffi::NID_dhKeyAgreement); +pub const PKCS5: Nid = Nid(ffi::NID_pkcs5); +pub const PBEWITHMD2ANDDES_CBC: Nid = Nid(ffi::NID_pbeWithMD2AndDES_CBC); +pub const PBEWITHMD5ANDDES_CBC: Nid = Nid(ffi::NID_pbeWithMD5AndDES_CBC); +pub const PBEWITHMD2ANDRC2_CBC: Nid = Nid(ffi::NID_pbeWithMD2AndRC2_CBC); +pub const PBEWITHMD5ANDRC2_CBC: Nid = Nid(ffi::NID_pbeWithMD5AndRC2_CBC); +pub const PBEWITHSHA1ANDDES_CBC: Nid = Nid(ffi::NID_pbeWithSHA1AndDES_CBC); +pub const PBEWITHSHA1ANDRC2_CBC: Nid = Nid(ffi::NID_pbeWithSHA1AndRC2_CBC); +pub const ID_PBKDF2: Nid = Nid(ffi::NID_id_pbkdf2); +pub const PBES2: Nid = Nid(ffi::NID_pbes2); +pub const PBMAC1: Nid = Nid(ffi::NID_pbmac1); +pub const PKCS7: Nid = Nid(ffi::NID_pkcs7); +pub const PKCS7_DATA: Nid = Nid(ffi::NID_pkcs7_data); +pub const PKCS7_SIGNED: Nid = Nid(ffi::NID_pkcs7_signed); +pub const PKCS7_ENVELOPED: Nid = Nid(ffi::NID_pkcs7_enveloped); +pub const PKCS7_SIGNEDANDENVELOPED: Nid = Nid(ffi::NID_pkcs7_signedAndEnveloped); +pub const PKCS7_DIGEST: Nid = Nid(ffi::NID_pkcs7_digest); +pub const PKCS7_ENCRYPTED: Nid = Nid(ffi::NID_pkcs7_encrypted); +pub const PKCS9: Nid = Nid(ffi::NID_pkcs9); +pub const PKCS9_EMAILADDRESS: Nid = Nid(ffi::NID_pkcs9_emailAddress); +pub const PKCS9_UNSTRUCTUREDNAME: Nid = Nid(ffi::NID_pkcs9_unstructuredName); +pub const PKCS9_CONTENTTYPE: Nid = Nid(ffi::NID_pkcs9_contentType); +pub const PKCS9_MESSAGEDIGEST: Nid = Nid(ffi::NID_pkcs9_messageDigest); +pub const PKCS9_SIGNINGTIME: Nid = Nid(ffi::NID_pkcs9_signingTime); +pub const PKCS9_COUNTERSIGNATURE: Nid = Nid(ffi::NID_pkcs9_countersignature); +pub const PKCS9_CHALLENGEPASSWORD: Nid = Nid(ffi::NID_pkcs9_challengePassword); +pub const PKCS9_UNSTRUCTUREDADDRESS: Nid = Nid(ffi::NID_pkcs9_unstructuredAddress); +pub const PKCS9_EXTCERTATTRIBUTES: Nid = Nid(ffi::NID_pkcs9_extCertAttributes); +pub const EXT_REQ: Nid = Nid(ffi::NID_ext_req); +pub const SMIMECAPABILITIES: Nid = Nid(ffi::NID_SMIMECapabilities); +pub const SMIME: Nid = Nid(ffi::NID_SMIME); +pub const ID_SMIME_MOD: Nid = Nid(ffi::NID_id_smime_mod); +pub const ID_SMIME_CT: Nid = Nid(ffi::NID_id_smime_ct); +pub const ID_SMIME_AA: Nid = Nid(ffi::NID_id_smime_aa); +pub const ID_SMIME_ALG: Nid = Nid(ffi::NID_id_smime_alg); +pub const ID_SMIME_CD: Nid = Nid(ffi::NID_id_smime_cd); +pub const ID_SMIME_SPQ: Nid = Nid(ffi::NID_id_smime_spq); +pub const ID_SMIME_CTI: Nid = Nid(ffi::NID_id_smime_cti); +pub const ID_SMIME_MOD_CMS: Nid = Nid(ffi::NID_id_smime_mod_cms); +pub const ID_SMIME_MOD_ESS: Nid = Nid(ffi::NID_id_smime_mod_ess); +pub const ID_SMIME_MOD_OID: Nid = Nid(ffi::NID_id_smime_mod_oid); +pub const ID_SMIME_MOD_MSG_V3: Nid = Nid(ffi::NID_id_smime_mod_msg_v3); +pub const ID_SMIME_MOD_ETS_ESIGNATURE_88: Nid = Nid(ffi::NID_id_smime_mod_ets_eSignature_88); +pub const ID_SMIME_MOD_ETS_ESIGNATURE_97: Nid = Nid(ffi::NID_id_smime_mod_ets_eSignature_97); +pub const ID_SMIME_MOD_ETS_ESIGPOLICY_88: Nid = Nid(ffi::NID_id_smime_mod_ets_eSigPolicy_88); +pub const ID_SMIME_MOD_ETS_ESIGPOLICY_97: Nid = Nid(ffi::NID_id_smime_mod_ets_eSigPolicy_97); +pub const ID_SMIME_CT_RECEIPT: Nid = Nid(ffi::NID_id_smime_ct_receipt); +pub const ID_SMIME_CT_AUTHDATA: Nid = Nid(ffi::NID_id_smime_ct_authData); +pub const ID_SMIME_CT_PUBLISHCERT: Nid = Nid(ffi::NID_id_smime_ct_publishCert); +pub const ID_SMIME_CT_TSTINFO: Nid = Nid(ffi::NID_id_smime_ct_TSTInfo); +pub const ID_SMIME_CT_TDTINFO: Nid = Nid(ffi::NID_id_smime_ct_TDTInfo); +pub const ID_SMIME_CT_CONTENTINFO: Nid = Nid(ffi::NID_id_smime_ct_contentInfo); +pub const ID_SMIME_CT_DVCSREQUESTDATA: Nid = Nid(ffi::NID_id_smime_ct_DVCSRequestData); +pub const ID_SMIME_CT_DVCSRESPONSEDATA: Nid = Nid(ffi::NID_id_smime_ct_DVCSResponseData); +pub const ID_SMIME_CT_COMPRESSEDDATA: Nid = Nid(ffi::NID_id_smime_ct_compressedData); +pub const ID_CT_ASCIITEXTWITHCRLF: Nid = Nid(ffi::NID_id_ct_asciiTextWithCRLF); +pub const ID_SMIME_AA_RECEIPTREQUEST: Nid = Nid(ffi::NID_id_smime_aa_receiptRequest); +pub const ID_SMIME_AA_SECURITYLABEL: Nid = Nid(ffi::NID_id_smime_aa_securityLabel); +pub const ID_SMIME_AA_MLEXPANDHISTORY: Nid = Nid(ffi::NID_id_smime_aa_mlExpandHistory); +pub const ID_SMIME_AA_CONTENTHINT: Nid = Nid(ffi::NID_id_smime_aa_contentHint); +pub const ID_SMIME_AA_MSGSIGDIGEST: Nid = Nid(ffi::NID_id_smime_aa_msgSigDigest); +pub const ID_SMIME_AA_ENCAPCONTENTTYPE: Nid = Nid(ffi::NID_id_smime_aa_encapContentType); +pub const ID_SMIME_AA_CONTENTIDENTIFIER: Nid = Nid(ffi::NID_id_smime_aa_contentIdentifier); +pub const ID_SMIME_AA_MACVALUE: Nid = Nid(ffi::NID_id_smime_aa_macValue); +pub const ID_SMIME_AA_EQUIVALENTLABELS: Nid = Nid(ffi::NID_id_smime_aa_equivalentLabels); +pub const ID_SMIME_AA_CONTENTREFERENCE: Nid = Nid(ffi::NID_id_smime_aa_contentReference); +pub const ID_SMIME_AA_ENCRYPKEYPREF: Nid = Nid(ffi::NID_id_smime_aa_encrypKeyPref); +pub const ID_SMIME_AA_SIGNINGCERTIFICATE: Nid = Nid(ffi::NID_id_smime_aa_signingCertificate); +pub const ID_SMIME_AA_SMIMEENCRYPTCERTS: Nid = Nid(ffi::NID_id_smime_aa_smimeEncryptCerts); +pub const ID_SMIME_AA_TIMESTAMPTOKEN: Nid = Nid(ffi::NID_id_smime_aa_timeStampToken); +pub const ID_SMIME_AA_ETS_SIGPOLICYID: Nid = Nid(ffi::NID_id_smime_aa_ets_sigPolicyId); +pub const ID_SMIME_AA_ETS_COMMITMENTTYPE: Nid = Nid(ffi::NID_id_smime_aa_ets_commitmentType); +pub const ID_SMIME_AA_ETS_SIGNERLOCATION: Nid = Nid(ffi::NID_id_smime_aa_ets_signerLocation); +pub const ID_SMIME_AA_ETS_SIGNERATTR: Nid = Nid(ffi::NID_id_smime_aa_ets_signerAttr); +pub const ID_SMIME_AA_ETS_OTHERSIGCERT: Nid = Nid(ffi::NID_id_smime_aa_ets_otherSigCert); +pub const ID_SMIME_AA_ETS_CONTENTTIMESTAMP: Nid = Nid(ffi::NID_id_smime_aa_ets_contentTimestamp); +pub const ID_SMIME_AA_ETS_CERTIFICATEREFS: Nid = Nid(ffi::NID_id_smime_aa_ets_CertificateRefs); +pub const ID_SMIME_AA_ETS_REVOCATIONREFS: Nid = Nid(ffi::NID_id_smime_aa_ets_RevocationRefs); +pub const ID_SMIME_AA_ETS_CERTVALUES: Nid = Nid(ffi::NID_id_smime_aa_ets_certValues); +pub const ID_SMIME_AA_ETS_REVOCATIONVALUES: Nid = Nid(ffi::NID_id_smime_aa_ets_revocationValues); +pub const ID_SMIME_AA_ETS_ESCTIMESTAMP: Nid = Nid(ffi::NID_id_smime_aa_ets_escTimeStamp); +pub const ID_SMIME_AA_ETS_CERTCRLTIMESTAMP: Nid = Nid(ffi::NID_id_smime_aa_ets_certCRLTimestamp); +pub const ID_SMIME_AA_ETS_ARCHIVETIMESTAMP: Nid = Nid(ffi::NID_id_smime_aa_ets_archiveTimeStamp); +pub const ID_SMIME_AA_SIGNATURETYPE: Nid = Nid(ffi::NID_id_smime_aa_signatureType); +pub const ID_SMIME_AA_DVCS_DVC: Nid = Nid(ffi::NID_id_smime_aa_dvcs_dvc); +pub const ID_SMIME_ALG_ESDHWITH3DES: Nid = Nid(ffi::NID_id_smime_alg_ESDHwith3DES); +pub const ID_SMIME_ALG_ESDHWITHRC2: Nid = Nid(ffi::NID_id_smime_alg_ESDHwithRC2); +pub const ID_SMIME_ALG_3DESWRAP: Nid = Nid(ffi::NID_id_smime_alg_3DESwrap); +pub const ID_SMIME_ALG_RC2WRAP: Nid = Nid(ffi::NID_id_smime_alg_RC2wrap); +pub const ID_SMIME_ALG_ESDH: Nid = Nid(ffi::NID_id_smime_alg_ESDH); +pub const ID_SMIME_ALG_CMS3DESWRAP: Nid = Nid(ffi::NID_id_smime_alg_CMS3DESwrap); +pub const ID_SMIME_ALG_CMSRC2WRAP: Nid = Nid(ffi::NID_id_smime_alg_CMSRC2wrap); +pub const ID_ALG_PWRI_KEK: Nid = Nid(ffi::NID_id_alg_PWRI_KEK); +pub const ID_SMIME_CD_LDAP: Nid = Nid(ffi::NID_id_smime_cd_ldap); +pub const ID_SMIME_SPQ_ETS_SQT_URI: Nid = Nid(ffi::NID_id_smime_spq_ets_sqt_uri); +pub const ID_SMIME_SPQ_ETS_SQT_UNOTICE: Nid = Nid(ffi::NID_id_smime_spq_ets_sqt_unotice); +pub const ID_SMIME_CTI_ETS_PROOFOFORIGIN: Nid = Nid(ffi::NID_id_smime_cti_ets_proofOfOrigin); +pub const ID_SMIME_CTI_ETS_PROOFOFRECEIPT: Nid = Nid(ffi::NID_id_smime_cti_ets_proofOfReceipt); +pub const ID_SMIME_CTI_ETS_PROOFOFDELIVERY: Nid = Nid(ffi::NID_id_smime_cti_ets_proofOfDelivery); +pub const ID_SMIME_CTI_ETS_PROOFOFSENDER: Nid = Nid(ffi::NID_id_smime_cti_ets_proofOfSender); +pub const ID_SMIME_CTI_ETS_PROOFOFAPPROVAL: Nid = Nid(ffi::NID_id_smime_cti_ets_proofOfApproval); +pub const ID_SMIME_CTI_ETS_PROOFOFCREATION: Nid = Nid(ffi::NID_id_smime_cti_ets_proofOfCreation); +pub const FRIENDLYNAME: Nid = Nid(ffi::NID_friendlyName); +pub const LOCALKEYID: Nid = Nid(ffi::NID_localKeyID); +pub const MS_CSP_NAME: Nid = Nid(ffi::NID_ms_csp_name); +pub const LOCALKEYSET: Nid = Nid(ffi::NID_LocalKeySet); +pub const X509CERTIFICATE: Nid = Nid(ffi::NID_x509Certificate); +pub const SDSICERTIFICATE: Nid = Nid(ffi::NID_sdsiCertificate); +pub const X509CRL: Nid = Nid(ffi::NID_x509Crl); +pub const PBE_WITHSHA1AND128BITRC4: Nid = Nid(ffi::NID_pbe_WithSHA1And128BitRC4); +pub const PBE_WITHSHA1AND40BITRC4: Nid = Nid(ffi::NID_pbe_WithSHA1And40BitRC4); +pub const PBE_WITHSHA1AND3_KEY_TRIPLEDES_CBC: Nid = Nid(ffi::NID_pbe_WithSHA1And3_Key_TripleDES_CBC); +pub const PBE_WITHSHA1AND2_KEY_TRIPLEDES_CBC: Nid = Nid(ffi::NID_pbe_WithSHA1And2_Key_TripleDES_CBC); +pub const PBE_WITHSHA1AND128BITRC2_CBC: Nid = Nid(ffi::NID_pbe_WithSHA1And128BitRC2_CBC); +pub const PBE_WITHSHA1AND40BITRC2_CBC: Nid = Nid(ffi::NID_pbe_WithSHA1And40BitRC2_CBC); +pub const KEYBAG: Nid = Nid(ffi::NID_keyBag); +pub const PKCS8SHROUDEDKEYBAG: Nid = Nid(ffi::NID_pkcs8ShroudedKeyBag); +pub const CERTBAG: Nid = Nid(ffi::NID_certBag); +pub const CRLBAG: Nid = Nid(ffi::NID_crlBag); +pub const SECRETBAG: Nid = Nid(ffi::NID_secretBag); +pub const SAFECONTENTSBAG: Nid = Nid(ffi::NID_safeContentsBag); +pub const MD2: Nid = Nid(ffi::NID_md2); +pub const MD4: Nid = Nid(ffi::NID_md4); +pub const MD5: Nid = Nid(ffi::NID_md5); +pub const MD5_SHA1: Nid = Nid(ffi::NID_md5_sha1); +pub const HMACWITHMD5: Nid = Nid(ffi::NID_hmacWithMD5); +pub const HMACWITHSHA1: Nid = Nid(ffi::NID_hmacWithSHA1); +pub const HMACWITHSHA224: Nid = Nid(ffi::NID_hmacWithSHA224); +pub const HMACWITHSHA256: Nid = Nid(ffi::NID_hmacWithSHA256); +pub const HMACWITHSHA384: Nid = Nid(ffi::NID_hmacWithSHA384); +pub const HMACWITHSHA512: Nid = Nid(ffi::NID_hmacWithSHA512); +pub const RC2_CBC: Nid = Nid(ffi::NID_rc2_cbc); +pub const RC2_ECB: Nid = Nid(ffi::NID_rc2_ecb); +pub const RC2_CFB64: Nid = Nid(ffi::NID_rc2_cfb64); +pub const RC2_OFB64: Nid = Nid(ffi::NID_rc2_ofb64); +pub const RC2_40_CBC: Nid = Nid(ffi::NID_rc2_40_cbc); +pub const RC2_64_CBC: Nid = Nid(ffi::NID_rc2_64_cbc); +pub const RC4: Nid = Nid(ffi::NID_rc4); +pub const RC4_40: Nid = Nid(ffi::NID_rc4_40); +pub const DES_EDE3_CBC: Nid = Nid(ffi::NID_des_ede3_cbc); +pub const RC5_CBC: Nid = Nid(ffi::NID_rc5_cbc); +pub const RC5_ECB: Nid = Nid(ffi::NID_rc5_ecb); +pub const RC5_CFB64: Nid = Nid(ffi::NID_rc5_cfb64); +pub const RC5_OFB64: Nid = Nid(ffi::NID_rc5_ofb64); +pub const MS_EXT_REQ: Nid = Nid(ffi::NID_ms_ext_req); +pub const MS_CODE_IND: Nid = Nid(ffi::NID_ms_code_ind); +pub const MS_CODE_COM: Nid = Nid(ffi::NID_ms_code_com); +pub const MS_CTL_SIGN: Nid = Nid(ffi::NID_ms_ctl_sign); +pub const MS_SGC: Nid = Nid(ffi::NID_ms_sgc); +pub const MS_EFS: Nid = Nid(ffi::NID_ms_efs); +pub const MS_SMARTCARD_LOGIN: Nid = Nid(ffi::NID_ms_smartcard_login); +pub const MS_UPN: Nid = Nid(ffi::NID_ms_upn); +pub const IDEA_CBC: Nid = Nid(ffi::NID_idea_cbc); +pub const IDEA_ECB: Nid = Nid(ffi::NID_idea_ecb); +pub const IDEA_CFB64: Nid = Nid(ffi::NID_idea_cfb64); +pub const IDEA_OFB64: Nid = Nid(ffi::NID_idea_ofb64); +pub const BF_CBC: Nid = Nid(ffi::NID_bf_cbc); +pub const BF_ECB: Nid = Nid(ffi::NID_bf_ecb); +pub const BF_CFB64: Nid = Nid(ffi::NID_bf_cfb64); +pub const BF_OFB64: Nid = Nid(ffi::NID_bf_ofb64); +pub const ID_PKIX: Nid = Nid(ffi::NID_id_pkix); +pub const ID_PKIX_MOD: Nid = Nid(ffi::NID_id_pkix_mod); +pub const ID_PE: Nid = Nid(ffi::NID_id_pe); +pub const ID_QT: Nid = Nid(ffi::NID_id_qt); +pub const ID_KP: Nid = Nid(ffi::NID_id_kp); +pub const ID_IT: Nid = Nid(ffi::NID_id_it); +pub const ID_PKIP: Nid = Nid(ffi::NID_id_pkip); +pub const ID_ALG: Nid = Nid(ffi::NID_id_alg); +pub const ID_CMC: Nid = Nid(ffi::NID_id_cmc); +pub const ID_ON: Nid = Nid(ffi::NID_id_on); +pub const ID_PDA: Nid = Nid(ffi::NID_id_pda); +pub const ID_ACA: Nid = Nid(ffi::NID_id_aca); +pub const ID_QCS: Nid = Nid(ffi::NID_id_qcs); +pub const ID_CCT: Nid = Nid(ffi::NID_id_cct); +pub const ID_PPL: Nid = Nid(ffi::NID_id_ppl); +pub const ID_AD: Nid = Nid(ffi::NID_id_ad); +pub const ID_PKIX1_EXPLICIT_88: Nid = Nid(ffi::NID_id_pkix1_explicit_88); +pub const ID_PKIX1_IMPLICIT_88: Nid = Nid(ffi::NID_id_pkix1_implicit_88); +pub const ID_PKIX1_EXPLICIT_93: Nid = Nid(ffi::NID_id_pkix1_explicit_93); +pub const ID_PKIX1_IMPLICIT_93: Nid = Nid(ffi::NID_id_pkix1_implicit_93); +pub const ID_MOD_CRMF: Nid = Nid(ffi::NID_id_mod_crmf); +pub const ID_MOD_CMC: Nid = Nid(ffi::NID_id_mod_cmc); +pub const ID_MOD_KEA_PROFILE_88: Nid = Nid(ffi::NID_id_mod_kea_profile_88); +pub const ID_MOD_KEA_PROFILE_93: Nid = Nid(ffi::NID_id_mod_kea_profile_93); +pub const ID_MOD_CMP: Nid = Nid(ffi::NID_id_mod_cmp); +pub const ID_MOD_QUALIFIED_CERT_88: Nid = Nid(ffi::NID_id_mod_qualified_cert_88); +pub const ID_MOD_QUALIFIED_CERT_93: Nid = Nid(ffi::NID_id_mod_qualified_cert_93); +pub const ID_MOD_ATTRIBUTE_CERT: Nid = Nid(ffi::NID_id_mod_attribute_cert); +pub const ID_MOD_TIMESTAMP_PROTOCOL: Nid = Nid(ffi::NID_id_mod_timestamp_protocol); +pub const ID_MOD_OCSP: Nid = Nid(ffi::NID_id_mod_ocsp); +pub const ID_MOD_DVCS: Nid = Nid(ffi::NID_id_mod_dvcs); +pub const ID_MOD_CMP2000: Nid = Nid(ffi::NID_id_mod_cmp2000); +pub const INFO_ACCESS: Nid = Nid(ffi::NID_info_access); +pub const BIOMETRICINFO: Nid = Nid(ffi::NID_biometricInfo); +pub const QCSTATEMENTS: Nid = Nid(ffi::NID_qcStatements); +pub const AC_AUDITENTITY: Nid = Nid(ffi::NID_ac_auditEntity); +pub const AC_TARGETING: Nid = Nid(ffi::NID_ac_targeting); +pub const AACONTROLS: Nid = Nid(ffi::NID_aaControls); +pub const SBGP_IPADDRBLOCK: Nid = Nid(ffi::NID_sbgp_ipAddrBlock); +pub const SBGP_AUTONOMOUSSYSNUM: Nid = Nid(ffi::NID_sbgp_autonomousSysNum); +pub const SBGP_ROUTERIDENTIFIER: Nid = Nid(ffi::NID_sbgp_routerIdentifier); +pub const AC_PROXYING: Nid = Nid(ffi::NID_ac_proxying); +pub const SINFO_ACCESS: Nid = Nid(ffi::NID_sinfo_access); +pub const PROXYCERTINFO: Nid = Nid(ffi::NID_proxyCertInfo); +pub const ID_QT_CPS: Nid = Nid(ffi::NID_id_qt_cps); +pub const ID_QT_UNOTICE: Nid = Nid(ffi::NID_id_qt_unotice); +pub const TEXTNOTICE: Nid = Nid(ffi::NID_textNotice); +pub const SERVER_AUTH: Nid = Nid(ffi::NID_server_auth); +pub const CLIENT_AUTH: Nid = Nid(ffi::NID_client_auth); +pub const CODE_SIGN: Nid = Nid(ffi::NID_code_sign); +pub const EMAIL_PROTECT: Nid = Nid(ffi::NID_email_protect); +pub const IPSECENDSYSTEM: Nid = Nid(ffi::NID_ipsecEndSystem); +pub const IPSECTUNNEL: Nid = Nid(ffi::NID_ipsecTunnel); +pub const IPSECUSER: Nid = Nid(ffi::NID_ipsecUser); +pub const TIME_STAMP: Nid = Nid(ffi::NID_time_stamp); +pub const OCSP_SIGN: Nid = Nid(ffi::NID_OCSP_sign); +pub const DVCS: Nid = Nid(ffi::NID_dvcs); +pub const ID_IT_CAPROTENCCERT: Nid = Nid(ffi::NID_id_it_caProtEncCert); +pub const ID_IT_SIGNKEYPAIRTYPES: Nid = Nid(ffi::NID_id_it_signKeyPairTypes); +pub const ID_IT_ENCKEYPAIRTYPES: Nid = Nid(ffi::NID_id_it_encKeyPairTypes); +pub const ID_IT_PREFERREDSYMMALG: Nid = Nid(ffi::NID_id_it_preferredSymmAlg); +pub const ID_IT_CAKEYUPDATEINFO: Nid = Nid(ffi::NID_id_it_caKeyUpdateInfo); +pub const ID_IT_CURRENTCRL: Nid = Nid(ffi::NID_id_it_currentCRL); +pub const ID_IT_UNSUPPORTEDOIDS: Nid = Nid(ffi::NID_id_it_unsupportedOIDs); +pub const ID_IT_SUBSCRIPTIONREQUEST: Nid = Nid(ffi::NID_id_it_subscriptionRequest); +pub const ID_IT_SUBSCRIPTIONRESPONSE: Nid = Nid(ffi::NID_id_it_subscriptionResponse); +pub const ID_IT_KEYPAIRPARAMREQ: Nid = Nid(ffi::NID_id_it_keyPairParamReq); +pub const ID_IT_KEYPAIRPARAMREP: Nid = Nid(ffi::NID_id_it_keyPairParamRep); +pub const ID_IT_REVPASSPHRASE: Nid = Nid(ffi::NID_id_it_revPassphrase); +pub const ID_IT_IMPLICITCONFIRM: Nid = Nid(ffi::NID_id_it_implicitConfirm); +pub const ID_IT_CONFIRMWAITTIME: Nid = Nid(ffi::NID_id_it_confirmWaitTime); +pub const ID_IT_ORIGPKIMESSAGE: Nid = Nid(ffi::NID_id_it_origPKIMessage); +pub const ID_IT_SUPPLANGTAGS: Nid = Nid(ffi::NID_id_it_suppLangTags); +pub const ID_REGCTRL: Nid = Nid(ffi::NID_id_regCtrl); +pub const ID_REGINFO: Nid = Nid(ffi::NID_id_regInfo); +pub const ID_REGCTRL_REGTOKEN: Nid = Nid(ffi::NID_id_regCtrl_regToken); +pub const ID_REGCTRL_AUTHENTICATOR: Nid = Nid(ffi::NID_id_regCtrl_authenticator); +pub const ID_REGCTRL_PKIPUBLICATIONINFO: Nid = Nid(ffi::NID_id_regCtrl_pkiPublicationInfo); +pub const ID_REGCTRL_PKIARCHIVEOPTIONS: Nid = Nid(ffi::NID_id_regCtrl_pkiArchiveOptions); +pub const ID_REGCTRL_OLDCERTID: Nid = Nid(ffi::NID_id_regCtrl_oldCertID); +pub const ID_REGCTRL_PROTOCOLENCRKEY: Nid = Nid(ffi::NID_id_regCtrl_protocolEncrKey); +pub const ID_REGINFO_UTF8PAIRS: Nid = Nid(ffi::NID_id_regInfo_utf8Pairs); +pub const ID_REGINFO_CERTREQ: Nid = Nid(ffi::NID_id_regInfo_certReq); +pub const ID_ALG_DES40: Nid = Nid(ffi::NID_id_alg_des40); +pub const ID_ALG_NOSIGNATURE: Nid = Nid(ffi::NID_id_alg_noSignature); +pub const ID_ALG_DH_SIG_HMAC_SHA1: Nid = Nid(ffi::NID_id_alg_dh_sig_hmac_sha1); +pub const ID_ALG_DH_POP: Nid = Nid(ffi::NID_id_alg_dh_pop); +pub const ID_CMC_STATUSINFO: Nid = Nid(ffi::NID_id_cmc_statusInfo); +pub const ID_CMC_IDENTIFICATION: Nid = Nid(ffi::NID_id_cmc_identification); +pub const ID_CMC_IDENTITYPROOF: Nid = Nid(ffi::NID_id_cmc_identityProof); +pub const ID_CMC_DATARETURN: Nid = Nid(ffi::NID_id_cmc_dataReturn); +pub const ID_CMC_TRANSACTIONID: Nid = Nid(ffi::NID_id_cmc_transactionId); +pub const ID_CMC_SENDERNONCE: Nid = Nid(ffi::NID_id_cmc_senderNonce); +pub const ID_CMC_RECIPIENTNONCE: Nid = Nid(ffi::NID_id_cmc_recipientNonce); +pub const ID_CMC_ADDEXTENSIONS: Nid = Nid(ffi::NID_id_cmc_addExtensions); +pub const ID_CMC_ENCRYPTEDPOP: Nid = Nid(ffi::NID_id_cmc_encryptedPOP); +pub const ID_CMC_DECRYPTEDPOP: Nid = Nid(ffi::NID_id_cmc_decryptedPOP); +pub const ID_CMC_LRAPOPWITNESS: Nid = Nid(ffi::NID_id_cmc_lraPOPWitness); +pub const ID_CMC_GETCERT: Nid = Nid(ffi::NID_id_cmc_getCert); +pub const ID_CMC_GETCRL: Nid = Nid(ffi::NID_id_cmc_getCRL); +pub const ID_CMC_REVOKEREQUEST: Nid = Nid(ffi::NID_id_cmc_revokeRequest); +pub const ID_CMC_REGINFO: Nid = Nid(ffi::NID_id_cmc_regInfo); +pub const ID_CMC_RESPONSEINFO: Nid = Nid(ffi::NID_id_cmc_responseInfo); +pub const ID_CMC_QUERYPENDING: Nid = Nid(ffi::NID_id_cmc_queryPending); +pub const ID_CMC_POPLINKRANDOM: Nid = Nid(ffi::NID_id_cmc_popLinkRandom); +pub const ID_CMC_POPLINKWITNESS: Nid = Nid(ffi::NID_id_cmc_popLinkWitness); +pub const ID_CMC_CONFIRMCERTACCEPTANCE: Nid = Nid(ffi::NID_id_cmc_confirmCertAcceptance); +pub const ID_ON_PERSONALDATA: Nid = Nid(ffi::NID_id_on_personalData); +pub const ID_ON_PERMANENTIDENTIFIER: Nid = Nid(ffi::NID_id_on_permanentIdentifier); +pub const ID_PDA_DATEOFBIRTH: Nid = Nid(ffi::NID_id_pda_dateOfBirth); +pub const ID_PDA_PLACEOFBIRTH: Nid = Nid(ffi::NID_id_pda_placeOfBirth); +pub const ID_PDA_GENDER: Nid = Nid(ffi::NID_id_pda_gender); +pub const ID_PDA_COUNTRYOFCITIZENSHIP: Nid = Nid(ffi::NID_id_pda_countryOfCitizenship); +pub const ID_PDA_COUNTRYOFRESIDENCE: Nid = Nid(ffi::NID_id_pda_countryOfResidence); +pub const ID_ACA_AUTHENTICATIONINFO: Nid = Nid(ffi::NID_id_aca_authenticationInfo); +pub const ID_ACA_ACCESSIDENTITY: Nid = Nid(ffi::NID_id_aca_accessIdentity); +pub const ID_ACA_CHARGINGIDENTITY: Nid = Nid(ffi::NID_id_aca_chargingIdentity); +pub const ID_ACA_GROUP: Nid = Nid(ffi::NID_id_aca_group); +pub const ID_ACA_ROLE: Nid = Nid(ffi::NID_id_aca_role); +pub const ID_ACA_ENCATTRS: Nid = Nid(ffi::NID_id_aca_encAttrs); +pub const ID_QCS_PKIXQCSYNTAX_V1: Nid = Nid(ffi::NID_id_qcs_pkixQCSyntax_v1); +pub const ID_CCT_CRS: Nid = Nid(ffi::NID_id_cct_crs); +pub const ID_CCT_PKIDATA: Nid = Nid(ffi::NID_id_cct_PKIData); +pub const ID_CCT_PKIRESPONSE: Nid = Nid(ffi::NID_id_cct_PKIResponse); +pub const ID_PPL_ANYLANGUAGE: Nid = Nid(ffi::NID_id_ppl_anyLanguage); +pub const ID_PPL_INHERITALL: Nid = Nid(ffi::NID_id_ppl_inheritAll); +pub const INDEPENDENT: Nid = Nid(ffi::NID_Independent); +pub const AD_OCSP: Nid = Nid(ffi::NID_ad_OCSP); +pub const AD_CA_ISSUERS: Nid = Nid(ffi::NID_ad_ca_issuers); +pub const AD_TIMESTAMPING: Nid = Nid(ffi::NID_ad_timeStamping); +pub const AD_DVCS: Nid = Nid(ffi::NID_ad_dvcs); +pub const CAREPOSITORY: Nid = Nid(ffi::NID_caRepository); +pub const ID_PKIX_OCSP_BASIC: Nid = Nid(ffi::NID_id_pkix_OCSP_basic); +pub const ID_PKIX_OCSP_NONCE: Nid = Nid(ffi::NID_id_pkix_OCSP_Nonce); +pub const ID_PKIX_OCSP_CRLID: Nid = Nid(ffi::NID_id_pkix_OCSP_CrlID); +pub const ID_PKIX_OCSP_ACCEPTABLERESPONSES: Nid = Nid(ffi::NID_id_pkix_OCSP_acceptableResponses); +pub const ID_PKIX_OCSP_NOCHECK: Nid = Nid(ffi::NID_id_pkix_OCSP_noCheck); +pub const ID_PKIX_OCSP_ARCHIVECUTOFF: Nid = Nid(ffi::NID_id_pkix_OCSP_archiveCutoff); +pub const ID_PKIX_OCSP_SERVICELOCATOR: Nid = Nid(ffi::NID_id_pkix_OCSP_serviceLocator); +pub const ID_PKIX_OCSP_EXTENDEDSTATUS: Nid = Nid(ffi::NID_id_pkix_OCSP_extendedStatus); +pub const ID_PKIX_OCSP_VALID: Nid = Nid(ffi::NID_id_pkix_OCSP_valid); +pub const ID_PKIX_OCSP_PATH: Nid = Nid(ffi::NID_id_pkix_OCSP_path); +pub const ID_PKIX_OCSP_TRUSTROOT: Nid = Nid(ffi::NID_id_pkix_OCSP_trustRoot); +pub const ALGORITHM: Nid = Nid(ffi::NID_algorithm); +pub const MD5WITHRSA: Nid = Nid(ffi::NID_md5WithRSA); +pub const DES_ECB: Nid = Nid(ffi::NID_des_ecb); +pub const DES_CBC: Nid = Nid(ffi::NID_des_cbc); +pub const DES_OFB64: Nid = Nid(ffi::NID_des_ofb64); +pub const DES_CFB64: Nid = Nid(ffi::NID_des_cfb64); +pub const RSASIGNATURE: Nid = Nid(ffi::NID_rsaSignature); +pub const DSA_2: Nid = Nid(ffi::NID_dsa_2); +pub const DSAWITHSHA: Nid = Nid(ffi::NID_dsaWithSHA); +pub const SHAWITHRSAENCRYPTION: Nid = Nid(ffi::NID_shaWithRSAEncryption); +pub const DES_EDE_ECB: Nid = Nid(ffi::NID_des_ede_ecb); +pub const DES_EDE3_ECB: Nid = Nid(ffi::NID_des_ede3_ecb); +pub const DES_EDE_CBC: Nid = Nid(ffi::NID_des_ede_cbc); +pub const DES_EDE_CFB64: Nid = Nid(ffi::NID_des_ede_cfb64); +pub const DES_EDE3_CFB64: Nid = Nid(ffi::NID_des_ede3_cfb64); +pub const DES_EDE_OFB64: Nid = Nid(ffi::NID_des_ede_ofb64); +pub const DES_EDE3_OFB64: Nid = Nid(ffi::NID_des_ede3_ofb64); +pub const DESX_CBC: Nid = Nid(ffi::NID_desx_cbc); +pub const SHA: Nid = Nid(ffi::NID_sha); +pub const SHA1: Nid = Nid(ffi::NID_sha1); +pub const DSAWITHSHA1_2: Nid = Nid(ffi::NID_dsaWithSHA1_2); +pub const SHA1WITHRSA: Nid = Nid(ffi::NID_sha1WithRSA); +pub const RIPEMD160: Nid = Nid(ffi::NID_ripemd160); +pub const RIPEMD160WITHRSA: Nid = Nid(ffi::NID_ripemd160WithRSA); +pub const SXNET: Nid = Nid(ffi::NID_sxnet); +pub const X500: Nid = Nid(ffi::NID_X500); +pub const X509: Nid = Nid(ffi::NID_X509); +pub const COMMONNAME: Nid = Nid(ffi::NID_commonName); +pub const SURNAME: Nid = Nid(ffi::NID_surname); +pub const SERIALNUMBER: Nid = Nid(ffi::NID_serialNumber); +pub const COUNTRYNAME: Nid = Nid(ffi::NID_countryName); +pub const LOCALITYNAME: Nid = Nid(ffi::NID_localityName); +pub const STATEORPROVINCENAME: Nid = Nid(ffi::NID_stateOrProvinceName); +pub const STREETADDRESS: Nid = Nid(ffi::NID_streetAddress); +pub const ORGANIZATIONNAME: Nid = Nid(ffi::NID_organizationName); +pub const ORGANIZATIONALUNITNAME: Nid = Nid(ffi::NID_organizationalUnitName); +pub const TITLE: Nid = Nid(ffi::NID_title); +pub const DESCRIPTION: Nid = Nid(ffi::NID_description); +pub const SEARCHGUIDE: Nid = Nid(ffi::NID_searchGuide); +pub const BUSINESSCATEGORY: Nid = Nid(ffi::NID_businessCategory); +pub const POSTALADDRESS: Nid = Nid(ffi::NID_postalAddress); +pub const POSTALCODE: Nid = Nid(ffi::NID_postalCode); +pub const POSTOFFICEBOX: Nid = Nid(ffi::NID_postOfficeBox); +pub const PHYSICALDELIVERYOFFICENAME: Nid = Nid(ffi::NID_physicalDeliveryOfficeName); +pub const TELEPHONENUMBER: Nid = Nid(ffi::NID_telephoneNumber); +pub const TELEXNUMBER: Nid = Nid(ffi::NID_telexNumber); +pub const TELETEXTERMINALIDENTIFIER: Nid = Nid(ffi::NID_teletexTerminalIdentifier); +pub const FACSIMILETELEPHONENUMBER: Nid = Nid(ffi::NID_facsimileTelephoneNumber); +pub const X121ADDRESS: Nid = Nid(ffi::NID_x121Address); +pub const INTERNATIONALISDNNUMBER: Nid = Nid(ffi::NID_internationaliSDNNumber); +pub const REGISTEREDADDRESS: Nid = Nid(ffi::NID_registeredAddress); +pub const DESTINATIONINDICATOR: Nid = Nid(ffi::NID_destinationIndicator); +pub const PREFERREDDELIVERYMETHOD: Nid = Nid(ffi::NID_preferredDeliveryMethod); +pub const PRESENTATIONADDRESS: Nid = Nid(ffi::NID_presentationAddress); +pub const SUPPORTEDAPPLICATIONCONTEXT: Nid = Nid(ffi::NID_supportedApplicationContext); +pub const MEMBER: Nid = Nid(ffi::NID_member); +pub const OWNER: Nid = Nid(ffi::NID_owner); +pub const ROLEOCCUPANT: Nid = Nid(ffi::NID_roleOccupant); +pub const SEEALSO: Nid = Nid(ffi::NID_seeAlso); +pub const USERPASSWORD: Nid = Nid(ffi::NID_userPassword); +pub const USERCERTIFICATE: Nid = Nid(ffi::NID_userCertificate); +pub const CACERTIFICATE: Nid = Nid(ffi::NID_cACertificate); +pub const AUTHORITYREVOCATIONLIST: Nid = Nid(ffi::NID_authorityRevocationList); +pub const CERTIFICATEREVOCATIONLIST: Nid = Nid(ffi::NID_certificateRevocationList); +pub const CROSSCERTIFICATEPAIR: Nid = Nid(ffi::NID_crossCertificatePair); +pub const NAME: Nid = Nid(ffi::NID_name); +pub const GIVENNAME: Nid = Nid(ffi::NID_givenName); +pub const INITIALS: Nid = Nid(ffi::NID_initials); +pub const GENERATIONQUALIFIER: Nid = Nid(ffi::NID_generationQualifier); +pub const X500UNIQUEIDENTIFIER: Nid = Nid(ffi::NID_x500UniqueIdentifier); +pub const DNQUALIFIER: Nid = Nid(ffi::NID_dnQualifier); +pub const ENHANCEDSEARCHGUIDE: Nid = Nid(ffi::NID_enhancedSearchGuide); +pub const PROTOCOLINFORMATION: Nid = Nid(ffi::NID_protocolInformation); +pub const DISTINGUISHEDNAME: Nid = Nid(ffi::NID_distinguishedName); +pub const UNIQUEMEMBER: Nid = Nid(ffi::NID_uniqueMember); +pub const HOUSEIDENTIFIER: Nid = Nid(ffi::NID_houseIdentifier); +pub const SUPPORTEDALGORITHMS: Nid = Nid(ffi::NID_supportedAlgorithms); +pub const DELTAREVOCATIONLIST: Nid = Nid(ffi::NID_deltaRevocationList); +pub const DMDNAME: Nid = Nid(ffi::NID_dmdName); +pub const PSEUDONYM: Nid = Nid(ffi::NID_pseudonym); +pub const ROLE: Nid = Nid(ffi::NID_role); +pub const X500ALGORITHMS: Nid = Nid(ffi::NID_X500algorithms); +pub const RSA: Nid = Nid(ffi::NID_rsa); +pub const MDC2WITHRSA: Nid = Nid(ffi::NID_mdc2WithRSA); +pub const MDC2: Nid = Nid(ffi::NID_mdc2); +pub const ID_CE: Nid = Nid(ffi::NID_id_ce); +pub const SUBJECT_DIRECTORY_ATTRIBUTES: Nid = Nid(ffi::NID_subject_directory_attributes); +pub const SUBJECT_KEY_IDENTIFIER: Nid = Nid(ffi::NID_subject_key_identifier); +pub const KEY_USAGE: Nid = Nid(ffi::NID_key_usage); +pub const PRIVATE_KEY_USAGE_PERIOD: Nid = Nid(ffi::NID_private_key_usage_period); +pub const SUBJECT_ALT_NAME: Nid = Nid(ffi::NID_subject_alt_name); +pub const ISSUER_ALT_NAME: Nid = Nid(ffi::NID_issuer_alt_name); +pub const BASIC_CONSTRAINTS: Nid = Nid(ffi::NID_basic_constraints); +pub const CRL_NUMBER: Nid = Nid(ffi::NID_crl_number); +pub const CRL_REASON: Nid = Nid(ffi::NID_crl_reason); +pub const INVALIDITY_DATE: Nid = Nid(ffi::NID_invalidity_date); +pub const DELTA_CRL: Nid = Nid(ffi::NID_delta_crl); +pub const ISSUING_DISTRIBUTION_POINT: Nid = Nid(ffi::NID_issuing_distribution_point); +pub const CERTIFICATE_ISSUER: Nid = Nid(ffi::NID_certificate_issuer); +pub const NAME_CONSTRAINTS: Nid = Nid(ffi::NID_name_constraints); +pub const CRL_DISTRIBUTION_POINTS: Nid = Nid(ffi::NID_crl_distribution_points); +pub const CERTIFICATE_POLICIES: Nid = Nid(ffi::NID_certificate_policies); +pub const ANY_POLICY: Nid = Nid(ffi::NID_any_policy); +pub const POLICY_MAPPINGS: Nid = Nid(ffi::NID_policy_mappings); +pub const AUTHORITY_KEY_IDENTIFIER: Nid = Nid(ffi::NID_authority_key_identifier); +pub const POLICY_CONSTRAINTS: Nid = Nid(ffi::NID_policy_constraints); +pub const EXT_KEY_USAGE: Nid = Nid(ffi::NID_ext_key_usage); +pub const FRESHEST_CRL: Nid = Nid(ffi::NID_freshest_crl); +pub const INHIBIT_ANY_POLICY: Nid = Nid(ffi::NID_inhibit_any_policy); +pub const TARGET_INFORMATION: Nid = Nid(ffi::NID_target_information); +pub const NO_REV_AVAIL: Nid = Nid(ffi::NID_no_rev_avail); +pub const ANYEXTENDEDKEYUSAGE: Nid = Nid(ffi::NID_anyExtendedKeyUsage); +pub const NETSCAPE: Nid = Nid(ffi::NID_netscape); +pub const NETSCAPE_CERT_EXTENSION: Nid = Nid(ffi::NID_netscape_cert_extension); +pub const NETSCAPE_DATA_TYPE: Nid = Nid(ffi::NID_netscape_data_type); +pub const NETSCAPE_CERT_TYPE: Nid = Nid(ffi::NID_netscape_cert_type); +pub const NETSCAPE_BASE_URL: Nid = Nid(ffi::NID_netscape_base_url); +pub const NETSCAPE_REVOCATION_URL: Nid = Nid(ffi::NID_netscape_revocation_url); +pub const NETSCAPE_CA_REVOCATION_URL: Nid = Nid(ffi::NID_netscape_ca_revocation_url); +pub const NETSCAPE_RENEWAL_URL: Nid = Nid(ffi::NID_netscape_renewal_url); +pub const NETSCAPE_CA_POLICY_URL: Nid = Nid(ffi::NID_netscape_ca_policy_url); +pub const NETSCAPE_SSL_SERVER_NAME: Nid = Nid(ffi::NID_netscape_ssl_server_name); +pub const NETSCAPE_COMMENT: Nid = Nid(ffi::NID_netscape_comment); +pub const NETSCAPE_CERT_SEQUENCE: Nid = Nid(ffi::NID_netscape_cert_sequence); +pub const NS_SGC: Nid = Nid(ffi::NID_ns_sgc); +pub const ORG: Nid = Nid(ffi::NID_org); +pub const DOD: Nid = Nid(ffi::NID_dod); +pub const IANA: Nid = Nid(ffi::NID_iana); +pub const DIRECTORY: Nid = Nid(ffi::NID_Directory); +pub const MANAGEMENT: Nid = Nid(ffi::NID_Management); +pub const EXPERIMENTAL: Nid = Nid(ffi::NID_Experimental); +pub const PRIVATE: Nid = Nid(ffi::NID_Private); +pub const SECURITY: Nid = Nid(ffi::NID_Security); +pub const SNMPV2: Nid = Nid(ffi::NID_SNMPv2); +pub const MAIL: Nid = Nid(ffi::NID_Mail); +pub const ENTERPRISES: Nid = Nid(ffi::NID_Enterprises); +pub const DCOBJECT: Nid = Nid(ffi::NID_dcObject); +pub const MIME_MHS: Nid = Nid(ffi::NID_mime_mhs); +pub const MIME_MHS_HEADINGS: Nid = Nid(ffi::NID_mime_mhs_headings); +pub const MIME_MHS_BODIES: Nid = Nid(ffi::NID_mime_mhs_bodies); +pub const ID_HEX_PARTIAL_MESSAGE: Nid = Nid(ffi::NID_id_hex_partial_message); +pub const ID_HEX_MULTIPART_MESSAGE: Nid = Nid(ffi::NID_id_hex_multipart_message); +pub const RLE_COMPRESSION: Nid = Nid(ffi::NID_rle_compression); +pub const ZLIB_COMPRESSION: Nid = Nid(ffi::NID_zlib_compression); +pub const AES_128_ECB: Nid = Nid(ffi::NID_aes_128_ecb); +pub const AES_128_CBC: Nid = Nid(ffi::NID_aes_128_cbc); +pub const AES_128_OFB128: Nid = Nid(ffi::NID_aes_128_ofb128); +pub const AES_128_CFB128: Nid = Nid(ffi::NID_aes_128_cfb128); +pub const ID_AES128_WRAP: Nid = Nid(ffi::NID_id_aes128_wrap); +pub const AES_128_GCM: Nid = Nid(ffi::NID_aes_128_gcm); +pub const AES_128_CCM: Nid = Nid(ffi::NID_aes_128_ccm); +pub const ID_AES128_WRAP_PAD: Nid = Nid(ffi::NID_id_aes128_wrap_pad); +pub const AES_192_ECB: Nid = Nid(ffi::NID_aes_192_ecb); +pub const AES_192_CBC: Nid = Nid(ffi::NID_aes_192_cbc); +pub const AES_192_OFB128: Nid = Nid(ffi::NID_aes_192_ofb128); +pub const AES_192_CFB128: Nid = Nid(ffi::NID_aes_192_cfb128); +pub const ID_AES192_WRAP: Nid = Nid(ffi::NID_id_aes192_wrap); +pub const AES_192_GCM: Nid = Nid(ffi::NID_aes_192_gcm); +pub const AES_192_CCM: Nid = Nid(ffi::NID_aes_192_ccm); +pub const ID_AES192_WRAP_PAD: Nid = Nid(ffi::NID_id_aes192_wrap_pad); +pub const AES_256_ECB: Nid = Nid(ffi::NID_aes_256_ecb); +pub const AES_256_CBC: Nid = Nid(ffi::NID_aes_256_cbc); +pub const AES_256_OFB128: Nid = Nid(ffi::NID_aes_256_ofb128); +pub const AES_256_CFB128: Nid = Nid(ffi::NID_aes_256_cfb128); +pub const ID_AES256_WRAP: Nid = Nid(ffi::NID_id_aes256_wrap); +pub const AES_256_GCM: Nid = Nid(ffi::NID_aes_256_gcm); +pub const AES_256_CCM: Nid = Nid(ffi::NID_aes_256_ccm); +pub const ID_AES256_WRAP_PAD: Nid = Nid(ffi::NID_id_aes256_wrap_pad); +pub const AES_128_CFB1: Nid = Nid(ffi::NID_aes_128_cfb1); +pub const AES_192_CFB1: Nid = Nid(ffi::NID_aes_192_cfb1); +pub const AES_256_CFB1: Nid = Nid(ffi::NID_aes_256_cfb1); +pub const AES_128_CFB8: Nid = Nid(ffi::NID_aes_128_cfb8); +pub const AES_192_CFB8: Nid = Nid(ffi::NID_aes_192_cfb8); +pub const AES_256_CFB8: Nid = Nid(ffi::NID_aes_256_cfb8); +pub const AES_128_CTR: Nid = Nid(ffi::NID_aes_128_ctr); +pub const AES_192_CTR: Nid = Nid(ffi::NID_aes_192_ctr); +pub const AES_256_CTR: Nid = Nid(ffi::NID_aes_256_ctr); +pub const AES_128_XTS: Nid = Nid(ffi::NID_aes_128_xts); +pub const AES_256_XTS: Nid = Nid(ffi::NID_aes_256_xts); +pub const DES_CFB1: Nid = Nid(ffi::NID_des_cfb1); +pub const DES_CFB8: Nid = Nid(ffi::NID_des_cfb8); +pub const DES_EDE3_CFB1: Nid = Nid(ffi::NID_des_ede3_cfb1); +pub const DES_EDE3_CFB8: Nid = Nid(ffi::NID_des_ede3_cfb8); +pub const SHA256: Nid = Nid(ffi::NID_sha256); +pub const SHA384: Nid = Nid(ffi::NID_sha384); +pub const SHA512: Nid = Nid(ffi::NID_sha512); +pub const SHA224: Nid = Nid(ffi::NID_sha224); +pub const DSA_WITH_SHA224: Nid = Nid(ffi::NID_dsa_with_SHA224); +pub const DSA_WITH_SHA256: Nid = Nid(ffi::NID_dsa_with_SHA256); +pub const HOLD_INSTRUCTION_CODE: Nid = Nid(ffi::NID_hold_instruction_code); +pub const HOLD_INSTRUCTION_NONE: Nid = Nid(ffi::NID_hold_instruction_none); +pub const HOLD_INSTRUCTION_CALL_ISSUER: Nid = Nid(ffi::NID_hold_instruction_call_issuer); +pub const HOLD_INSTRUCTION_REJECT: Nid = Nid(ffi::NID_hold_instruction_reject); +pub const DATA: Nid = Nid(ffi::NID_data); +pub const PSS: Nid = Nid(ffi::NID_pss); +pub const UCL: Nid = Nid(ffi::NID_ucl); +pub const PILOT: Nid = Nid(ffi::NID_pilot); +pub const PILOTATTRIBUTETYPE: Nid = Nid(ffi::NID_pilotAttributeType); +pub const PILOTATTRIBUTESYNTAX: Nid = Nid(ffi::NID_pilotAttributeSyntax); +pub const PILOTOBJECTCLASS: Nid = Nid(ffi::NID_pilotObjectClass); +pub const PILOTGROUPS: Nid = Nid(ffi::NID_pilotGroups); +pub const IA5STRINGSYNTAX: Nid = Nid(ffi::NID_iA5StringSyntax); +pub const CASEIGNOREIA5STRINGSYNTAX: Nid = Nid(ffi::NID_caseIgnoreIA5StringSyntax); +pub const PILOTOBJECT: Nid = Nid(ffi::NID_pilotObject); +pub const PILOTPERSON: Nid = Nid(ffi::NID_pilotPerson); +pub const ACCOUNT: Nid = Nid(ffi::NID_account); +pub const DOCUMENT: Nid = Nid(ffi::NID_document); +pub const ROOM: Nid = Nid(ffi::NID_room); +pub const DOCUMENTSERIES: Nid = Nid(ffi::NID_documentSeries); +pub const DOMAIN: Nid = Nid(ffi::NID_Domain); +pub const RFC822LOCALPART: Nid = Nid(ffi::NID_rFC822localPart); +pub const DNSDOMAIN: Nid = Nid(ffi::NID_dNSDomain); +pub const DOMAINRELATEDOBJECT: Nid = Nid(ffi::NID_domainRelatedObject); +pub const FRIENDLYCOUNTRY: Nid = Nid(ffi::NID_friendlyCountry); +pub const SIMPLESECURITYOBJECT: Nid = Nid(ffi::NID_simpleSecurityObject); +pub const PILOTORGANIZATION: Nid = Nid(ffi::NID_pilotOrganization); +pub const PILOTDSA: Nid = Nid(ffi::NID_pilotDSA); +pub const QUALITYLABELLEDDATA: Nid = Nid(ffi::NID_qualityLabelledData); +pub const USERID: Nid = Nid(ffi::NID_userId); +pub const TEXTENCODEDORADDRESS: Nid = Nid(ffi::NID_textEncodedORAddress); +pub const RFC822MAILBOX: Nid = Nid(ffi::NID_rfc822Mailbox); +pub const INFO: Nid = Nid(ffi::NID_info); +pub const FAVOURITEDRINK: Nid = Nid(ffi::NID_favouriteDrink); +pub const ROOMNUMBER: Nid = Nid(ffi::NID_roomNumber); +pub const PHOTO: Nid = Nid(ffi::NID_photo); +pub const USERCLASS: Nid = Nid(ffi::NID_userClass); +pub const HOST: Nid = Nid(ffi::NID_host); +pub const MANAGER: Nid = Nid(ffi::NID_manager); +pub const DOCUMENTIDENTIFIER: Nid = Nid(ffi::NID_documentIdentifier); +pub const DOCUMENTTITLE: Nid = Nid(ffi::NID_documentTitle); +pub const DOCUMENTVERSION: Nid = Nid(ffi::NID_documentVersion); +pub const DOCUMENTAUTHOR: Nid = Nid(ffi::NID_documentAuthor); +pub const DOCUMENTLOCATION: Nid = Nid(ffi::NID_documentLocation); +pub const HOMETELEPHONENUMBER: Nid = Nid(ffi::NID_homeTelephoneNumber); +pub const SECRETARY: Nid = Nid(ffi::NID_secretary); +pub const OTHERMAILBOX: Nid = Nid(ffi::NID_otherMailbox); +pub const LASTMODIFIEDTIME: Nid = Nid(ffi::NID_lastModifiedTime); +pub const LASTMODIFIEDBY: Nid = Nid(ffi::NID_lastModifiedBy); +pub const DOMAINCOMPONENT: Nid = Nid(ffi::NID_domainComponent); +pub const ARECORD: Nid = Nid(ffi::NID_aRecord); +pub const PILOTATTRIBUTETYPE27: Nid = Nid(ffi::NID_pilotAttributeType27); +pub const MXRECORD: Nid = Nid(ffi::NID_mXRecord); +pub const NSRECORD: Nid = Nid(ffi::NID_nSRecord); +pub const SOARECORD: Nid = Nid(ffi::NID_sOARecord); +pub const CNAMERECORD: Nid = Nid(ffi::NID_cNAMERecord); +pub const ASSOCIATEDDOMAIN: Nid = Nid(ffi::NID_associatedDomain); +pub const ASSOCIATEDNAME: Nid = Nid(ffi::NID_associatedName); +pub const HOMEPOSTALADDRESS: Nid = Nid(ffi::NID_homePostalAddress); +pub const PERSONALTITLE: Nid = Nid(ffi::NID_personalTitle); +pub const MOBILETELEPHONENUMBER: Nid = Nid(ffi::NID_mobileTelephoneNumber); +pub const PAGERTELEPHONENUMBER: Nid = Nid(ffi::NID_pagerTelephoneNumber); +pub const FRIENDLYCOUNTRYNAME: Nid = Nid(ffi::NID_friendlyCountryName); +pub const ORGANIZATIONALSTATUS: Nid = Nid(ffi::NID_organizationalStatus); +pub const JANETMAILBOX: Nid = Nid(ffi::NID_janetMailbox); +pub const MAILPREFERENCEOPTION: Nid = Nid(ffi::NID_mailPreferenceOption); +pub const BUILDINGNAME: Nid = Nid(ffi::NID_buildingName); +pub const DSAQUALITY: Nid = Nid(ffi::NID_dSAQuality); +pub const SINGLELEVELQUALITY: Nid = Nid(ffi::NID_singleLevelQuality); +pub const SUBTREEMINIMUMQUALITY: Nid = Nid(ffi::NID_subtreeMinimumQuality); +pub const SUBTREEMAXIMUMQUALITY: Nid = Nid(ffi::NID_subtreeMaximumQuality); +pub const PERSONALSIGNATURE: Nid = Nid(ffi::NID_personalSignature); +pub const DITREDIRECT: Nid = Nid(ffi::NID_dITRedirect); +pub const AUDIO: Nid = Nid(ffi::NID_audio); +pub const DOCUMENTPUBLISHER: Nid = Nid(ffi::NID_documentPublisher); +pub const ID_SET: Nid = Nid(ffi::NID_id_set); +pub const SET_CTYPE: Nid = Nid(ffi::NID_set_ctype); +pub const SET_MSGEXT: Nid = Nid(ffi::NID_set_msgExt); +pub const SET_ATTR: Nid = Nid(ffi::NID_set_attr); +pub const SET_POLICY: Nid = Nid(ffi::NID_set_policy); +pub const SET_CERTEXT: Nid = Nid(ffi::NID_set_certExt); +pub const SET_BRAND: Nid = Nid(ffi::NID_set_brand); +pub const SETCT_PANDATA: Nid = Nid(ffi::NID_setct_PANData); +pub const SETCT_PANTOKEN: Nid = Nid(ffi::NID_setct_PANToken); +pub const SETCT_PANONLY: Nid = Nid(ffi::NID_setct_PANOnly); +pub const SETCT_OIDATA: Nid = Nid(ffi::NID_setct_OIData); +pub const SETCT_PI: Nid = Nid(ffi::NID_setct_PI); +pub const SETCT_PIDATA: Nid = Nid(ffi::NID_setct_PIData); +pub const SETCT_PIDATAUNSIGNED: Nid = Nid(ffi::NID_setct_PIDataUnsigned); +pub const SETCT_HODINPUT: Nid = Nid(ffi::NID_setct_HODInput); +pub const SETCT_AUTHRESBAGGAGE: Nid = Nid(ffi::NID_setct_AuthResBaggage); +pub const SETCT_AUTHREVREQBAGGAGE: Nid = Nid(ffi::NID_setct_AuthRevReqBaggage); +pub const SETCT_AUTHREVRESBAGGAGE: Nid = Nid(ffi::NID_setct_AuthRevResBaggage); +pub const SETCT_CAPTOKENSEQ: Nid = Nid(ffi::NID_setct_CapTokenSeq); +pub const SETCT_PINITRESDATA: Nid = Nid(ffi::NID_setct_PInitResData); +pub const SETCT_PI_TBS: Nid = Nid(ffi::NID_setct_PI_TBS); +pub const SETCT_PRESDATA: Nid = Nid(ffi::NID_setct_PResData); +pub const SETCT_AUTHREQTBS: Nid = Nid(ffi::NID_setct_AuthReqTBS); +pub const SETCT_AUTHRESTBS: Nid = Nid(ffi::NID_setct_AuthResTBS); +pub const SETCT_AUTHRESTBSX: Nid = Nid(ffi::NID_setct_AuthResTBSX); +pub const SETCT_AUTHTOKENTBS: Nid = Nid(ffi::NID_setct_AuthTokenTBS); +pub const SETCT_CAPTOKENDATA: Nid = Nid(ffi::NID_setct_CapTokenData); +pub const SETCT_CAPTOKENTBS: Nid = Nid(ffi::NID_setct_CapTokenTBS); +pub const SETCT_ACQCARDCODEMSG: Nid = Nid(ffi::NID_setct_AcqCardCodeMsg); +pub const SETCT_AUTHREVREQTBS: Nid = Nid(ffi::NID_setct_AuthRevReqTBS); +pub const SETCT_AUTHREVRESDATA: Nid = Nid(ffi::NID_setct_AuthRevResData); +pub const SETCT_AUTHREVRESTBS: Nid = Nid(ffi::NID_setct_AuthRevResTBS); +pub const SETCT_CAPREQTBS: Nid = Nid(ffi::NID_setct_CapReqTBS); +pub const SETCT_CAPREQTBSX: Nid = Nid(ffi::NID_setct_CapReqTBSX); +pub const SETCT_CAPRESDATA: Nid = Nid(ffi::NID_setct_CapResData); +pub const SETCT_CAPREVREQTBS: Nid = Nid(ffi::NID_setct_CapRevReqTBS); +pub const SETCT_CAPREVREQTBSX: Nid = Nid(ffi::NID_setct_CapRevReqTBSX); +pub const SETCT_CAPREVRESDATA: Nid = Nid(ffi::NID_setct_CapRevResData); +pub const SETCT_CREDREQTBS: Nid = Nid(ffi::NID_setct_CredReqTBS); +pub const SETCT_CREDREQTBSX: Nid = Nid(ffi::NID_setct_CredReqTBSX); +pub const SETCT_CREDRESDATA: Nid = Nid(ffi::NID_setct_CredResData); +pub const SETCT_CREDREVREQTBS: Nid = Nid(ffi::NID_setct_CredRevReqTBS); +pub const SETCT_CREDREVREQTBSX: Nid = Nid(ffi::NID_setct_CredRevReqTBSX); +pub const SETCT_CREDREVRESDATA: Nid = Nid(ffi::NID_setct_CredRevResData); +pub const SETCT_PCERTREQDATA: Nid = Nid(ffi::NID_setct_PCertReqData); +pub const SETCT_PCERTRESTBS: Nid = Nid(ffi::NID_setct_PCertResTBS); +pub const SETCT_BATCHADMINREQDATA: Nid = Nid(ffi::NID_setct_BatchAdminReqData); +pub const SETCT_BATCHADMINRESDATA: Nid = Nid(ffi::NID_setct_BatchAdminResData); +pub const SETCT_CARDCINITRESTBS: Nid = Nid(ffi::NID_setct_CardCInitResTBS); +pub const SETCT_MEAQCINITRESTBS: Nid = Nid(ffi::NID_setct_MeAqCInitResTBS); +pub const SETCT_REGFORMRESTBS: Nid = Nid(ffi::NID_setct_RegFormResTBS); +pub const SETCT_CERTREQDATA: Nid = Nid(ffi::NID_setct_CertReqData); +pub const SETCT_CERTREQTBS: Nid = Nid(ffi::NID_setct_CertReqTBS); +pub const SETCT_CERTRESDATA: Nid = Nid(ffi::NID_setct_CertResData); +pub const SETCT_CERTINQREQTBS: Nid = Nid(ffi::NID_setct_CertInqReqTBS); +pub const SETCT_ERRORTBS: Nid = Nid(ffi::NID_setct_ErrorTBS); +pub const SETCT_PIDUALSIGNEDTBE: Nid = Nid(ffi::NID_setct_PIDualSignedTBE); +pub const SETCT_PIUNSIGNEDTBE: Nid = Nid(ffi::NID_setct_PIUnsignedTBE); +pub const SETCT_AUTHREQTBE: Nid = Nid(ffi::NID_setct_AuthReqTBE); +pub const SETCT_AUTHRESTBE: Nid = Nid(ffi::NID_setct_AuthResTBE); +pub const SETCT_AUTHRESTBEX: Nid = Nid(ffi::NID_setct_AuthResTBEX); +pub const SETCT_AUTHTOKENTBE: Nid = Nid(ffi::NID_setct_AuthTokenTBE); +pub const SETCT_CAPTOKENTBE: Nid = Nid(ffi::NID_setct_CapTokenTBE); +pub const SETCT_CAPTOKENTBEX: Nid = Nid(ffi::NID_setct_CapTokenTBEX); +pub const SETCT_ACQCARDCODEMSGTBE: Nid = Nid(ffi::NID_setct_AcqCardCodeMsgTBE); +pub const SETCT_AUTHREVREQTBE: Nid = Nid(ffi::NID_setct_AuthRevReqTBE); +pub const SETCT_AUTHREVRESTBE: Nid = Nid(ffi::NID_setct_AuthRevResTBE); +pub const SETCT_AUTHREVRESTBEB: Nid = Nid(ffi::NID_setct_AuthRevResTBEB); +pub const SETCT_CAPREQTBE: Nid = Nid(ffi::NID_setct_CapReqTBE); +pub const SETCT_CAPREQTBEX: Nid = Nid(ffi::NID_setct_CapReqTBEX); +pub const SETCT_CAPRESTBE: Nid = Nid(ffi::NID_setct_CapResTBE); +pub const SETCT_CAPREVREQTBE: Nid = Nid(ffi::NID_setct_CapRevReqTBE); +pub const SETCT_CAPREVREQTBEX: Nid = Nid(ffi::NID_setct_CapRevReqTBEX); +pub const SETCT_CAPREVRESTBE: Nid = Nid(ffi::NID_setct_CapRevResTBE); +pub const SETCT_CREDREQTBE: Nid = Nid(ffi::NID_setct_CredReqTBE); +pub const SETCT_CREDREQTBEX: Nid = Nid(ffi::NID_setct_CredReqTBEX); +pub const SETCT_CREDRESTBE: Nid = Nid(ffi::NID_setct_CredResTBE); +pub const SETCT_CREDREVREQTBE: Nid = Nid(ffi::NID_setct_CredRevReqTBE); +pub const SETCT_CREDREVREQTBEX: Nid = Nid(ffi::NID_setct_CredRevReqTBEX); +pub const SETCT_CREDREVRESTBE: Nid = Nid(ffi::NID_setct_CredRevResTBE); +pub const SETCT_BATCHADMINREQTBE: Nid = Nid(ffi::NID_setct_BatchAdminReqTBE); +pub const SETCT_BATCHADMINRESTBE: Nid = Nid(ffi::NID_setct_BatchAdminResTBE); +pub const SETCT_REGFORMREQTBE: Nid = Nid(ffi::NID_setct_RegFormReqTBE); +pub const SETCT_CERTREQTBE: Nid = Nid(ffi::NID_setct_CertReqTBE); +pub const SETCT_CERTREQTBEX: Nid = Nid(ffi::NID_setct_CertReqTBEX); +pub const SETCT_CERTRESTBE: Nid = Nid(ffi::NID_setct_CertResTBE); +pub const SETCT_CRLNOTIFICATIONTBS: Nid = Nid(ffi::NID_setct_CRLNotificationTBS); +pub const SETCT_CRLNOTIFICATIONRESTBS: Nid = Nid(ffi::NID_setct_CRLNotificationResTBS); +pub const SETCT_BCIDISTRIBUTIONTBS: Nid = Nid(ffi::NID_setct_BCIDistributionTBS); +pub const SETEXT_GENCRYPT: Nid = Nid(ffi::NID_setext_genCrypt); +pub const SETEXT_MIAUTH: Nid = Nid(ffi::NID_setext_miAuth); +pub const SETEXT_PINSECURE: Nid = Nid(ffi::NID_setext_pinSecure); +pub const SETEXT_PINANY: Nid = Nid(ffi::NID_setext_pinAny); +pub const SETEXT_TRACK2: Nid = Nid(ffi::NID_setext_track2); +pub const SETEXT_CV: Nid = Nid(ffi::NID_setext_cv); +pub const SET_POLICY_ROOT: Nid = Nid(ffi::NID_set_policy_root); +pub const SETCEXT_HASHEDROOT: Nid = Nid(ffi::NID_setCext_hashedRoot); +pub const SETCEXT_CERTTYPE: Nid = Nid(ffi::NID_setCext_certType); +pub const SETCEXT_MERCHDATA: Nid = Nid(ffi::NID_setCext_merchData); +pub const SETCEXT_CCERTREQUIRED: Nid = Nid(ffi::NID_setCext_cCertRequired); +pub const SETCEXT_TUNNELING: Nid = Nid(ffi::NID_setCext_tunneling); +pub const SETCEXT_SETEXT: Nid = Nid(ffi::NID_setCext_setExt); +pub const SETCEXT_SETQUALF: Nid = Nid(ffi::NID_setCext_setQualf); +pub const SETCEXT_PGWYCAPABILITIES: Nid = Nid(ffi::NID_setCext_PGWYcapabilities); +pub const SETCEXT_TOKENIDENTIFIER: Nid = Nid(ffi::NID_setCext_TokenIdentifier); +pub const SETCEXT_TRACK2DATA: Nid = Nid(ffi::NID_setCext_Track2Data); +pub const SETCEXT_TOKENTYPE: Nid = Nid(ffi::NID_setCext_TokenType); +pub const SETCEXT_ISSUERCAPABILITIES: Nid = Nid(ffi::NID_setCext_IssuerCapabilities); +pub const SETATTR_CERT: Nid = Nid(ffi::NID_setAttr_Cert); +pub const SETATTR_PGWYCAP: Nid = Nid(ffi::NID_setAttr_PGWYcap); +pub const SETATTR_TOKENTYPE: Nid = Nid(ffi::NID_setAttr_TokenType); +pub const SETATTR_ISSCAP: Nid = Nid(ffi::NID_setAttr_IssCap); +pub const SET_ROOTKEYTHUMB: Nid = Nid(ffi::NID_set_rootKeyThumb); +pub const SET_ADDPOLICY: Nid = Nid(ffi::NID_set_addPolicy); +pub const SETATTR_TOKEN_EMV: Nid = Nid(ffi::NID_setAttr_Token_EMV); +pub const SETATTR_TOKEN_B0PRIME: Nid = Nid(ffi::NID_setAttr_Token_B0Prime); +pub const SETATTR_ISSCAP_CVM: Nid = Nid(ffi::NID_setAttr_IssCap_CVM); +pub const SETATTR_ISSCAP_T2: Nid = Nid(ffi::NID_setAttr_IssCap_T2); +pub const SETATTR_ISSCAP_SIG: Nid = Nid(ffi::NID_setAttr_IssCap_Sig); +pub const SETATTR_GENCRYPTGRM: Nid = Nid(ffi::NID_setAttr_GenCryptgrm); +pub const SETATTR_T2ENC: Nid = Nid(ffi::NID_setAttr_T2Enc); +pub const SETATTR_T2CLEARTXT: Nid = Nid(ffi::NID_setAttr_T2cleartxt); +pub const SETATTR_TOKICCSIG: Nid = Nid(ffi::NID_setAttr_TokICCsig); +pub const SETATTR_SECDEVSIG: Nid = Nid(ffi::NID_setAttr_SecDevSig); +pub const SET_BRAND_IATA_ATA: Nid = Nid(ffi::NID_set_brand_IATA_ATA); +pub const SET_BRAND_DINERS: Nid = Nid(ffi::NID_set_brand_Diners); +pub const SET_BRAND_AMERICANEXPRESS: Nid = Nid(ffi::NID_set_brand_AmericanExpress); +pub const SET_BRAND_JCB: Nid = Nid(ffi::NID_set_brand_JCB); +pub const SET_BRAND_VISA: Nid = Nid(ffi::NID_set_brand_Visa); +pub const SET_BRAND_MASTERCARD: Nid = Nid(ffi::NID_set_brand_MasterCard); +pub const SET_BRAND_NOVUS: Nid = Nid(ffi::NID_set_brand_Novus); +pub const DES_CDMF: Nid = Nid(ffi::NID_des_cdmf); +pub const RSAOAEPENCRYPTIONSET: Nid = Nid(ffi::NID_rsaOAEPEncryptionSET); +pub const IPSEC3: Nid = Nid(ffi::NID_ipsec3); +pub const IPSEC4: Nid = Nid(ffi::NID_ipsec4); +pub const WHIRLPOOL: Nid = Nid(ffi::NID_whirlpool); +pub const CRYPTOPRO: Nid = Nid(ffi::NID_cryptopro); +pub const CRYPTOCOM: Nid = Nid(ffi::NID_cryptocom); +pub const ID_GOSTR3411_94_WITH_GOSTR3410_2001: Nid = Nid(ffi::NID_id_GostR3411_94_with_GostR3410_2001); +pub const ID_GOSTR3411_94_WITH_GOSTR3410_94: Nid = Nid(ffi::NID_id_GostR3411_94_with_GostR3410_94); +pub const ID_GOSTR3411_94: Nid = Nid(ffi::NID_id_GostR3411_94); +pub const ID_HMACGOSTR3411_94: Nid = Nid(ffi::NID_id_HMACGostR3411_94); +pub const ID_GOSTR3410_2001: Nid = Nid(ffi::NID_id_GostR3410_2001); +pub const ID_GOSTR3410_94: Nid = Nid(ffi::NID_id_GostR3410_94); +pub const ID_GOST28147_89: Nid = Nid(ffi::NID_id_Gost28147_89); +pub const GOST89_CNT: Nid = Nid(ffi::NID_gost89_cnt); +pub const ID_GOST28147_89_MAC: Nid = Nid(ffi::NID_id_Gost28147_89_MAC); +pub const ID_GOSTR3411_94_PRF: Nid = Nid(ffi::NID_id_GostR3411_94_prf); +pub const ID_GOSTR3410_2001DH: Nid = Nid(ffi::NID_id_GostR3410_2001DH); +pub const ID_GOSTR3410_94DH: Nid = Nid(ffi::NID_id_GostR3410_94DH); +pub const ID_GOST28147_89_CRYPTOPRO_KEYMESHING: Nid = Nid(ffi::NID_id_Gost28147_89_CryptoPro_KeyMeshing); +pub const ID_GOST28147_89_NONE_KEYMESHING: Nid = Nid(ffi::NID_id_Gost28147_89_None_KeyMeshing); +pub const ID_GOSTR3411_94_TESTPARAMSET: Nid = Nid(ffi::NID_id_GostR3411_94_TestParamSet); +pub const ID_GOSTR3411_94_CRYPTOPROPARAMSET: Nid = Nid(ffi::NID_id_GostR3411_94_CryptoProParamSet); +pub const ID_GOST28147_89_TESTPARAMSET: Nid = Nid(ffi::NID_id_Gost28147_89_TestParamSet); +pub const ID_GOST28147_89_CRYPTOPRO_A_PARAMSET: Nid = Nid(ffi::NID_id_Gost28147_89_CryptoPro_A_ParamSet); +pub const ID_GOST28147_89_CRYPTOPRO_B_PARAMSET: Nid = Nid(ffi::NID_id_Gost28147_89_CryptoPro_B_ParamSet); +pub const ID_GOST28147_89_CRYPTOPRO_C_PARAMSET: Nid = Nid(ffi::NID_id_Gost28147_89_CryptoPro_C_ParamSet); +pub const ID_GOST28147_89_CRYPTOPRO_D_PARAMSET: Nid = Nid(ffi::NID_id_Gost28147_89_CryptoPro_D_ParamSet); +pub const ID_GOST28147_89_CRYPTOPRO_OSCAR_1_1_PARAMSET: Nid = Nid(ffi::NID_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet); +pub const ID_GOST28147_89_CRYPTOPRO_OSCAR_1_0_PARAMSET: Nid = Nid(ffi::NID_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet); +pub const ID_GOST28147_89_CRYPTOPRO_RIC_1_PARAMSET: Nid = Nid(ffi::NID_id_Gost28147_89_CryptoPro_RIC_1_ParamSet); +pub const ID_GOSTR3410_94_TESTPARAMSET: Nid = Nid(ffi::NID_id_GostR3410_94_TestParamSet); +pub const ID_GOSTR3410_94_CRYPTOPRO_A_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_94_CryptoPro_A_ParamSet); +pub const ID_GOSTR3410_94_CRYPTOPRO_B_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_94_CryptoPro_B_ParamSet); +pub const ID_GOSTR3410_94_CRYPTOPRO_C_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_94_CryptoPro_C_ParamSet); +pub const ID_GOSTR3410_94_CRYPTOPRO_D_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_94_CryptoPro_D_ParamSet); +pub const ID_GOSTR3410_94_CRYPTOPRO_XCHA_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchA_ParamSet); +pub const ID_GOSTR3410_94_CRYPTOPRO_XCHB_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchB_ParamSet); +pub const ID_GOSTR3410_94_CRYPTOPRO_XCHC_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchC_ParamSet); +pub const ID_GOSTR3410_2001_TESTPARAMSET: Nid = Nid(ffi::NID_id_GostR3410_2001_TestParamSet); +pub const ID_GOSTR3410_2001_CRYPTOPRO_A_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_2001_CryptoPro_A_ParamSet); +pub const ID_GOSTR3410_2001_CRYPTOPRO_B_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_2001_CryptoPro_B_ParamSet); +pub const ID_GOSTR3410_2001_CRYPTOPRO_C_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_2001_CryptoPro_C_ParamSet); +pub const ID_GOSTR3410_2001_CRYPTOPRO_XCHA_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet); +pub const ID_GOSTR3410_2001_CRYPTOPRO_XCHB_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet); +pub const ID_GOSTR3410_94_A: Nid = Nid(ffi::NID_id_GostR3410_94_a); +pub const ID_GOSTR3410_94_ABIS: Nid = Nid(ffi::NID_id_GostR3410_94_aBis); +pub const ID_GOSTR3410_94_B: Nid = Nid(ffi::NID_id_GostR3410_94_b); +pub const ID_GOSTR3410_94_BBIS: Nid = Nid(ffi::NID_id_GostR3410_94_bBis); +pub const ID_GOST28147_89_CC: Nid = Nid(ffi::NID_id_Gost28147_89_cc); +pub const ID_GOSTR3410_94_CC: Nid = Nid(ffi::NID_id_GostR3410_94_cc); +pub const ID_GOSTR3410_2001_CC: Nid = Nid(ffi::NID_id_GostR3410_2001_cc); +pub const ID_GOSTR3411_94_WITH_GOSTR3410_94_CC: Nid = Nid(ffi::NID_id_GostR3411_94_with_GostR3410_94_cc); +pub const ID_GOSTR3411_94_WITH_GOSTR3410_2001_CC: Nid = Nid(ffi::NID_id_GostR3411_94_with_GostR3410_2001_cc); +pub const ID_GOSTR3410_2001_PARAMSET_CC: Nid = Nid(ffi::NID_id_GostR3410_2001_ParamSet_cc); +pub const CAMELLIA_128_CBC: Nid = Nid(ffi::NID_camellia_128_cbc); +pub const CAMELLIA_192_CBC: Nid = Nid(ffi::NID_camellia_192_cbc); +pub const CAMELLIA_256_CBC: Nid = Nid(ffi::NID_camellia_256_cbc); +pub const ID_CAMELLIA128_WRAP: Nid = Nid(ffi::NID_id_camellia128_wrap); +pub const ID_CAMELLIA192_WRAP: Nid = Nid(ffi::NID_id_camellia192_wrap); +pub const ID_CAMELLIA256_WRAP: Nid = Nid(ffi::NID_id_camellia256_wrap); +pub const CAMELLIA_128_ECB: Nid = Nid(ffi::NID_camellia_128_ecb); +pub const CAMELLIA_128_OFB128: Nid = Nid(ffi::NID_camellia_128_ofb128); +pub const CAMELLIA_128_CFB128: Nid = Nid(ffi::NID_camellia_128_cfb128); +pub const CAMELLIA_192_ECB: Nid = Nid(ffi::NID_camellia_192_ecb); +pub const CAMELLIA_192_OFB128: Nid = Nid(ffi::NID_camellia_192_ofb128); +pub const CAMELLIA_192_CFB128: Nid = Nid(ffi::NID_camellia_192_cfb128); +pub const CAMELLIA_256_ECB: Nid = Nid(ffi::NID_camellia_256_ecb); +pub const CAMELLIA_256_OFB128: Nid = Nid(ffi::NID_camellia_256_ofb128); +pub const CAMELLIA_256_CFB128: Nid = Nid(ffi::NID_camellia_256_cfb128); +pub const CAMELLIA_128_CFB1: Nid = Nid(ffi::NID_camellia_128_cfb1); +pub const CAMELLIA_192_CFB1: Nid = Nid(ffi::NID_camellia_192_cfb1); +pub const CAMELLIA_256_CFB1: Nid = Nid(ffi::NID_camellia_256_cfb1); +pub const CAMELLIA_128_CFB8: Nid = Nid(ffi::NID_camellia_128_cfb8); +pub const CAMELLIA_192_CFB8: Nid = Nid(ffi::NID_camellia_192_cfb8); +pub const CAMELLIA_256_CFB8: Nid = Nid(ffi::NID_camellia_256_cfb8); +pub const KISA: Nid = Nid(ffi::NID_kisa); +pub const SEED_ECB: Nid = Nid(ffi::NID_seed_ecb); +pub const SEED_CBC: Nid = Nid(ffi::NID_seed_cbc); +pub const SEED_CFB128: Nid = Nid(ffi::NID_seed_cfb128); +pub const SEED_OFB128: Nid = Nid(ffi::NID_seed_ofb128); +pub const HMAC: Nid = Nid(ffi::NID_hmac); +pub const CMAC: Nid = Nid(ffi::NID_cmac); +pub const RC4_HMAC_MD5: Nid = Nid(ffi::NID_rc4_hmac_md5); +pub const AES_128_CBC_HMAC_SHA1: Nid = Nid(ffi::NID_aes_128_cbc_hmac_sha1); +pub const AES_192_CBC_HMAC_SHA1: Nid = Nid(ffi::NID_aes_192_cbc_hmac_sha1); +pub const AES_256_CBC_HMAC_SHA1: Nid = Nid(ffi::NID_aes_256_cbc_hmac_sha1); +pub const AES_128_CBC_HMAC_SHA256: Nid = Nid(ffi::NID_aes_128_cbc_hmac_sha256); +pub const AES_192_CBC_HMAC_SHA256: Nid = Nid(ffi::NID_aes_192_cbc_hmac_sha256); +pub const AES_256_CBC_HMAC_SHA256: Nid = Nid(ffi::NID_aes_256_cbc_hmac_sha256); +pub const DHPUBLICNUMBER: Nid = Nid(ffi::NID_dhpublicnumber); +pub const BRAINPOOLP160R1: Nid = Nid(ffi::NID_brainpoolP160r1); +pub const BRAINPOOLP160T1: Nid = Nid(ffi::NID_brainpoolP160t1); +pub const BRAINPOOLP192R1: Nid = Nid(ffi::NID_brainpoolP192r1); +pub const BRAINPOOLP192T1: Nid = Nid(ffi::NID_brainpoolP192t1); +pub const BRAINPOOLP224R1: Nid = Nid(ffi::NID_brainpoolP224r1); +pub const BRAINPOOLP224T1: Nid = Nid(ffi::NID_brainpoolP224t1); +pub const BRAINPOOLP256R1: Nid = Nid(ffi::NID_brainpoolP256r1); +pub const BRAINPOOLP256T1: Nid = Nid(ffi::NID_brainpoolP256t1); +pub const BRAINPOOLP320R1: Nid = Nid(ffi::NID_brainpoolP320r1); +pub const BRAINPOOLP320T1: Nid = Nid(ffi::NID_brainpoolP320t1); +pub const BRAINPOOLP384R1: Nid = Nid(ffi::NID_brainpoolP384r1); +pub const BRAINPOOLP384T1: Nid = Nid(ffi::NID_brainpoolP384t1); +pub const BRAINPOOLP512R1: Nid = Nid(ffi::NID_brainpoolP512r1); +pub const BRAINPOOLP512T1: Nid = Nid(ffi::NID_brainpoolP512t1); +pub const DHSINGLEPASS_STDDH_SHA1KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_stdDH_sha1kdf_scheme); +pub const DHSINGLEPASS_STDDH_SHA224KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_stdDH_sha224kdf_scheme); +pub const DHSINGLEPASS_STDDH_SHA256KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_stdDH_sha256kdf_scheme); +pub const DHSINGLEPASS_STDDH_SHA384KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_stdDH_sha384kdf_scheme); +pub const DHSINGLEPASS_STDDH_SHA512KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_stdDH_sha512kdf_scheme); +pub const DHSINGLEPASS_COFACTORDH_SHA1KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_cofactorDH_sha1kdf_scheme); +pub const DHSINGLEPASS_COFACTORDH_SHA224KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_cofactorDH_sha224kdf_scheme); +pub const DHSINGLEPASS_COFACTORDH_SHA256KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_cofactorDH_sha256kdf_scheme); +pub const DHSINGLEPASS_COFACTORDH_SHA384KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_cofactorDH_sha384kdf_scheme); +pub const DHSINGLEPASS_COFACTORDH_SHA512KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_cofactorDH_sha512kdf_scheme); +pub const DH_STD_KDF: Nid = Nid(ffi::NID_dh_std_kdf); +pub const DH_COFACTOR_KDF: Nid = Nid(ffi::NID_dh_cofactor_kdf); +pub const CT_PRECERT_SCTS: Nid = Nid(ffi::NID_ct_precert_scts); +pub const CT_PRECERT_POISON: Nid = Nid(ffi::NID_ct_precert_poison); +pub const CT_PRECERT_SIGNER: Nid = Nid(ffi::NID_ct_precert_signer); +pub const CT_CERT_SCTS: Nid = Nid(ffi::NID_ct_cert_scts); +pub const JURISDICTIONLOCALITYNAME: Nid = Nid(ffi::NID_jurisdictionLocalityName); +pub const JURISDICTIONSTATEORPROVINCENAME: Nid = Nid(ffi::NID_jurisdictionStateOrProvinceName); +pub const JURISDICTIONCOUNTRYNAME: Nid = Nid(ffi::NID_jurisdictionCountryName); diff --git a/openssl/src/x509/extension.rs b/openssl/src/x509/extension.rs index fc6b3c3b..7ac66383 100644 --- a/openssl/src/x509/extension.rs +++ b/openssl/src/x509/extension.rs @@ -1,6 +1,6 @@ use std::fmt; -use nid::Nid; +use nid::{self, Nid}; /// Type-only version of the `Extension` enum. /// @@ -71,10 +71,10 @@ impl Extension { impl ExtensionType { pub fn get_nid(&self) -> Option { match self { - &ExtensionType::KeyUsage => Some(Nid::key_usage()), - &ExtensionType::ExtKeyUsage => Some(Nid::ext_key_usage()), - &ExtensionType::SubjectAltName => Some(Nid::subject_alt_name()), - &ExtensionType::IssuerAltName => Some(Nid::issuer_alt_name()), + &ExtensionType::KeyUsage => Some(nid::KEY_USAGE), + &ExtensionType::ExtKeyUsage => Some(nid::EXT_KEY_USAGE), + &ExtensionType::SubjectAltName => Some(nid::SUBJECT_ALT_NAME), + &ExtensionType::IssuerAltName => Some(nid::ISSUER_ALT_NAME), &ExtensionType::OtherNid(nid) => Some(nid), &ExtensionType::OtherStr(_) => None, } diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index c0c7ce87..185c4910 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -8,7 +8,7 @@ use x509::extension::Extension::{KeyUsage, ExtKeyUsage, SubjectAltName, OtherNid use x509::extension::AltNameOption as SAN; use x509::extension::KeyUsageOption::{DigitalSignature, KeyEncipherment}; use x509::extension::ExtKeyUsageOption::{self, ClientAuth, ServerAuth}; -use nid::Nid; +use nid; fn get_generator() -> X509Generator { X509Generator::new() @@ -20,7 +20,7 @@ fn get_generator() -> X509Generator { 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(OtherNid(nid::BASIC_CONSTRAINTS, "critical,CA:TRUE".to_owned())) .add_extension(OtherStr("2.999.2".to_owned(), "ASN1:UTF8:example value".to_owned())) } @@ -48,8 +48,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(OtherNid(nid::SUBJECT_KEY_IDENTIFIER, "hash".to_owned())) + .add_extension(OtherNid(nid::AUTHORITY_KEY_IDENTIFIER, "keyid:always".to_owned())) .sign(&pkey) .expect("Failed to generate cert with order-dependent extensions"); } @@ -60,9 +60,9 @@ 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(), + .add_extension(OtherNid(nid::AUTHORITY_KEY_IDENTIFIER, "keyid:always".to_owned())) - .add_extension(OtherNid(Nid::subject_key_identifier(), "hash".to_owned())) + .add_extension(OtherNid(nid::SUBJECT_KEY_IDENTIFIER, "hash".to_owned())) .sign(&pkey); assert!(result.is_err()); @@ -116,7 +116,7 @@ fn test_subject_read_cn() { let cert = include_bytes!("../../test/cert.pem"); let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); let subject = cert.subject_name(); - let cn = match subject.text_by_nid(Nid::commonName()) { + let cn = match subject.text_by_nid(nid::COMMONNAME) { Some(x) => x, None => panic!("Failed to read CN from cert"), }; @@ -130,19 +130,19 @@ fn test_nid_values() { let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); let subject = cert.subject_name(); - let cn = match subject.text_by_nid(Nid::commonName()) { + let cn = match subject.text_by_nid(nid::COMMONNAME) { Some(x) => x, None => panic!("Failed to read CN from cert"), }; assert_eq!(&cn as &str, "example.com"); - let email = match subject.text_by_nid(Nid::pkcs9_emailAddress()) { + let email = match subject.text_by_nid(nid::PKCS9_EMAILADDRESS) { Some(x) => x, None => panic!("Failed to read subject email address from cert"), }; assert_eq!(&email as &str, "test@example.com"); - let friendly = match subject.text_by_nid(Nid::friendlyName()) { + let friendly = match subject.text_by_nid(nid::FRIENDLYNAME) { Some(x) => x, None => panic!("Failed to read subject friendly name from cert"), }; @@ -155,7 +155,7 @@ fn test_nid_uid_value() { let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); let subject = cert.subject_name(); - let cn = match subject.text_by_nid(Nid::userId()) { + let cn = match subject.text_by_nid(nid::USERID) { Some(x) => x, None => panic!("Failed to read UID from cert"), }; From d39a2cedad749c47e3fabe7701cd1134568e5cfd Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 22 Oct 2016 16:01:26 -0700 Subject: [PATCH 084/186] Fix tests --- openssl/src/hash.rs | 4 ++-- openssl/src/sign.rs | 16 ++++++++-------- openssl/src/x509/extension.rs | 4 ++-- openssl/src/x509/mod.rs | 8 ++++---- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/openssl/src/hash.rs b/openssl/src/hash.rs index 9112ed24..4093ab79 100644 --- a/openssl/src/hash.rs +++ b/openssl/src/hash.rs @@ -77,7 +77,7 @@ use self::State::*; /// Calculate a hash in one go. /// /// ``` -/// use openssl::crypto::hash::{hash, MessageDigest}; +/// use openssl::hash::{hash, MessageDigest}; /// /// let data = b"\x42\xF4\x97\xE0"; /// let spec = b"\x7c\x43\x0f\x17\x8a\xef\xdf\x14\x87\xfe\xe7\x14\x4e\x96\x41\xe2"; @@ -88,7 +88,7 @@ use self::State::*; /// Use the `Write` trait to supply the input in chunks. /// /// ``` -/// use openssl::crypto::hash::{Hasher, MessageDigest}; +/// use openssl::hash::{Hasher, MessageDigest}; /// /// let data = [b"\x42\xF4", b"\x97\xE0"]; /// let spec = b"\x7c\x43\x0f\x17\x8a\xef\xdf\x14\x87\xfe\xe7\x14\x4e\x96\x41\xe2"; diff --git a/openssl/src/sign.rs b/openssl/src/sign.rs index 2e88f38f..a1a37ce6 100644 --- a/openssl/src/sign.rs +++ b/openssl/src/sign.rs @@ -10,13 +10,13 @@ //! Sign and verify data given an RSA keypair: //! //! ```rust -//! use openssl::crypto::sign::{Signer, Verifier}; -//! use openssl::crypto::rsa::RSA; -//! use openssl::crypto::pkey::PKey; -//! use openssl::crypto::hash::MessageDigest; +//! use openssl::sign::{Signer, Verifier}; +//! use openssl::rsa::Rsa; +//! use openssl::pkey::PKey; +//! use openssl::hash::MessageDigest; //! //! // Generate a keypair -//! let keypair = RSA::generate(2048).unwrap(); +//! let keypair = Rsa::generate(2048).unwrap(); //! let keypair = PKey::from_rsa(keypair).unwrap(); //! //! let data = b"hello, world!"; @@ -38,9 +38,9 @@ //! Compute an HMAC (note that `Verifier` cannot be used with HMACs): //! //! ```rust -//! use openssl::crypto::sign::Signer; -//! use openssl::crypto::pkey::PKey; -//! use openssl::crypto::hash::MessageDigest; +//! use openssl::sign::Signer; +//! use openssl::pkey::PKey; +//! use openssl::hash::MessageDigest; //! //! // Create a PKey //! let key = PKey::hmac(b"my secret").unwrap(); diff --git a/openssl/src/x509/extension.rs b/openssl/src/x509/extension.rs index 7ac66383..398bbb3e 100644 --- a/openssl/src/x509/extension.rs +++ b/openssl/src/x509/extension.rs @@ -36,10 +36,10 @@ pub enum Extension { /// /// ``` /// use openssl::x509::extension::Extension::*; - /// use openssl::nid::Nid; + /// use openssl::nid; /// /// # let generator = openssl::x509::X509Generator::new(); - /// generator.add_extension(OtherNid(Nid::BasicConstraints,"critical,CA:TRUE".to_owned())); + /// generator.add_extension(OtherNid(nid::BASIC_CONSTRAINTS,"critical,CA:TRUE".to_owned())); /// ``` OtherNid(Nid, String), /// Arbitrary extensions by OID string. See `man ASN1_generate_nconf` for value syntax. diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 8653b44e..af5c722a 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -130,13 +130,13 @@ impl X509StoreContextRef { /// # Example /// /// ``` -/// use openssl::crypto::hash::MessageDigest; -/// use openssl::crypto::pkey::PKey; -/// use openssl::crypto::rsa::RSA; +/// 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 rsa = Rsa::generate(2048).unwrap(); /// let pkey = PKey::from_rsa(rsa).unwrap(); /// /// let gen = X509Generator::new() From 04fc853ee33b9206062b1d0b233faddf2f4a8609 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 23 Oct 2016 09:16:20 -0700 Subject: [PATCH 085/186] Remove NIDs only defined in 1.0.2+ --- openssl-sys/src/lib.rs | 39 --------------------------------------- openssl/src/nid.rs | 40 +--------------------------------------- 2 files changed, 1 insertion(+), 78 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index dfe2fae0..10e3e895 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -240,7 +240,6 @@ pub const NID_md5WithRSAEncryption: c_int = 8; pub const NID_sha1WithRSAEncryption: c_int = 65; pub const NID_rsaesOaep: c_int = 919; pub const NID_mgf1: c_int = 911; -pub const NID_pSpecified: c_int = 935; pub const NID_rsassaPss: c_int = 912; pub const NID_sha256WithRSAEncryption: c_int = 668; pub const NID_sha384WithRSAEncryption: c_int = 669; @@ -692,7 +691,6 @@ pub const NID_mime_mhs_headings: c_int = 505; pub const NID_mime_mhs_bodies: c_int = 506; pub const NID_id_hex_partial_message: c_int = 507; pub const NID_id_hex_multipart_message: c_int = 508; -pub const NID_rle_compression: c_int = 124; pub const NID_zlib_compression: c_int = 125; pub const NID_aes_128_ecb: c_int = 418; pub const NID_aes_128_cbc: c_int = 419; @@ -1032,43 +1030,6 @@ pub const NID_rc4_hmac_md5: c_int = 915; pub const NID_aes_128_cbc_hmac_sha1: c_int = 916; pub const NID_aes_192_cbc_hmac_sha1: c_int = 917; pub const NID_aes_256_cbc_hmac_sha1: c_int = 918; -pub const NID_aes_128_cbc_hmac_sha256: c_int = 948; -pub const NID_aes_192_cbc_hmac_sha256: c_int = 949; -pub const NID_aes_256_cbc_hmac_sha256: c_int = 950; -pub const NID_dhpublicnumber: c_int = 920; -pub const NID_brainpoolP160r1: c_int = 921; -pub const NID_brainpoolP160t1: c_int = 922; -pub const NID_brainpoolP192r1: c_int = 923; -pub const NID_brainpoolP192t1: c_int = 924; -pub const NID_brainpoolP224r1: c_int = 925; -pub const NID_brainpoolP224t1: c_int = 926; -pub const NID_brainpoolP256r1: c_int = 927; -pub const NID_brainpoolP256t1: c_int = 928; -pub const NID_brainpoolP320r1: c_int = 929; -pub const NID_brainpoolP320t1: c_int = 930; -pub const NID_brainpoolP384r1: c_int = 931; -pub const NID_brainpoolP384t1: c_int = 932; -pub const NID_brainpoolP512r1: c_int = 933; -pub const NID_brainpoolP512t1: c_int = 934; -pub const NID_dhSinglePass_stdDH_sha1kdf_scheme: c_int = 936; -pub const NID_dhSinglePass_stdDH_sha224kdf_scheme: c_int = 937; -pub const NID_dhSinglePass_stdDH_sha256kdf_scheme: c_int = 938; -pub const NID_dhSinglePass_stdDH_sha384kdf_scheme: c_int = 939; -pub const NID_dhSinglePass_stdDH_sha512kdf_scheme: c_int = 940; -pub const NID_dhSinglePass_cofactorDH_sha1kdf_scheme: c_int = 941; -pub const NID_dhSinglePass_cofactorDH_sha224kdf_scheme: c_int = 942; -pub const NID_dhSinglePass_cofactorDH_sha256kdf_scheme: c_int = 943; -pub const NID_dhSinglePass_cofactorDH_sha384kdf_scheme: c_int = 944; -pub const NID_dhSinglePass_cofactorDH_sha512kdf_scheme: c_int = 945; -pub const NID_dh_std_kdf: c_int = 946; -pub const NID_dh_cofactor_kdf: c_int = 947; -pub const NID_ct_precert_scts: c_int = 951; -pub const NID_ct_precert_poison: c_int = 952; -pub const NID_ct_precert_signer: c_int = 953; -pub const NID_ct_cert_scts: c_int = 954; -pub const NID_jurisdictionLocalityName: c_int = 955; -pub const NID_jurisdictionStateOrProvinceName: c_int = 956; -pub const NID_jurisdictionCountryName: c_int = 957; pub const PKCS5_SALT_LEN: c_int = 8; diff --git a/openssl/src/nid.rs b/openssl/src/nid.rs index 480aa91a..b58e3a3d 100644 --- a/openssl/src/nid.rs +++ b/openssl/src/nid.rs @@ -137,7 +137,6 @@ pub const MD5WITHRSAENCRYPTION: Nid = Nid(ffi::NID_md5WithRSAEncryption); pub const SHA1WITHRSAENCRYPTION: Nid = Nid(ffi::NID_sha1WithRSAEncryption); pub const RSAESOAEP: Nid = Nid(ffi::NID_rsaesOaep); pub const MGF1: Nid = Nid(ffi::NID_mgf1); -pub const PSPECIFIED: Nid = Nid(ffi::NID_pSpecified); pub const RSASSAPSS: Nid = Nid(ffi::NID_rsassaPss); pub const SHA256WITHRSAENCRYPTION: Nid = Nid(ffi::NID_sha256WithRSAEncryption); pub const SHA384WITHRSAENCRYPTION: Nid = Nid(ffi::NID_sha384WithRSAEncryption); @@ -589,7 +588,6 @@ pub const MIME_MHS_HEADINGS: Nid = Nid(ffi::NID_mime_mhs_headings); pub const MIME_MHS_BODIES: Nid = Nid(ffi::NID_mime_mhs_bodies); pub const ID_HEX_PARTIAL_MESSAGE: Nid = Nid(ffi::NID_id_hex_partial_message); pub const ID_HEX_MULTIPART_MESSAGE: Nid = Nid(ffi::NID_id_hex_multipart_message); -pub const RLE_COMPRESSION: Nid = Nid(ffi::NID_rle_compression); pub const ZLIB_COMPRESSION: Nid = Nid(ffi::NID_zlib_compression); pub const AES_128_ECB: Nid = Nid(ffi::NID_aes_128_ecb); pub const AES_128_CBC: Nid = Nid(ffi::NID_aes_128_cbc); @@ -929,40 +927,4 @@ pub const RC4_HMAC_MD5: Nid = Nid(ffi::NID_rc4_hmac_md5); pub const AES_128_CBC_HMAC_SHA1: Nid = Nid(ffi::NID_aes_128_cbc_hmac_sha1); pub const AES_192_CBC_HMAC_SHA1: Nid = Nid(ffi::NID_aes_192_cbc_hmac_sha1); pub const AES_256_CBC_HMAC_SHA1: Nid = Nid(ffi::NID_aes_256_cbc_hmac_sha1); -pub const AES_128_CBC_HMAC_SHA256: Nid = Nid(ffi::NID_aes_128_cbc_hmac_sha256); -pub const AES_192_CBC_HMAC_SHA256: Nid = Nid(ffi::NID_aes_192_cbc_hmac_sha256); -pub const AES_256_CBC_HMAC_SHA256: Nid = Nid(ffi::NID_aes_256_cbc_hmac_sha256); -pub const DHPUBLICNUMBER: Nid = Nid(ffi::NID_dhpublicnumber); -pub const BRAINPOOLP160R1: Nid = Nid(ffi::NID_brainpoolP160r1); -pub const BRAINPOOLP160T1: Nid = Nid(ffi::NID_brainpoolP160t1); -pub const BRAINPOOLP192R1: Nid = Nid(ffi::NID_brainpoolP192r1); -pub const BRAINPOOLP192T1: Nid = Nid(ffi::NID_brainpoolP192t1); -pub const BRAINPOOLP224R1: Nid = Nid(ffi::NID_brainpoolP224r1); -pub const BRAINPOOLP224T1: Nid = Nid(ffi::NID_brainpoolP224t1); -pub const BRAINPOOLP256R1: Nid = Nid(ffi::NID_brainpoolP256r1); -pub const BRAINPOOLP256T1: Nid = Nid(ffi::NID_brainpoolP256t1); -pub const BRAINPOOLP320R1: Nid = Nid(ffi::NID_brainpoolP320r1); -pub const BRAINPOOLP320T1: Nid = Nid(ffi::NID_brainpoolP320t1); -pub const BRAINPOOLP384R1: Nid = Nid(ffi::NID_brainpoolP384r1); -pub const BRAINPOOLP384T1: Nid = Nid(ffi::NID_brainpoolP384t1); -pub const BRAINPOOLP512R1: Nid = Nid(ffi::NID_brainpoolP512r1); -pub const BRAINPOOLP512T1: Nid = Nid(ffi::NID_brainpoolP512t1); -pub const DHSINGLEPASS_STDDH_SHA1KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_stdDH_sha1kdf_scheme); -pub const DHSINGLEPASS_STDDH_SHA224KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_stdDH_sha224kdf_scheme); -pub const DHSINGLEPASS_STDDH_SHA256KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_stdDH_sha256kdf_scheme); -pub const DHSINGLEPASS_STDDH_SHA384KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_stdDH_sha384kdf_scheme); -pub const DHSINGLEPASS_STDDH_SHA512KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_stdDH_sha512kdf_scheme); -pub const DHSINGLEPASS_COFACTORDH_SHA1KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_cofactorDH_sha1kdf_scheme); -pub const DHSINGLEPASS_COFACTORDH_SHA224KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_cofactorDH_sha224kdf_scheme); -pub const DHSINGLEPASS_COFACTORDH_SHA256KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_cofactorDH_sha256kdf_scheme); -pub const DHSINGLEPASS_COFACTORDH_SHA384KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_cofactorDH_sha384kdf_scheme); -pub const DHSINGLEPASS_COFACTORDH_SHA512KDF_SCHEME: Nid = Nid(ffi::NID_dhSinglePass_cofactorDH_sha512kdf_scheme); -pub const DH_STD_KDF: Nid = Nid(ffi::NID_dh_std_kdf); -pub const DH_COFACTOR_KDF: Nid = Nid(ffi::NID_dh_cofactor_kdf); -pub const CT_PRECERT_SCTS: Nid = Nid(ffi::NID_ct_precert_scts); -pub const CT_PRECERT_POISON: Nid = Nid(ffi::NID_ct_precert_poison); -pub const CT_PRECERT_SIGNER: Nid = Nid(ffi::NID_ct_precert_signer); -pub const CT_CERT_SCTS: Nid = Nid(ffi::NID_ct_cert_scts); -pub const JURISDICTIONLOCALITYNAME: Nid = Nid(ffi::NID_jurisdictionLocalityName); -pub const JURISDICTIONSTATEORPROVINCENAME: Nid = Nid(ffi::NID_jurisdictionStateOrProvinceName); -pub const JURISDICTIONCOUNTRYNAME: Nid = Nid(ffi::NID_jurisdictionCountryName); + From ca71e008789027893654029fcc57346393e9d324 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 23 Oct 2016 20:55:31 -0700 Subject: [PATCH 086/186] Fix Send + Sync-ness of SslStream --- openssl/src/ssl/bio.rs | 61 +++++++++++++++++++----------------- openssl/src/ssl/mod.rs | 9 +++--- openssl/src/ssl/tests/mod.rs | 8 +++++ 3 files changed, 45 insertions(+), 33 deletions(-) diff --git a/openssl/src/ssl/bio.rs b/openssl/src/ssl/bio.rs index 968aad10..a0215c2f 100644 --- a/openssl/src/ssl/bio.rs +++ b/openssl/src/ssl/bio.rs @@ -7,7 +7,6 @@ use std::io::prelude::*; use std::mem; use std::ptr; use std::slice; -use std::sync::Arc; use cvt_p; use error::ErrorStack; @@ -22,15 +21,16 @@ pub struct StreamState { pub struct BioMethod(compat::BIO_METHOD); impl BioMethod { - pub fn new() -> BioMethod { + fn new() -> BioMethod { BioMethod(compat::BIO_METHOD::new::()) } } +unsafe impl Sync for BioMethod {} unsafe impl Send for BioMethod {} -pub fn new(stream: S) -> Result<(*mut BIO, Arc), ErrorStack> { - let method = Arc::new(BioMethod::new::()); +pub fn new(stream: S) -> Result<(*mut BIO, BioMethod), ErrorStack> { + let method = BioMethod::new::(); let state = Box::new(StreamState { stream: stream, @@ -188,9 +188,7 @@ mod compat { pub unsafe fn BIO_set_num(_bio: *mut ffi::BIO, _num: c_int) {} - pub struct BIO_METHOD { - inner: *mut ffi::BIO_METHOD, - } + pub struct BIO_METHOD(*mut ffi::BIO_METHOD); impl BIO_METHOD { pub fn new() -> BIO_METHOD { @@ -198,7 +196,7 @@ mod compat { let ptr = ffi::BIO_meth_new(ffi::BIO_TYPE_NONE, b"rust\0".as_ptr() as *const _); assert!(!ptr.is_null()); - let ret = BIO_METHOD { inner: ptr }; + let ret = BIO_METHOD(ptr); assert!(ffi::BIO_meth_set_write(ptr, super::bwrite::) != 0); assert!(ffi::BIO_meth_set_read(ptr, super::bread::) != 0); assert!(ffi::BIO_meth_set_puts(ptr, super::bputs::) != 0); @@ -210,14 +208,14 @@ mod compat { } pub fn get(&self) -> *mut ffi::BIO_METHOD { - self.inner + self.0 } } impl Drop for BIO_METHOD { fn drop(&mut self) { unsafe { - ffi::BIO_meth_free(self.inner); + ffi::BIO_meth_free(self.0); } } } @@ -227,35 +225,40 @@ mod compat { #[allow(bad_style)] mod compat { use std::io::{Read, Write}; - use std::cell::UnsafeCell; use ffi; use libc::{c_int, c_void}; - pub struct BIO_METHOD { - inner: UnsafeCell, - } + pub struct BIO_METHOD(*mut ffi::BIO_METHOD); impl BIO_METHOD { pub fn new() -> BIO_METHOD { - BIO_METHOD { - inner: UnsafeCell::new(ffi::BIO_METHOD { - type_: ffi::BIO_TYPE_NONE, - name: b"rust\0".as_ptr() as *const _, - bwrite: Some(super::bwrite::), - bread: Some(super::bread::), - bputs: Some(super::bputs::), - bgets: None, - ctrl: Some(super::ctrl::), - create: Some(super::create), - destroy: Some(super::destroy::), - callback_ctrl: None, - }), - } + let ptr = Box::new(ffi::BIO_METHOD { + type_: ffi::BIO_TYPE_NONE, + name: b"rust\0".as_ptr() as *const _, + bwrite: Some(super::bwrite::), + bread: Some(super::bread::), + bputs: Some(super::bputs::), + bgets: None, + ctrl: Some(super::ctrl::), + create: Some(super::create), + destroy: Some(super::destroy::), + callback_ctrl: None, + }); + + BIO_METHOD(Box::into_raw(ptr)) } pub fn get(&self) -> *mut ffi::BIO_METHOD { - self.inner.get() + self.0 + } + } + + impl Drop for BIO_METHOD { + fn drop(&mut self) { + unsafe { + Box::::from_raw(self.0); + } } } diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 6e5a2c09..92e0c159 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -13,7 +13,7 @@ use std::ops::{Deref, DerefMut}; use std::path::Path; use std::ptr; use std::str; -use std::sync::{Mutex, Arc}; +use std::sync::Mutex; use libc::{c_uchar, c_uint}; use std::slice; use std::marker::PhantomData; @@ -1023,6 +1023,9 @@ impl SslRef { pub struct Ssl(*mut ffi::SSL); +unsafe impl Sync for Ssl {} +unsafe impl Send for Ssl {} + impl fmt::Debug for Ssl { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let mut builder = fmt.debug_struct("Ssl"); @@ -1128,12 +1131,10 @@ impl Ssl { /// A stream wrapper which handles SSL encryption for an underlying stream. pub struct SslStream { ssl: Ssl, - _method: Arc, // NOTE: this *must* be after the Ssl field so things drop right + _method: BioMethod, // NOTE: this *must* be after the Ssl field so things drop right _p: PhantomData, } -unsafe impl Send for SslStream {} - impl fmt::Debug for SslStream where S: fmt::Debug { diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 45c5b215..d11073f2 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -1083,3 +1083,11 @@ fn invalid_hostname() { let s = TcpStream::connect("google.com:443").unwrap(); assert!(ssl.connect(s).is_err()); } + +fn _check_kinds() { + fn is_send() {} + fn is_sync() {} + + is_send::>(); + is_sync::>(); +} From 938fdd71374b040609cdf3d2a8e1f28abbf15203 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 23 Oct 2016 21:54:49 -0700 Subject: [PATCH 087/186] Add into_error --- openssl/src/ssl/mod.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 92e0c159..3327ff22 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -1254,6 +1254,11 @@ impl MidHandshakeSslStream { &self.error } + /// Consumes `self`, returning its error. + pub fn into_error(self) -> Error { + self.error + } + /// Restarts the handshake process. pub fn handshake(mut self) -> Result, HandshakeError> { let ret = unsafe { ffi::SSL_do_handshake(self.stream.ssl.as_ptr()) }; From eb655bddbc8c0f5d79090fe0c0b3c9dfe40f6dd1 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 25 Oct 2016 20:01:28 -0700 Subject: [PATCH 088/186] Fix ordering --- openssl/src/ssl/mod.rs | 118 ++++++++++++++++++++--------------------- 1 file changed, 59 insertions(+), 59 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 3327ff22..bf4c03f7 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -1128,65 +1128,6 @@ impl Ssl { } } -/// A stream wrapper which handles SSL encryption for an underlying stream. -pub struct SslStream { - ssl: Ssl, - _method: BioMethod, // NOTE: this *must* be after the Ssl field so things drop right - _p: PhantomData, -} - -impl fmt::Debug for SslStream - where S: fmt::Debug -{ - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("SslStream") - .field("stream", &self.get_ref()) - .field("ssl", &self.ssl()) - .finish() - } -} - -impl SslStream { - fn new_base(ssl: Ssl, stream: S) -> Self { - unsafe { - let (bio, method) = bio::new(stream).unwrap(); - ffi::SSL_set_bio(ssl.as_ptr(), bio, bio); - - SslStream { - ssl: ssl, - _method: method, - _p: PhantomData, - } - } - } - - /// Like `read`, but returns an `ssl::Error` rather than an `io::Error`. - /// - /// This is particularly useful with a nonblocking socket, where the error - /// value will identify if OpenSSL is waiting on read or write readiness. - pub fn ssl_read(&mut self, buf: &mut [u8]) -> Result { - let ret = self.ssl.read(buf); - if ret >= 0 { - Ok(ret as usize) - } else { - Err(self.make_error(ret)) - } - } - - /// Like `write`, but returns an `ssl::Error` rather than an `io::Error`. - /// - /// This is particularly useful with a nonblocking socket, where the error - /// value will identify if OpenSSL is waiting on read or write readiness. - pub fn ssl_write(&mut self, buf: &[u8]) -> Result { - let ret = self.ssl.write(buf); - if ret >= 0 { - Ok(ret as usize) - } else { - Err(self.make_error(ret)) - } - } -} - /// An error or intermediate state after a TLS handshake attempt. #[derive(Debug)] pub enum HandshakeError { @@ -1280,6 +1221,65 @@ impl MidHandshakeSslStream { } } +/// A stream wrapper which handles SSL encryption for an underlying stream. +pub struct SslStream { + ssl: Ssl, + _method: BioMethod, // NOTE: this *must* be after the Ssl field so things drop right + _p: PhantomData, +} + +impl fmt::Debug for SslStream + where S: fmt::Debug +{ + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("SslStream") + .field("stream", &self.get_ref()) + .field("ssl", &self.ssl()) + .finish() + } +} + +impl SslStream { + fn new_base(ssl: Ssl, stream: S) -> Self { + unsafe { + let (bio, method) = bio::new(stream).unwrap(); + ffi::SSL_set_bio(ssl.as_ptr(), bio, bio); + + SslStream { + ssl: ssl, + _method: method, + _p: PhantomData, + } + } + } + + /// Like `read`, but returns an `ssl::Error` rather than an `io::Error`. + /// + /// This is particularly useful with a nonblocking socket, where the error + /// value will identify if OpenSSL is waiting on read or write readiness. + pub fn ssl_read(&mut self, buf: &mut [u8]) -> Result { + let ret = self.ssl.read(buf); + if ret >= 0 { + Ok(ret as usize) + } else { + Err(self.make_error(ret)) + } + } + + /// Like `write`, but returns an `ssl::Error` rather than an `io::Error`. + /// + /// This is particularly useful with a nonblocking socket, where the error + /// value will identify if OpenSSL is waiting on read or write readiness. + pub fn ssl_write(&mut self, buf: &[u8]) -> Result { + let ret = self.ssl.write(buf); + if ret >= 0 { + Ok(ret as usize) + } else { + Err(self.make_error(ret)) + } + } +} + impl SslStream { fn make_error(&mut self, ret: c_int) -> Error { self.check_panic(); From 39279455c8b0132d58742b8a08e884c3fde404fd Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 25 Oct 2016 20:40:18 -0700 Subject: [PATCH 089/186] Add a shutdown method --- openssl-sys/src/lib.rs | 1 + openssl/src/ssl/mod.rs | 30 ++++++++++++++++++++++++++++++ openssl/src/ssl/tests/mod.rs | 34 +++++++++++++++++++++++++++++++++- 3 files changed, 64 insertions(+), 1 deletion(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 10e3e895..fd5aa469 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1556,6 +1556,7 @@ extern { #[cfg(not(ossl101))] pub fn SSL_get0_param(ssl: *mut SSL) -> *mut X509_VERIFY_PARAM; pub fn SSL_get_verify_result(ssl: *const SSL) -> c_long; + pub fn SSL_shutdown(ssl: *mut SSL) -> c_int; #[cfg(not(osslconf = "OPENSSL_NO_COMP"))] pub fn SSL_COMP_get_name(comp: *const COMP_METHOD) -> *const c_char; diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index bf4c03f7..2577600f 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -1278,6 +1278,26 @@ impl SslStream { Err(self.make_error(ret)) } } + + /// Shuts down the session. + /// + /// The shutdown process consists of two steps. The first step sends a + /// close notify message to the peer, after which `ShutdownResult::Sent` + /// is returned. The second step awaits the receipt of a close notify + /// message from the peer, after which `ShutdownResult::Received` is + /// returned. + /// + /// While the connection may be closed after the first step, it is + /// recommended to fully shut the session down. In particular, it must + /// be fully shut down if the connection is to be used for further + /// communication in the future. + pub fn shutdown(&mut self) -> Result { + match unsafe { ffi::SSL_shutdown(self.ssl.as_ptr()) } { + 0 => Ok(ShutdownResult::Sent), + 1 => Ok(ShutdownResult::Received), + n => Err(self.make_error(n)), + } + } } impl SslStream { @@ -1383,6 +1403,16 @@ impl Write for SslStream { } } +/// The result of a shutdown request. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum ShutdownResult { + /// A close notify message has been sent to the peer. + Sent, + + /// A close notify response message has been received from the peer. + Received, +} + #[cfg(ossl110)] mod compat { use std::ptr; diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index d11073f2..4bc6f216 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -19,7 +19,7 @@ use ssl; use ssl::SSL_VERIFY_PEER; use ssl::{SslMethod, HandshakeError}; use ssl::error::Error; -use ssl::{SslContext, SslStream, Ssl}; +use ssl::{SslContext, SslStream, Ssl, ShutdownResult}; use x509::X509StoreContextRef; use x509::X509FileType; use x509::X509; @@ -1084,6 +1084,38 @@ fn invalid_hostname() { assert!(ssl.connect(s).is_err()); } +#[test] +fn shutdown() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + + thread::spawn(move || { + let stream = listener.accept().unwrap().0; + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM).unwrap(); + ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM).unwrap(); + let ssl = Ssl::new(&ctx).unwrap(); + let mut stream = ssl.accept(stream).unwrap(); + + stream.write_all(b"hello").unwrap(); + let mut buf = [0; 1]; + assert_eq!(stream.read(&mut buf).unwrap(), 0); + assert_eq!(stream.shutdown().unwrap(), ShutdownResult::Received); + }); + + let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let ctx = SslContext::new(SslMethod::tls()).unwrap(); + let ssl = Ssl::new(&ctx).unwrap(); + let mut stream = ssl.connect(stream).unwrap(); + + let mut buf = [0; 5]; + stream.read_exact(&mut buf).unwrap(); + assert_eq!(b"hello", &buf); + + assert_eq!(stream.shutdown().unwrap(), ShutdownResult::Sent); + assert_eq!(stream.shutdown().unwrap(), ShutdownResult::Received); +} + fn _check_kinds() { fn is_send() {} fn is_sync() {} From bea53bb39b93a7891163c54eaa8b6a519b54a68a Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 25 Oct 2016 20:58:33 -0700 Subject: [PATCH 090/186] Support AES GCM Closes #326 --- openssl-sys/src/lib.rs | 4 ++-- openssl/src/symm.rs | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index fd5aa469..ac168c48 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1359,7 +1359,7 @@ extern { pub fn EVP_aes_128_ecb() -> *const EVP_CIPHER; pub fn EVP_aes_128_xts() -> *const EVP_CIPHER; pub fn EVP_aes_128_ctr() -> *const EVP_CIPHER; - // fn EVP_aes_128_gcm() -> EVP_CIPHER; + pub fn EVP_aes_128_gcm() -> *const EVP_CIPHER; pub fn EVP_aes_128_cfb1() -> *const EVP_CIPHER; pub fn EVP_aes_128_cfb128() -> *const EVP_CIPHER; pub fn EVP_aes_128_cfb8() -> *const EVP_CIPHER; @@ -1367,7 +1367,7 @@ extern { pub fn EVP_aes_256_ecb() -> *const EVP_CIPHER; pub fn EVP_aes_256_xts() -> *const EVP_CIPHER; pub fn EVP_aes_256_ctr() -> *const EVP_CIPHER; - // fn EVP_aes_256_gcm() -> EVP_CIPHER; + pub fn EVP_aes_256_gcm() -> *const EVP_CIPHER; pub fn EVP_aes_256_cfb1() -> *const EVP_CIPHER; pub fn EVP_aes_256_cfb128() -> *const EVP_CIPHER; pub fn EVP_aes_256_cfb8() -> *const EVP_CIPHER; diff --git a/openssl/src/symm.rs b/openssl/src/symm.rs index 65f0addb..bffe337a 100644 --- a/openssl/src/symm.rs +++ b/openssl/src/symm.rs @@ -58,6 +58,12 @@ impl Cipher { } } + pub fn aes_128_gcm() -> Cipher { + unsafe { + Cipher(ffi::EVP_aes_128_gcm()) + } + } + pub fn aes_256_ecb() -> Cipher { unsafe { Cipher(ffi::EVP_aes_256_ecb()) @@ -100,6 +106,12 @@ impl Cipher { } } + pub fn aes_256_gcm() -> Cipher { + unsafe { + Cipher(ffi::EVP_aes_256_gcm()) + } + } + pub fn des_cbc() -> Cipher { unsafe { Cipher(ffi::EVP_des_cbc()) @@ -118,6 +130,10 @@ impl Cipher { } } + pub unsafe fn from_ptr(ptr: *const ffi::EVP_CIPHER) -> Cipher { + Cipher(ptr) + } + pub fn as_ptr(&self) -> *const ffi::EVP_CIPHER { self.0 } From f4b70067719a6724658a2b67e80eaf9b38ab89bc Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 25 Oct 2016 23:12:56 -0700 Subject: [PATCH 091/186] Don't allow mutation of SslContexts SslContext is reference counted and the various setter methods don't take out locks where necessary. Fix this by adding a builder for the context. --- openssl/src/dh.rs | 6 +- openssl/src/ssl/mod.rs | 85 ++++++++++------ openssl/src/ssl/tests/mod.rs | 192 +++++++++++++++++------------------ 3 files changed, 155 insertions(+), 128 deletions(-) diff --git a/openssl/src/dh.rs b/openssl/src/dh.rs index 3b06951e..7111a068 100644 --- a/openssl/src/dh.rs +++ b/openssl/src/dh.rs @@ -101,7 +101,7 @@ mod tests { #[test] #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn test_dh_rfc5114() { - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); let dh1 = DH::get_1024_160().unwrap(); ctx.set_tmp_dh(&dh1).unwrap(); let dh2 = DH::get_2048_224().unwrap(); @@ -112,7 +112,7 @@ mod tests { #[test] fn test_dh() { - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); let p = BigNum::from_hex_str("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435\ E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF429\ 6D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C02\ @@ -142,7 +142,7 @@ mod tests { #[test] fn test_dh_from_pem() { - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); let params = include_bytes!("../test/dhparams.pem"); let dh = DH::from_pem(params).ok().expect("Failed to load PEM"); ctx.set_tmp_dh(&dh).unwrap(); diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 2577600f..d6f5e160 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -335,20 +335,34 @@ pub enum SniError { NoAck, } -/// A borrowed SSL context object. -pub struct SslContextRef(Opaque); +pub struct SslContextBuilder(*mut ffi::SSL_CTX); -impl SslContextRef { - pub unsafe fn from_ptr<'a>(ctx: *mut ffi::SSL_CTX) -> &'a SslContextRef { - &*(ctx as *mut _) +impl Drop for SslContextBuilder { + fn drop(&mut self) { + unsafe { ffi::SSL_CTX_free(self.as_ptr()) } + } +} + +impl SslContextBuilder { + pub fn new(method: SslMethod) -> Result { + init(); + + let mut ctx = unsafe { + let ctx = try!(cvt_p(ffi::SSL_CTX_new(method.as_ptr()))); + SslContextBuilder::from_ptr(ctx) + }; + + try!(ctx.set_mode(ffi::SSL_MODE_AUTO_RETRY | ffi::SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)); + + Ok(ctx) } - pub unsafe fn from_ptr_mut<'a>(ctx: *mut ffi::SSL_CTX) -> &'a mut SslContextRef { - &mut *(ctx as *mut _) + pub unsafe fn from_ptr(ctx: *mut ffi::SSL_CTX) -> SslContextBuilder { + SslContextBuilder(ctx) } pub fn as_ptr(&self) -> *mut ffi::SSL_CTX { - self as *const _ as *mut _ + self.0 } /// Configures the certificate verification method for new connections. @@ -409,7 +423,7 @@ impl SslContextRef { pub fn set_tmp_dh(&mut self, dh: &DH) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::SSL_CTX_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as i32).map(|_| ()) + cvt(ffi::SSL_CTX_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as c_int).map(|_| ()) } } @@ -470,7 +484,7 @@ impl SslContextRef { /// Specifies the file that contains certificate chain pub fn set_certificate_chain_file>(&mut self, file: P) - -> Result<(), ErrorStack> { + -> Result<(), ErrorStack> { let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap(); unsafe { cvt(ffi::SSL_CTX_use_certificate_chain_file(self.as_ptr(), @@ -517,13 +531,6 @@ impl SslContextRef { } } - /// Check consistency of private key and certificate - pub fn check_private_key(&mut self) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::SSL_CTX_check_private_key(self.as_ptr())).map(|_| ()) - } - } - pub fn set_cipher_list(&mut self, cipher_list: &str) -> Result<(), ErrorStack> { let cipher_list = CString::new(cipher_list).unwrap(); unsafe { @@ -628,6 +635,36 @@ impl SslContextRef { Ok(()) } } + + /// Checks consistency between the private key and certificate. + pub fn check_private_key(&self) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::SSL_CTX_check_private_key(self.as_ptr())).map(|_| ()) + } + } + + pub fn build(self) -> SslContext { + let ctx = SslContext(self.0); + mem::forget(self); + ctx + } +} + +/// A borrowed SSL context object. +pub struct SslContextRef(Opaque); + +impl SslContextRef { + pub unsafe fn from_ptr<'a>(ctx: *mut ffi::SSL_CTX) -> &'a SslContextRef { + &*(ctx as *mut _) + } + + pub unsafe fn from_ptr_mut<'a>(ctx: *mut ffi::SSL_CTX) -> &'a mut SslContextRef { + &mut *(ctx as *mut _) + } + + pub fn as_ptr(&self) -> *mut ffi::SSL_CTX { + self as *const _ as *mut _ + } } /// An owned SSL context object. @@ -677,18 +714,8 @@ impl DerefMut for SslContext { } impl SslContext { - /// Creates a new SSL context. - pub fn new(method: SslMethod) -> Result { - init(); - - let mut ctx = unsafe { - let ctx = try!(cvt_p(ffi::SSL_CTX_new(method.as_ptr()))); - SslContext::from_ptr(ctx) - }; - - try!(ctx.set_mode(ffi::SSL_MODE_AUTO_RETRY | ffi::SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)); - - Ok(ctx) + pub fn builder(method: SslMethod) -> Result { + SslContextBuilder::new(method) } pub unsafe fn from_ptr(ctx: *mut ffi::SSL_CTX) -> SslContext { diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 4bc6f216..ca4af6f7 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -189,87 +189,87 @@ macro_rules! run_test( ); run_test!(new_ctx, |method, _| { - SslContext::new(method).unwrap(); + SslContext::builder(method).unwrap(); }); run_test!(verify_untrusted, |method, stream| { - let mut ctx = SslContext::new(method).unwrap(); + let mut ctx = SslContext::builder(method).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - match Ssl::new(&ctx).unwrap().connect(stream) { + match Ssl::new(&ctx.build()).unwrap().connect(stream) { Ok(_) => panic!("expected failure"), Err(err) => println!("error {:?}", err), } }); run_test!(verify_trusted, |method, stream| { - let mut ctx = SslContext::new(method).unwrap(); + let mut ctx = SslContext::builder(method).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - match Ssl::new(&ctx).unwrap().connect(stream) { + match Ssl::new(&ctx.build()).unwrap().connect(stream) { Ok(_) => (), Err(err) => panic!("Expected success, got {:?}", err), } }); run_test!(verify_untrusted_callback_override_ok, |method, stream| { - let mut ctx = SslContext::new(method).unwrap(); + let mut ctx = SslContext::builder(method).unwrap(); ctx.set_verify_callback(SSL_VERIFY_PEER, |_, _| true); - match Ssl::new(&ctx).unwrap().connect(stream) { + match Ssl::new(&ctx.build()).unwrap().connect(stream) { Ok(_) => (), Err(err) => panic!("Expected success, got {:?}", err), } }); run_test!(verify_untrusted_callback_override_bad, |method, stream| { - let mut ctx = SslContext::new(method).unwrap(); + let mut ctx = SslContext::builder(method).unwrap(); ctx.set_verify_callback(SSL_VERIFY_PEER, |_, _| false); - assert!(Ssl::new(&ctx).unwrap().connect(stream).is_err()); + assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_err()); }); run_test!(verify_trusted_callback_override_ok, |method, stream| { - let mut ctx = SslContext::new(method).unwrap(); + let mut ctx = SslContext::builder(method).unwrap(); ctx.set_verify_callback(SSL_VERIFY_PEER, |_, _| true); match ctx.set_CA_file(&Path::new("test/cert.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - match Ssl::new(&ctx).unwrap().connect(stream) { + match Ssl::new(&ctx.build()).unwrap().connect(stream) { Ok(_) => (), Err(err) => panic!("Expected success, got {:?}", err), } }); run_test!(verify_trusted_callback_override_bad, |method, stream| { - let mut ctx = SslContext::new(method).unwrap(); + let mut ctx = SslContext::builder(method).unwrap(); ctx.set_verify_callback(SSL_VERIFY_PEER, |_, _| false); match ctx.set_CA_file(&Path::new("test/cert.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - assert!(Ssl::new(&ctx).unwrap().connect(stream).is_err()); + assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_err()); }); run_test!(verify_callback_load_certs, |method, stream| { - let mut ctx = SslContext::new(method).unwrap(); + let mut ctx = SslContext::builder(method).unwrap(); ctx.set_verify_callback(SSL_VERIFY_PEER, |_, x509_ctx| { assert!(x509_ctx.current_cert().is_some()); true }); - assert!(Ssl::new(&ctx).unwrap().connect(stream).is_ok()); + assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_ok()); }); run_test!(verify_trusted_get_error_ok, |method, stream| { - let mut ctx = SslContext::new(method).unwrap(); + let mut ctx = SslContext::builder(method).unwrap(); ctx.set_verify_callback(SSL_VERIFY_PEER, |_, x509_ctx| { assert!(x509_ctx.error().is_none()); true @@ -279,21 +279,21 @@ run_test!(verify_trusted_get_error_ok, |method, stream| { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - assert!(Ssl::new(&ctx).unwrap().connect(stream).is_ok()); + assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_ok()); }); run_test!(verify_trusted_get_error_err, |method, stream| { - let mut ctx = SslContext::new(method).unwrap(); + let mut ctx = SslContext::builder(method).unwrap(); ctx.set_verify_callback(SSL_VERIFY_PEER, |_, x509_ctx| { assert!(x509_ctx.error().is_some()); false }); - assert!(Ssl::new(&ctx).unwrap().connect(stream).is_err()); + assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_err()); }); run_test!(verify_callback_data, |method, stream| { - let mut ctx = SslContext::new(method).unwrap(); + let mut ctx = SslContext::builder(method).unwrap(); // Node id was generated as SHA256 hash of certificate "test/cert.pem" // in DER format. @@ -313,7 +313,7 @@ run_test!(verify_callback_data, |method, stream| { }); ctx.set_verify_depth(1); - match Ssl::new(&ctx).unwrap().connect(stream) { + match Ssl::new(&ctx.build()).unwrap().connect(stream) { Ok(_) => (), Err(err) => panic!("Expected success, got {:?}", err), } @@ -324,8 +324,8 @@ run_test!(ssl_verify_callback, |method, stream| { static CHECKED: AtomicUsize = ATOMIC_USIZE_INIT; - let ctx = SslContext::new(method).unwrap(); - let mut ssl = Ssl::new(&ctx).unwrap(); + let ctx = SslContext::builder(method).unwrap(); + let mut ssl = Ssl::new(&ctx.build()).unwrap(); let node_hash_str = "59172d9313e84459bcff27f967e79e6e9217e584"; let node_id = node_hash_str.from_hex().unwrap(); @@ -355,20 +355,20 @@ fn test_write_hits_stream() { let addr = listener.local_addr().unwrap(); let guard = thread::spawn(move || { - let ctx = SslContext::new(SslMethod::tls()).unwrap(); + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); let stream = TcpStream::connect(addr).unwrap(); - let mut stream = Ssl::new(&ctx).unwrap().connect(stream).unwrap(); + let mut stream = Ssl::new(&ctx.build()).unwrap().connect(stream).unwrap(); stream.write_all(b"hello").unwrap(); stream }); - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM).unwrap(); ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM).unwrap(); let stream = listener.accept().unwrap().0; - let mut stream = Ssl::new(&ctx).unwrap().accept(stream).unwrap(); + let mut stream = Ssl::new(&ctx.build()).unwrap().accept(stream).unwrap(); let mut buf = [0; 5]; assert_eq!(5, stream.read(&mut buf).unwrap()); @@ -383,7 +383,7 @@ fn test_set_certificate_and_private_key() { let cert = include_bytes!("../../../test/cert.pem"); let cert = X509::from_pem(cert).unwrap(); - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_private_key(&key).unwrap(); ctx.set_certificate(&cert).unwrap(); @@ -391,18 +391,18 @@ fn test_set_certificate_and_private_key() { } run_test!(get_ctx_options, |method, _| { - let ctx = SslContext::new(method).unwrap(); + let ctx = SslContext::builder(method).unwrap(); ctx.options(); }); run_test!(set_ctx_options, |method, _| { - let mut ctx = SslContext::new(method).unwrap(); + let mut ctx = SslContext::builder(method).unwrap(); let opts = ctx.set_options(ssl::SSL_OP_NO_TICKET); assert!(opts.contains(ssl::SSL_OP_NO_TICKET)); }); run_test!(clear_ctx_options, |method, _| { - let mut ctx = SslContext::new(method).unwrap(); + let mut ctx = SslContext::builder(method).unwrap(); ctx.set_options(ssl::SSL_OP_ALL); let opts = ctx.clear_options(ssl::SSL_OP_ALL); assert!(!opts.contains(ssl::SSL_OP_ALL)); @@ -411,8 +411,8 @@ run_test!(clear_ctx_options, |method, _| { #[test] fn test_write() { let (_s, stream) = Server::new(); - let ctx = SslContext::new(SslMethod::tls()).unwrap(); - let mut stream = Ssl::new(&ctx).unwrap().connect(stream).unwrap(); + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let mut stream = Ssl::new(&ctx.build()).unwrap().connect(stream).unwrap(); stream.write_all("hello".as_bytes()).unwrap(); stream.flush().unwrap(); stream.write_all(" there".as_bytes()).unwrap(); @@ -420,8 +420,8 @@ fn test_write() { } run_test!(get_peer_certificate, |method, stream| { - let ctx = SslContext::new(method).unwrap(); - let stream = Ssl::new(&ctx).unwrap().connect(stream).unwrap(); + let ctx = SslContext::builder(method).unwrap(); + let stream = Ssl::new(&ctx.build()).unwrap().connect(stream).unwrap(); let cert = stream.ssl().peer_certificate().unwrap(); let fingerprint = cert.fingerprint(MessageDigest::sha1()).unwrap(); let node_hash_str = "59172d9313e84459bcff27f967e79e6e9217e584"; @@ -433,8 +433,8 @@ run_test!(get_peer_certificate, |method, stream| { #[cfg_attr(any(windows, target_arch = "arm"), ignore)] // FIXME(#467) fn test_write_dtlsv1() { let (_s, stream) = Server::new_dtlsv1(iter::repeat("y\n")); - let ctx = SslContext::new(SslMethod::dtls()).unwrap(); - let mut stream = Ssl::new(&ctx).unwrap().connect(stream).unwrap(); + let ctx = SslContext::builder(SslMethod::dtls()).unwrap(); + let mut stream = Ssl::new(&ctx.build()).unwrap().connect(stream).unwrap(); stream.write_all(b"hello").unwrap(); stream.flush().unwrap(); stream.write_all(b" there").unwrap(); @@ -444,8 +444,8 @@ fn test_write_dtlsv1() { #[test] fn test_read() { let (_s, tcp) = Server::new(); - let ctx = SslContext::new(SslMethod::tls()).unwrap(); - let mut stream = Ssl::new(&ctx).unwrap().connect(tcp).unwrap(); + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let mut stream = Ssl::new(&ctx.build()).unwrap().connect(tcp).unwrap(); stream.write_all("GET /\r\n\r\n".as_bytes()).unwrap(); stream.flush().unwrap(); io::copy(&mut stream, &mut io::sink()).ok().expect("read error"); @@ -454,8 +454,8 @@ fn test_read() { #[test] fn test_pending() { let (_s, tcp) = Server::new(); - let ctx = SslContext::new(SslMethod::tls()).unwrap(); - let mut stream = Ssl::new(&ctx).unwrap().connect(tcp).unwrap(); + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let mut stream = Ssl::new(&ctx.build()).unwrap().connect(tcp).unwrap(); stream.write_all("GET /\r\n\r\n".as_bytes()).unwrap(); stream.flush().unwrap(); @@ -478,8 +478,8 @@ fn test_pending() { #[test] fn test_state() { let (_s, tcp) = Server::new(); - let ctx = SslContext::new(SslMethod::tls()).unwrap(); - let stream = Ssl::new(&ctx).unwrap().connect(tcp).unwrap(); + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let stream = Ssl::new(&ctx.build()).unwrap().connect(tcp).unwrap(); assert_eq!(stream.ssl().state_string(), "SSLOK "); assert_eq!(stream.ssl().state_string_long(), "SSL negotiation finished successfully"); @@ -491,14 +491,14 @@ fn test_state() { #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn test_connect_with_unilateral_alpn() { let (_s, stream) = Server::new(); - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - let stream = match Ssl::new(&ctx).unwrap().connect(stream) { + let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { Ok(stream) => stream, Err(err) => panic!("Expected success, got {:?}", err), }; @@ -512,14 +512,14 @@ fn test_connect_with_unilateral_alpn() { #[test] fn test_connect_with_unilateral_npn() { let (_s, stream) = Server::new(); - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - let stream = match Ssl::new(&ctx).unwrap().connect(stream) { + let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { Ok(stream) => stream, Err(err) => panic!("Expected success, got {:?}", err), }; @@ -534,14 +534,14 @@ fn test_connect_with_unilateral_npn() { #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn test_connect_with_alpn_successful_multiple_matching() { let (_s, stream) = Server::new_alpn(); - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"spdy/3.1", b"http/1.1"]).unwrap(); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - let stream = match Ssl::new(&ctx).unwrap().connect(stream) { + let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { Ok(stream) => stream, Err(err) => panic!("Expected success, got {:?}", err), }; @@ -556,14 +556,14 @@ fn test_connect_with_alpn_successful_multiple_matching() { #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn test_connect_with_npn_successful_multiple_matching() { let (_s, stream) = Server::new_alpn(); - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"spdy/3.1", b"http/1.1"]).unwrap(); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - let stream = match Ssl::new(&ctx).unwrap().connect(stream) { + let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { Ok(stream) => stream, Err(err) => panic!("Expected success, got {:?}", err), }; @@ -579,14 +579,14 @@ fn test_connect_with_npn_successful_multiple_matching() { #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn test_connect_with_alpn_successful_single_match() { let (_s, stream) = Server::new_alpn(); - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"spdy/3.1"]).unwrap(); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - let stream = match Ssl::new(&ctx).unwrap().connect(stream) { + let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { Ok(stream) => stream, Err(err) => panic!("Expected success, got {:?}", err), }; @@ -603,14 +603,14 @@ fn test_connect_with_alpn_successful_single_match() { #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn test_connect_with_npn_successful_single_match() { let (_s, stream) = Server::new_alpn(); - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"spdy/3.1"]).unwrap(); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } - let stream = match Ssl::new(&ctx).unwrap().connect(stream) { + let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { Ok(stream) => stream, Err(err) => panic!("Expected success, got {:?}", err), }; @@ -627,14 +627,14 @@ fn test_npn_server_advertise_multiple() { let localhost = listener.local_addr().unwrap(); // We create a different context instance for the server... let listener_ctx = { - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) .is_ok()); ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM) .unwrap(); - ctx + ctx.build() }; // Have the listener wait on the connection in a different thread. thread::spawn(move || { @@ -642,7 +642,7 @@ fn test_npn_server_advertise_multiple() { Ssl::new(&listener_ctx).unwrap().accept(stream).unwrap(); }); - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"spdy/3.1"]).unwrap(); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -651,7 +651,7 @@ fn test_npn_server_advertise_multiple() { } // Now connect to the socket and make sure the protocol negotiation works... let stream = TcpStream::connect(localhost).unwrap(); - let stream = match Ssl::new(&ctx).unwrap().connect(stream) { + let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { Ok(stream) => stream, Err(err) => panic!("Expected success, got {:?}", err), }; @@ -668,14 +668,14 @@ fn test_alpn_server_advertise_multiple() { let localhost = listener.local_addr().unwrap(); // We create a different context instance for the server... let listener_ctx = { - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) .is_ok()); ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM) .unwrap(); - ctx + ctx.build() }; // Have the listener wait on the connection in a different thread. thread::spawn(move || { @@ -683,7 +683,7 @@ fn test_alpn_server_advertise_multiple() { Ssl::new(&listener_ctx).unwrap().accept(stream).unwrap(); }); - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"spdy/3.1"]).unwrap(); match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { @@ -692,7 +692,7 @@ fn test_alpn_server_advertise_multiple() { } // Now connect to the socket and make sure the protocol negotiation works... let stream = TcpStream::connect(localhost).unwrap(); - let stream = match Ssl::new(&ctx).unwrap().connect(stream) { + let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { Ok(stream) => stream, Err(err) => panic!("Expected success, got {:?}", err), }; @@ -709,14 +709,14 @@ fn test_alpn_server_select_none() { let localhost = listener.local_addr().unwrap(); // We create a different context instance for the server... let listener_ctx = { - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) .is_ok()); ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM) .unwrap(); - ctx + ctx.build() }; // Have the listener wait on the connection in a different thread. thread::spawn(move || { @@ -724,13 +724,13 @@ fn test_alpn_server_select_none() { Ssl::new(&listener_ctx).unwrap().accept(stream).unwrap(); }); - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/2"]).unwrap(); ctx.set_CA_file(&Path::new("test/root-ca.pem")).unwrap(); // Now connect to the socket and make sure the protocol negotiation works... let stream = TcpStream::connect(localhost).unwrap(); - let stream = Ssl::new(&ctx).unwrap().connect(stream).unwrap(); + let stream = Ssl::new(&ctx.build()).unwrap().connect(stream).unwrap(); // Since the protocols from the server and client don't overlap at all, no protocol is selected assert_eq!(None, stream.ssl().selected_alpn_protocol()); @@ -744,14 +744,14 @@ fn test_alpn_server_select_none() { let localhost = listener.local_addr().unwrap(); // We create a different context instance for the server... let listener_ctx = { - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) .is_ok()); ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM) .unwrap(); - ctx + ctx.build() }; // Have the listener wait on the connection in a different thread. thread::spawn(move || { @@ -759,13 +759,13 @@ fn test_alpn_server_select_none() { assert!(Ssl::new(&listener_ctx).unwrap().accept(stream).is_err()); }); - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/2"]).unwrap(); ctx.set_CA_file(&Path::new("test/root-ca.pem")).unwrap(); // Now connect to the socket and make sure the protocol negotiation works... let stream = TcpStream::connect(localhost).unwrap(); - assert!(Ssl::new(&ctx).unwrap().connect(stream).is_err()); + assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_err()); } #[cfg(test)] @@ -782,7 +782,7 @@ mod dtlsv1 { #[test] fn test_new_ctx() { - SslContext::new(SslMethod::dtls()).unwrap(); + SslContext::builder(SslMethod::dtls()).unwrap(); } } @@ -791,8 +791,8 @@ mod dtlsv1 { fn test_read_dtlsv1() { let (_s, stream) = Server::new_dtlsv1(Some("hello")); - let ctx = SslContext::new(SslMethod::dtls()).unwrap(); - let mut stream = Ssl::new(&ctx).unwrap().connect(stream).unwrap(); + let ctx = SslContext::builder(SslMethod::dtls()).unwrap(); + let mut stream = Ssl::new(&ctx.build()).unwrap().connect(stream).unwrap(); let mut buf = [0u8; 100]; assert!(stream.read(&mut buf).is_ok()); } @@ -832,7 +832,7 @@ fn handshake(res: Result, HandshakeError>) fn test_write_nonblocking() { let (_s, stream) = Server::new(); stream.set_nonblocking(true).unwrap(); - let cx = SslContext::new(SslMethod::tls()).unwrap(); + let cx = SslContext::builder(SslMethod::tls()).unwrap().build(); let mut stream = handshake(Ssl::new(&cx).unwrap().connect(stream)); let mut iterations = 0; @@ -870,7 +870,7 @@ fn test_write_nonblocking() { fn test_read_nonblocking() { let (_s, stream) = Server::new(); stream.set_nonblocking(true).unwrap(); - let cx = SslContext::new(SslMethod::tls()).unwrap(); + let cx = SslContext::builder(SslMethod::tls()).unwrap().build(); let mut stream = handshake(Ssl::new(&cx).unwrap().connect(stream)); let mut iterations = 0; @@ -944,8 +944,8 @@ fn write_panic() { let (_s, stream) = Server::new(); let stream = ExplodingStream(stream); - let ctx = SslContext::new(SslMethod::tls()).unwrap(); - let _ = Ssl::new(&ctx).unwrap().connect(stream); + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let _ = Ssl::new(&ctx.build()).unwrap().connect(stream); } #[test] @@ -972,8 +972,8 @@ fn read_panic() { let (_s, stream) = Server::new(); let stream = ExplodingStream(stream); - let ctx = SslContext::new(SslMethod::tls()).unwrap(); - let _ = Ssl::new(&ctx).unwrap().connect(stream); + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let _ = Ssl::new(&ctx.build()).unwrap().connect(stream); } #[test] @@ -1000,20 +1000,20 @@ fn flush_panic() { let (_s, stream) = Server::new(); let stream = ExplodingStream(stream); - let ctx = SslContext::new(SslMethod::tls()).unwrap(); - let mut stream = Ssl::new(&ctx).unwrap().connect(stream).ok().unwrap(); + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let mut stream = Ssl::new(&ctx.build()).unwrap().connect(stream).ok().unwrap(); let _ = stream.flush(); } #[test] fn refcount_ssl_context() { let mut ssl = { - let ctx = SslContext::new(SslMethod::tls()).unwrap(); - ssl::Ssl::new(&ctx).unwrap() + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ssl::Ssl::new(&ctx.build()).unwrap() }; { - let new_ctx_a = SslContext::new(SslMethod::tls()).unwrap(); + let new_ctx_a = SslContext::builder(SslMethod::tls()).unwrap().build(); let _new_ctx_b = ssl.set_ssl_context(&new_ctx_a); } } @@ -1021,11 +1021,11 @@ fn refcount_ssl_context() { #[test] #[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( fn default_verify_paths() { - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_default_verify_paths().unwrap(); ctx.set_verify(SSL_VERIFY_PEER); let s = TcpStream::connect("google.com:443").unwrap(); - let mut socket = Ssl::new(&ctx).unwrap().connect(s).unwrap(); + let mut socket = Ssl::new(&ctx.build()).unwrap().connect(s).unwrap(); socket.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); let mut result = vec![]; @@ -1040,7 +1040,7 @@ fn default_verify_paths() { fn add_extra_chain_cert() { let cert = include_bytes!("../../../test/cert.pem"); let cert = X509::from_pem(cert).unwrap(); - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.add_extra_chain_cert(cert).unwrap(); } @@ -1048,11 +1048,11 @@ fn add_extra_chain_cert() { #[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn valid_hostname() { - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_default_verify_paths().unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - let mut ssl = Ssl::new(&ctx).unwrap(); + let mut ssl = Ssl::new(&ctx.build()).unwrap(); ssl.param_mut().set_hostflags(X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); ssl.param_mut().set_host("google.com").unwrap(); @@ -1072,11 +1072,11 @@ fn valid_hostname() { #[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn invalid_hostname() { - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_default_verify_paths().unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - let mut ssl = Ssl::new(&ctx).unwrap(); + let mut ssl = Ssl::new(&ctx.build()).unwrap(); ssl.param_mut().set_hostflags(X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); ssl.param_mut().set_host("foobar.com").unwrap(); @@ -1091,10 +1091,10 @@ fn shutdown() { thread::spawn(move || { let stream = listener.accept().unwrap().0; - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM).unwrap(); ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM).unwrap(); - let ssl = Ssl::new(&ctx).unwrap(); + let ssl = Ssl::new(&ctx.build()).unwrap(); let mut stream = ssl.accept(stream).unwrap(); stream.write_all(b"hello").unwrap(); @@ -1104,8 +1104,8 @@ fn shutdown() { }); let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); - let ctx = SslContext::new(SslMethod::tls()).unwrap(); - let ssl = Ssl::new(&ctx).unwrap(); + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let ssl = Ssl::new(&ctx.build()).unwrap(); let mut stream = ssl.connect(stream).unwrap(); let mut buf = [0; 5]; From ebc4c56c34706bbc8cf720a9cae81767a4735663 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Wed, 26 Oct 2016 20:43:43 -0700 Subject: [PATCH 092/186] Add SslMethod::from_ptr --- openssl/src/ssl/mod.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index d6f5e160..b6f24529 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -100,6 +100,10 @@ impl SslMethod { SslMethod(compat::dtls_method()) } + pub unsafe fn from_ptr(ptr: *const ffi::SSL_METHOD) -> SslMethod { + SslMethod(ptr) + } + pub fn as_ptr(&self) -> *const ffi::SSL_METHOD { self.0 } From 4f59d576752aa1f44704b19befbf893dbd046465 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Wed, 26 Oct 2016 21:28:00 -0700 Subject: [PATCH 093/186] Move SslString to a shared location --- openssl/src/crypto.rs | 43 +++++++++++++++++++++++++++++++++++++++++ openssl/src/lib.rs | 1 + openssl/src/x509/mod.rs | 42 +++------------------------------------- 3 files changed, 47 insertions(+), 39 deletions(-) create mode 100644 openssl/src/crypto.rs diff --git a/openssl/src/crypto.rs b/openssl/src/crypto.rs new file mode 100644 index 00000000..0a121fa0 --- /dev/null +++ b/openssl/src/crypto.rs @@ -0,0 +1,43 @@ +use ffi; +use libc::{c_int, c_void}; +use std::fmt; +use std::slice; +use std::ops::Deref; +use std::str; + +pub struct CryptoString(&'static str); + +impl<'s> Drop for CryptoString { + fn drop(&mut self) { + unsafe { + CRYPTO_free!(self.0.as_ptr() as *mut c_void); + } + } +} + +impl Deref for CryptoString { + type Target = str; + + fn deref(&self) -> &str { + self.0 + } +} + +impl CryptoString { + pub unsafe fn from_raw_parts(buf: *const u8, len: usize) -> CryptoString { + let slice = slice::from_raw_parts(buf, len); + CryptoString(str::from_utf8_unchecked(slice)) + } +} + +impl fmt::Display for CryptoString { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(self.0, f) + } +} + +impl fmt::Debug for CryptoString { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(self.0, f) + } +} diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index 9ed02207..b8ab3da1 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -27,6 +27,7 @@ mod opaque; mod util; pub mod asn1; pub mod bn; +pub mod crypto; pub mod dh; pub mod dsa; pub mod error; diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index af5c722a..b92462d4 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -15,6 +15,7 @@ use {cvt, cvt_p}; use asn1::Asn1Time; use asn1::Asn1TimeRef; use bio::{MemBio, MemBioSlice}; +use crypto::CryptoString; use hash::MessageDigest; use pkey::PKey; use rand::rand_bytes; @@ -46,43 +47,6 @@ use self::extension::{ExtensionType, Extension}; #[cfg(test)] mod tests; -pub struct SslString(&'static str); - -impl<'s> Drop for SslString { - fn drop(&mut self) { - unsafe { - CRYPTO_free!(self.0.as_ptr() as *mut c_void); - } - } -} - -impl Deref for SslString { - type Target = str; - - fn deref(&self) -> &str { - self.0 - } -} - -impl SslString { - unsafe fn new(buf: *const u8, len: c_int) -> SslString { - let slice = slice::from_raw_parts(buf, len as usize); - SslString(str::from_utf8_unchecked(slice)) - } -} - -impl fmt::Display for SslString { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(self.0, f) - } -} - -impl fmt::Debug for SslString { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Debug::fmt(self.0, f) - } -} - #[derive(Copy, Clone)] #[repr(i32)] pub enum X509FileType { @@ -551,7 +515,7 @@ impl X509NameRef { self as *const _ as *mut _ } - pub fn text_by_nid(&self, nid: Nid) -> Option { + pub fn text_by_nid(&self, nid: Nid) -> Option { unsafe { let loc = ffi::X509_NAME_get_index_by_NID(self.as_ptr(), nid.as_raw(), -1); if loc == -1 { @@ -577,7 +541,7 @@ impl X509NameRef { assert!(!str_from_asn1.is_null()); - Some(SslString::new(str_from_asn1, len)) + Some(CryptoString::from_raw_parts(str_from_asn1, len as usize)) } } } From 654f0941e18376d37c9e0f97d28f44f6b16cd2b5 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Wed, 26 Oct 2016 21:42:09 -0700 Subject: [PATCH 094/186] Don't double-allocate strings --- openssl/src/bn.rs | 23 +++++++++-------------- openssl/src/crypto.rs | 11 ++++++++--- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs index 700367bd..fb0c286c 100644 --- a/openssl/src/bn.rs +++ b/openssl/src/bn.rs @@ -1,11 +1,12 @@ use ffi; -use libc::{c_int, c_void}; +use libc::c_int; use std::cmp::Ordering; -use std::ffi::{CStr, CString}; +use std::ffi::CString; use std::{fmt, ptr}; use std::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub, Deref, DerefMut}; use {cvt, cvt_p, cvt_n}; +use crypto::CryptoString; use error::ErrorStack; use opaque::Opaque; @@ -473,15 +474,12 @@ impl BigNumRef { /// # use openssl::bn::BigNum; /// let s = -BigNum::from_u32(12345).unwrap(); /// - /// assert_eq!(s.to_dec_str().unwrap(), "-12345"); + /// assert_eq!(&*s.to_dec_str().unwrap(), "-12345"); /// ``` - pub fn to_dec_str(&self) -> Result { + pub fn to_dec_str(&self) -> Result { unsafe { let buf = try!(cvt_p(ffi::BN_bn2dec(self.as_ptr()))); - let str = String::from_utf8(CStr::from_ptr(buf as *const _).to_bytes().to_vec()) - .unwrap(); - CRYPTO_free!(buf as *mut c_void); - Ok(str) + Ok(CryptoString::from_null_terminated(buf)) } } @@ -491,15 +489,12 @@ impl BigNumRef { /// # use openssl::bn::BigNum; /// let s = -BigNum::from_u32(0x99ff).unwrap(); /// - /// assert_eq!(s.to_hex_str().unwrap(), "-99FF"); + /// assert_eq!(&*s.to_hex_str().unwrap(), "-99FF"); /// ``` - pub fn to_hex_str(&self) -> Result { + pub fn to_hex_str(&self) -> Result { unsafe { let buf = try!(cvt_p(ffi::BN_bn2hex(self.as_ptr()))); - let str = String::from_utf8(CStr::from_ptr(buf as *const _).to_bytes().to_vec()) - .unwrap(); - CRYPTO_free!(buf as *mut c_void); - Ok(str) + Ok(CryptoString::from_null_terminated(buf)) } } } diff --git a/openssl/src/crypto.rs b/openssl/src/crypto.rs index 0a121fa0..26f66d0e 100644 --- a/openssl/src/crypto.rs +++ b/openssl/src/crypto.rs @@ -1,6 +1,6 @@ -use ffi; -use libc::{c_int, c_void}; +use libc::{c_char, c_void}; use std::fmt; +use std::ffi::CStr; use std::slice; use std::ops::Deref; use std::str; @@ -24,10 +24,15 @@ impl Deref for CryptoString { } impl CryptoString { - pub unsafe fn from_raw_parts(buf: *const u8, len: usize) -> CryptoString { + pub unsafe fn from_raw_parts(buf: *mut u8, len: usize) -> CryptoString { let slice = slice::from_raw_parts(buf, len); CryptoString(str::from_utf8_unchecked(slice)) } + + pub unsafe fn from_null_terminated(buf: *mut c_char) -> CryptoString { + let slice = CStr::from_ptr(buf).to_bytes(); + CryptoString(str::from_utf8_unchecked(slice)) + } } impl fmt::Display for CryptoString { From 548c8b5fbaca291237e22b8959c05769a884b08c Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Wed, 26 Oct 2016 21:55:13 -0700 Subject: [PATCH 095/186] Remove macros module --- openssl/src/crypto.rs | 15 +++++++++++++-- openssl/src/lib.rs | 2 -- openssl/src/macros.rs | 15 --------------- 3 files changed, 13 insertions(+), 19 deletions(-) delete mode 100644 openssl/src/macros.rs diff --git a/openssl/src/crypto.rs b/openssl/src/crypto.rs index 26f66d0e..3a031368 100644 --- a/openssl/src/crypto.rs +++ b/openssl/src/crypto.rs @@ -1,4 +1,4 @@ -use libc::{c_char, c_void}; +use libc::{c_char, c_int, c_void}; use std::fmt; use std::ffi::CStr; use std::slice; @@ -10,7 +10,9 @@ pub struct CryptoString(&'static str); impl<'s> Drop for CryptoString { fn drop(&mut self) { unsafe { - CRYPTO_free!(self.0.as_ptr() as *mut c_void); + CRYPTO_free(self.0.as_ptr() as *mut c_void, + concat!(file!(), "\0").as_ptr() as *const c_char, + line!() as c_int); } } } @@ -46,3 +48,12 @@ impl fmt::Debug for CryptoString { fmt::Debug::fmt(self.0, f) } } + +#[cfg(not(ossl110))] +#[allow(non_snake_case)] +unsafe fn CRYPTO_free(buf: *mut c_void, _: *const c_char, _: c_int) { + ::ffi::CRYPTO_free(buf); +} + +#[cfg(ossl110)] +use ffi::CRYPTO_free; diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index b8ab3da1..b191ec5b 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -20,8 +20,6 @@ use libc::c_int; use error::ErrorStack; -mod macros; - mod bio; mod opaque; mod util; diff --git a/openssl/src/macros.rs b/openssl/src/macros.rs deleted file mode 100644 index 85175445..00000000 --- a/openssl/src/macros.rs +++ /dev/null @@ -1,15 +0,0 @@ -#![macro_use] - -#[cfg(ossl10x)] -macro_rules! CRYPTO_free { - ($e:expr) => (::ffi::CRYPTO_free($e)) -} - -#[cfg(ossl110)] -macro_rules! CRYPTO_free { - ($e:expr) => ( - ::ffi::CRYPTO_free($e, - concat!(file!(), "\0").as_ptr() as *const _, - line!() as i32) - ) -} From 2234899e596b9e85244207f3954843e1c31b7ca0 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Wed, 26 Oct 2016 22:00:33 -0700 Subject: [PATCH 096/186] Fix drop signature --- openssl/src/crypto.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openssl/src/crypto.rs b/openssl/src/crypto.rs index 3a031368..ce83cbae 100644 --- a/openssl/src/crypto.rs +++ b/openssl/src/crypto.rs @@ -7,7 +7,7 @@ use std::str; pub struct CryptoString(&'static str); -impl<'s> Drop for CryptoString { +impl Drop for CryptoString { fn drop(&mut self) { unsafe { CRYPTO_free(self.0.as_ptr() as *mut c_void, From 63b1ec1a12847c3361a11e33f4836b16c4b87cde Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Wed, 26 Oct 2016 22:13:10 -0700 Subject: [PATCH 097/186] Stop returning an Option from cipher description --- openssl/src/ssl/mod.rs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index b6f24529..f2224b1e 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -784,17 +784,12 @@ impl SslCipherRef { } /// Returns a textual description of the cipher used - pub fn description(&self) -> Option { + pub fn description(&self) -> String { unsafe { // SSL_CIPHER_description requires a buffer of at least 128 bytes. let mut buf = [0; 128]; - let desc_ptr = ffi::SSL_CIPHER_description(self.as_ptr(), buf.as_mut_ptr(), 128); - - if !desc_ptr.is_null() { - String::from_utf8(CStr::from_ptr(desc_ptr as *const _).to_bytes().to_vec()).ok() - } else { - None - } + ffi::SSL_CIPHER_description(self.as_ptr(), buf.as_mut_ptr(), 128); + String::from_utf8(CStr::from_ptr(buf.as_ptr() as *const _).to_bytes().to_vec()).unwrap() } } } From 8e129af25638435f0ecfd5750d981c072550ee04 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Wed, 26 Oct 2016 22:15:41 -0700 Subject: [PATCH 098/186] Fix description --- openssl/src/ssl/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index f2224b1e..a1c39248 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -788,8 +788,8 @@ impl SslCipherRef { unsafe { // SSL_CIPHER_description requires a buffer of at least 128 bytes. let mut buf = [0; 128]; - ffi::SSL_CIPHER_description(self.as_ptr(), buf.as_mut_ptr(), 128); - String::from_utf8(CStr::from_ptr(buf.as_ptr() as *const _).to_bytes().to_vec()).unwrap() + let ptr = ffi::SSL_CIPHER_description(self.as_ptr(), buf.as_mut_ptr(), 128); + String::from_utf8(CStr::from_ptr(ptr as *const _).to_bytes().to_vec()).unwrap() } } } From 781417d50f72f832159e35c86dea76df5978434c Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 27 Oct 2016 19:12:55 -0700 Subject: [PATCH 099/186] Add a macro definition --- openssl-sys/src/ossl10x.rs | 6 ++++++ openssl/src/ssl/mod.rs | 6 +----- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/openssl-sys/src/ossl10x.rs b/openssl-sys/src/ossl10x.rs index 595b673b..241dc782 100644 --- a/openssl-sys/src/ossl10x.rs +++ b/openssl-sys/src/ossl10x.rs @@ -527,6 +527,12 @@ fn set_id_callback() { #[cfg(not(unix))] fn set_id_callback() {} +// macros +#[cfg(ossl102)] +pub unsafe fn SSL_CTX_set_ecdh_auto(ctx: *mut SSL_CTX, onoff: c_int) -> c_int { + ::SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff as c_long, ::std::ptr::null_mut()) as c_int +} + extern { pub fn BIO_new(type_: *mut BIO_METHOD) -> *mut BIO; pub fn BIO_s_file() -> *mut BIO_METHOD; diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index a1c39248..071e3137 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -551,11 +551,7 @@ impl SslContextBuilder { #[cfg(all(feature = "v102", ossl102))] pub fn set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::SSL_CTX_ctrl(self.as_ptr(), - ffi::SSL_CTRL_SET_ECDH_AUTO, - onoff as c_long, - ptr::null_mut()) as c_int) - .map(|_| ()) + cvt(ffi::SSL_CTX_set_ecdh_auto(self.as_ptr(), onoff as c_int)).map(|_| ()) } } From 8604668a1831551359c7b9512efb151002acaf48 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 27 Oct 2016 19:56:52 -0700 Subject: [PATCH 100/186] Make padding types consts --- openssl/src/rsa.rs | 28 +++++++++------------------- 1 file changed, 9 insertions(+), 19 deletions(-) diff --git a/openssl/src/rsa.rs b/openssl/src/rsa.rs index 550ce6e4..e63e567d 100644 --- a/openssl/src/rsa.rs +++ b/openssl/src/rsa.rs @@ -14,19 +14,9 @@ use util::{CallbackState, invoke_passwd_cb}; #[derive(Copy, Clone)] pub struct Padding(c_int); -impl Padding { - pub fn none() -> Padding { - Padding(ffi::RSA_NO_PADDING) - } - - pub fn pkcs1() -> Padding { - Padding(ffi::RSA_PKCS1_PADDING) - } - - pub fn pkcs1_oaep() -> Padding { - Padding(ffi::RSA_PKCS1_OAEP_PADDING) - } -} +pub const NO_PADDING: Padding = Padding(ffi::RSA_NO_PADDING); +pub const PKCS1_PADDING: Padding = Padding(ffi::RSA_PKCS1_PADDING); +pub const PKCS1_OAEP_PADDING: Padding = Padding(ffi::RSA_PKCS1_OAEP_PADDING); pub struct Rsa(*mut ffi::RSA); @@ -443,13 +433,13 @@ mod test { let mut result = vec![0; public_key.size()]; let original_data = b"This is test"; - let len = public_key.public_encrypt(original_data, &mut result, Padding::pkcs1()).unwrap(); + let len = public_key.public_encrypt(original_data, &mut result, PKCS1_PADDING).unwrap(); assert_eq!(len, 256); let pkey = include_bytes!("../test/rsa.pem"); let private_key = Rsa::private_key_from_pem(pkey).unwrap(); let mut dec_result = vec![0; private_key.size()]; - let len = private_key.private_decrypt(&result, &mut dec_result, Padding::pkcs1()).unwrap(); + let len = private_key.private_decrypt(&result, &mut dec_result, PKCS1_PADDING).unwrap(); assert_eq!(&dec_result[..len], original_data); } @@ -463,9 +453,9 @@ mod test { let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; let mut emesg = vec![0; k0.size()]; - k0.private_encrypt(&msg, &mut emesg, Padding::pkcs1()).unwrap(); + k0.private_encrypt(&msg, &mut emesg, PKCS1_PADDING).unwrap(); let mut dmesg = vec![0; k1.size()]; - let len = k1.public_decrypt(&emesg, &mut dmesg, Padding::pkcs1()).unwrap(); + let len = k1.public_decrypt(&emesg, &mut dmesg, PKCS1_PADDING).unwrap(); assert_eq!(msg, &dmesg[..len]); } @@ -478,9 +468,9 @@ mod test { let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; let mut emesg = vec![0; k0.size()]; - k0.public_encrypt(&msg, &mut emesg, Padding::pkcs1()).unwrap(); + k0.public_encrypt(&msg, &mut emesg, PKCS1_PADDING).unwrap(); let mut dmesg = vec![0; k1.size()]; - let len = k1.private_decrypt(&emesg, &mut dmesg, Padding::pkcs1()).unwrap(); + let len = k1.private_decrypt(&emesg, &mut dmesg, PKCS1_PADDING).unwrap(); assert_eq!(msg, &dmesg[..len]); } From dafb46fc51555407ed0501f8ad92917e1ad9fb76 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 27 Oct 2016 20:26:18 -0700 Subject: [PATCH 101/186] Camel case DH --- openssl/src/dh.rs | 40 ++++++++++++++++++++-------------------- openssl/src/ssl/mod.rs | 4 ++-- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/openssl/src/dh.rs b/openssl/src/dh.rs index 7111a068..755e3e6b 100644 --- a/openssl/src/dh.rs +++ b/openssl/src/dh.rs @@ -7,12 +7,12 @@ use {cvt, cvt_p}; use bn::BigNum; use std::mem; -pub struct DH(*mut ffi::DH); +pub struct Dh(*mut ffi::DH); -impl DH { - pub fn from_params(p: BigNum, g: BigNum, q: BigNum) -> Result { +impl Dh { + pub fn from_params(p: BigNum, g: BigNum, q: BigNum) -> Result { unsafe { - let dh = DH(try!(cvt_p(ffi::DH_new()))); + let dh = Dh(try!(cvt_p(ffi::DH_new()))); try!(cvt(compat::DH_set0_pqg(dh.0, p.as_ptr(), q.as_ptr(), @@ -22,47 +22,47 @@ impl DH { } } - pub fn from_pem(buf: &[u8]) -> Result { + pub fn from_pem(buf: &[u8]) -> Result { let mem_bio = try!(MemBioSlice::new(buf)); unsafe { cvt_p(ffi::PEM_read_bio_DHparams(mem_bio.as_ptr(), ptr::null_mut(), None, ptr::null_mut())) - .map(DH) + .map(Dh) } } /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - pub fn get_1024_160() -> Result { + pub fn get_1024_160() -> Result { unsafe { - cvt_p(ffi::DH_get_1024_160()).map(DH) + cvt_p(ffi::DH_get_1024_160()).map(Dh) } } /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - pub fn get_2048_224() -> Result { + pub fn get_2048_224() -> Result { unsafe { - cvt_p(ffi::DH_get_2048_224()).map(DH) + cvt_p(ffi::DH_get_2048_224()).map(Dh) } } /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - pub fn get_2048_256() -> Result { + pub fn get_2048_256() -> Result { unsafe { - cvt_p(ffi::DH_get_2048_256()).map(DH) + cvt_p(ffi::DH_get_2048_256()).map(Dh) } } - pub unsafe fn as_ptr(&self) -> *mut ffi::DH { + pub fn as_ptr(&self) -> *mut ffi::DH { self.0 } } -impl Drop for DH { +impl Drop for Dh { fn drop(&mut self) { unsafe { ffi::DH_free(self.as_ptr()) @@ -94,7 +94,7 @@ mod compat { #[cfg(test)] mod tests { - use super::DH; + use dh::Dh; use bn::BigNum; use ssl::{SslMethod, SslContext}; @@ -102,11 +102,11 @@ mod tests { #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn test_dh_rfc5114() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - let dh1 = DH::get_1024_160().unwrap(); + let dh1 = Dh::get_1024_160().unwrap(); ctx.set_tmp_dh(&dh1).unwrap(); - let dh2 = DH::get_2048_224().unwrap(); + let dh2 = Dh::get_2048_224().unwrap(); ctx.set_tmp_dh(&dh2).unwrap(); - let dh3 = DH::get_2048_256().unwrap(); + let dh3 = Dh::get_2048_256().unwrap(); ctx.set_tmp_dh(&dh3).unwrap(); } @@ -136,7 +136,7 @@ mod tests { let q = BigNum::from_hex_str("8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F\ 5FBD3") .unwrap(); - let dh = DH::from_params(p, g, q).unwrap(); + let dh = Dh::from_params(p, g, q).unwrap(); ctx.set_tmp_dh(&dh).unwrap(); } @@ -144,7 +144,7 @@ mod tests { fn test_dh_from_pem() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); let params = include_bytes!("../test/dhparams.pem"); - let dh = DH::from_pem(params).ok().expect("Failed to load PEM"); + let dh = Dh::from_pem(params).ok().expect("Failed to load PEM"); ctx.set_tmp_dh(&dh).unwrap(); } } diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 071e3137..cc9069dc 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -20,7 +20,7 @@ use std::marker::PhantomData; use ffi; use {init, cvt, cvt_p}; -use dh::DH; +use dh::Dh; use x509::{X509StoreContextRef, X509FileType, X509, X509Ref, X509VerifyError}; #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] use x509::verify::X509VerifyParamRef; @@ -425,7 +425,7 @@ impl SslContextBuilder { } } - pub fn set_tmp_dh(&mut self, dh: &DH) -> Result<(), ErrorStack> { + pub fn set_tmp_dh(&mut self, dh: &Dh) -> Result<(), ErrorStack> { unsafe { cvt(ffi::SSL_CTX_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as c_int).map(|_| ()) } From c0cf4ab1c230421084939626d6c815f162564416 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 27 Oct 2016 20:33:38 -0700 Subject: [PATCH 102/186] Remove private field in ParsedPkcs12 The function definition is fixed - nothing else is going to be coming out of a PKCS#12 archive --- openssl/src/pkcs12.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/openssl/src/pkcs12.rs b/openssl/src/pkcs12.rs index f143ec49..d5d4750a 100644 --- a/openssl/src/pkcs12.rs +++ b/openssl/src/pkcs12.rs @@ -58,7 +58,6 @@ impl Pkcs12 { pkey: pkey, cert: cert, chain: chain_out, - _p: (), }) } } @@ -68,7 +67,6 @@ pub struct ParsedPkcs12 { pub pkey: PKey, pub cert: X509, pub chain: Vec, - _p: (), } #[cfg(ossl110)] From 1a288da86ce1ca94b5a0b3eac8750e5ffd03e8e7 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 28 Oct 2016 22:14:44 -0700 Subject: [PATCH 103/186] Make verification unconditionally exposed internally --- openssl/src/lib.rs | 2 ++ openssl/src/{x509 => }/verify.rs | 0 openssl/src/x509/mod.rs | 8 ++++---- 3 files changed, 6 insertions(+), 4 deletions(-) rename openssl/src/{x509 => }/verify.rs (100%) diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index b191ec5b..acdc2ea8 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -42,6 +42,8 @@ pub mod ssl; pub mod symm; pub mod version; pub mod x509; +#[cfg(any(ossl102, ossl110))] +mod verify; pub fn cvt_p(r: *mut T) -> Result<*mut T, ErrorStack> { if r.is_null() { diff --git a/openssl/src/x509/verify.rs b/openssl/src/verify.rs similarity index 100% rename from openssl/src/x509/verify.rs rename to openssl/src/verify.rs diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index b92462d4..cc6b73bb 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -37,12 +37,12 @@ use ffi::{ ASN1_STRING_get0_data as ASN1_STRING_data, }; -pub mod extension; - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -pub mod verify; +pub use verify; -use self::extension::{ExtensionType, Extension}; +use x509::extension::{ExtensionType, Extension}; + +pub mod extension; #[cfg(test)] mod tests; From 4c7a5a418ee6a71f26fb6cc720a36b5bca6f3376 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 29 Oct 2016 14:02:26 -0700 Subject: [PATCH 104/186] Implement client and server connectors --- openssl/src/ssl/connector.rs | 329 +++++++++++++++++++++++++++++++++++ openssl/src/ssl/mod.rs | 23 ++- openssl/src/ssl/tests/mod.rs | 70 +++++++- openssl/src/x509/mod.rs | 29 ++- 4 files changed, 437 insertions(+), 14 deletions(-) create mode 100644 openssl/src/ssl/connector.rs diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs new file mode 100644 index 00000000..aed01f8c --- /dev/null +++ b/openssl/src/ssl/connector.rs @@ -0,0 +1,329 @@ +use std::io::{Read, Write}; + +use dh::Dh; +use error::ErrorStack; +use ssl::{self, SslMethod, SslContextBuilder, SslContext, Ssl, SSL_VERIFY_PEER, SslStream, + HandshakeError}; +use pkey::PKey; +use x509::X509Ref; + +// apps/dh2048.pem +const DHPARAM_PEM: &'static str = r#" +-----BEGIN DH PARAMETERS----- +MIIBCAKCAQEA///////////JD9qiIWjCNMTGYouA3BzRKQJOCIpnzHQCC76mOxOb +IlFKCHmONATd75UZs806QxswKwpt8l8UN0/hNW1tUcJF5IW1dmJefsb0TELppjft +awv/XLb0Brft7jhr+1qJn6WunyQRfEsf5kkoZlHs5Fs9wgB8uKFjvwWY2kg2HFXT +mmkWP6j9JM9fg2VdI9yjrZYcYvNWIIVSu57VKQdwlpZtZww1Tkq8mATxdGwIyhgh +fDKQXkYuNs474553LBgOhgObJ4Oi7Aeij7XFXfBvTFLJ3ivL9pVYFxg5lUl86pVq +5RXSJhiY+gUQFXKOWoqsqmj//////////wIBAg== +-----END DH PARAMETERS----- + +These are the 2048-bit DH parameters from "More Modular Exponential +(MODP) Diffie-Hellman groups for Internet Key Exchange (IKE)": +https://tools.ietf.org/html/rfc3526 + +See https://tools.ietf.org/html/rfc2412 for how they were generated."#; + +fn ctx(method: SslMethod) -> Result { + let mut ctx = try!(SslContextBuilder::new(method)); + + // options to enable and cipher list lifted from libcurl + let mut opts = ssl::SSL_OP_ALL; + opts |= ssl::SSL_OP_NO_TICKET; + opts |= ssl::SSL_OP_NO_COMPRESSION; + opts &= !ssl::SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG; + opts &= !ssl::SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; + opts |= ssl::SSL_OP_NO_SSLV2; + opts |= ssl::SSL_OP_NO_SSLV3; + ctx.set_options(opts); + + Ok(ctx) +} + +pub struct ClientConnectorBuilder(SslContextBuilder); + +impl ClientConnectorBuilder { + pub fn tls() -> Result { + ClientConnectorBuilder::new(SslMethod::tls()) + } + + fn new(method: SslMethod) -> Result { + let mut ctx = try!(ctx(method)); + try!(ctx.set_default_verify_paths()); + try!(ctx.set_cipher_list("ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH")); + + Ok(ClientConnectorBuilder(ctx)) + } + + pub fn context(&self) -> &SslContextBuilder { + &self.0 + } + + pub fn context_mut(&mut self) -> &mut SslContextBuilder { + &mut self.0 + } + + pub fn build(self) -> ClientConnector { + ClientConnector(self.0.build()) + } +} + +pub struct ClientConnector(SslContext); + +impl ClientConnector { + pub fn connect(&self, domain: &str, stream: S) -> Result, HandshakeError> + where S: Read + Write + { + let mut ssl = try!(Ssl::new(&self.0)); + try!(ssl.set_hostname(domain)); + try!(setup_verify(&mut ssl, domain)); + + ssl.connect(stream) + } +} + +pub struct ServerConnectorBuilder(SslContextBuilder); + +impl ServerConnectorBuilder { + pub fn tls(private_key: &PKey, + certificate: &X509Ref, + chain: I) + -> Result + where I: IntoIterator, + T: AsRef + { + ServerConnectorBuilder::new(SslMethod::tls(), private_key, certificate, chain) + } + + fn new(method: SslMethod, + private_key: &PKey, + certificate: &X509Ref, + chain: I) + -> Result + where I: IntoIterator, + T: AsRef + { + let mut ctx = try!(ctx(method)); + ctx.set_options(ssl::SSL_OP_SINGLE_DH_USE | ssl::SSL_OP_CIPHER_SERVER_PREFERENCE); + let dh = try!(Dh::from_pem(DHPARAM_PEM.as_bytes())); + try!(ctx.set_tmp_dh(&dh)); + try!(ctx.set_cipher_list( + "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:\ + ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:\ + ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:\ + DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:\ + ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:\ + ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:\ + ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:\ + DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:\ + EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:\ + AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS")); + try!(ctx.set_private_key(private_key)); + try!(ctx.set_certificate(certificate)); + try!(ctx.check_private_key()); + for cert in chain { + try!(ctx.add_extra_chain_cert(cert.as_ref().to_owned())); + } + Ok(ServerConnectorBuilder(ctx)) + } + + pub fn context(&self) -> &SslContextBuilder { + &self.0 + } + + pub fn context_mut(&mut self) -> &mut SslContextBuilder { + &mut self.0 + } + + pub fn build(self) -> ServerConnector { + ServerConnector(self.0.build()) + } +} + +pub struct ServerConnector(SslContext); + +impl ServerConnector { + pub fn connect(&self, stream: S) -> Result, HandshakeError> + where S: Read + Write + { + let ssl = try!(Ssl::new(&self.0)); + ssl.accept(stream) + } +} + +#[cfg(any(ossl102, ossl110))] +fn setup_verify(ssl: &mut Ssl, domain: &str) -> Result<(), ErrorStack> { + ssl.set_verify(SSL_VERIFY_PEER); + let param = ssl._param_mut(); + param.set_hostflags(::verify::X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); + param.set_host(domain) +} + +#[cfg(not(any(ossl102, ossl110)))] +fn setup_verify(ssl: &mut Ssl, domain: &str) -> Result<(), ErrorStack> { + let domain = domain.to_owned(); + ssl.set_verify_callback(SSL_VERIFY_PEER, move |p, x| verify::verify_callback(&domain, p, x)); + Ok(()) +} + +#[cfg(not(any(ossl102, ossl110)))] +mod verify { + use std::net::IpAddr; + + use nid; + use x509::{X509StoreContextRef, X509Ref, GeneralNames, X509NameRef}; + + pub fn verify_callback(domain: &str, + preverify_ok: bool, + x509_ctx: &X509StoreContextRef) + -> bool { + if !preverify_ok || x509_ctx.error_depth() != 0 { + return preverify_ok; + } + + match x509_ctx.current_cert() { + Some(x509) => verify_hostname(domain, &x509), + None => true, + } + } + + fn verify_hostname(domain: &str, cert: &X509Ref) -> bool { + match cert.subject_alt_names() { + Some(names) => verify_subject_alt_names(domain, &names), + None => verify_subject_name(domain, &cert.subject_name()), + } + } + + fn verify_subject_alt_names(domain: &str, names: &GeneralNames) -> bool { + let ip = domain.parse(); + + for name in names { + match ip { + Ok(ip) => { + if let Some(actual) = name.ipaddress() { + if matches_ip(&ip, actual) { + return true; + } + } + } + Err(_) => { + if let Some(pattern) = name.dnsname() { + if matches_dns(pattern, domain, false) { + return true; + } + } + } + } + } + + false + } + + fn verify_subject_name(domain: &str, subject_name: &X509NameRef) -> bool { + if let Some(pattern) = subject_name.text_by_nid(nid::COMMONNAME) { + // Unlike with SANs, IP addresses in the subject name don't have a + // different encoding. We need to pass this down to matches_dns to + // disallow wildcard matches with bogus patterns like *.0.0.1 + let is_ip = domain.parse::().is_ok(); + + if matches_dns(&pattern, domain, is_ip) { + return true; + } + } + + false + } + + fn matches_dns(mut pattern: &str, mut hostname: &str, is_ip: bool) -> bool { + // first strip trailing . off of pattern and hostname to normalize + if pattern.ends_with('.') { + pattern = &pattern[..pattern.len() - 1]; + } + if hostname.ends_with('.') { + hostname = &hostname[..hostname.len() - 1]; + } + + matches_wildcard(pattern, hostname, is_ip).unwrap_or_else(|| pattern == hostname) + } + + fn matches_wildcard(pattern: &str, hostname: &str, is_ip: bool) -> Option { + // IP addresses and internationalized domains can't involved in wildcards + if is_ip || pattern.starts_with("xn--") { + return None; + } + + let wildcard_location = match pattern.find('*') { + Some(l) => l, + None => return None, + }; + + let mut dot_idxs = pattern.match_indices('.').map(|(l, _)| l); + let wildcard_end = match dot_idxs.next() { + Some(l) => l, + None => return None, + }; + + // Never match wildcards if the pattern has less than 2 '.'s (no *.com) + // + // This is a bit dubious, as it doesn't disallow other TLDs like *.co.uk. + // Chrome has a black- and white-list for this, but Firefox (via NSS) does + // the same thing we do here. + // + // The Public Suffix (https://www.publicsuffix.org/) list could + // potentically be used here, but it's both huge and updated frequently + // enough that management would be a PITA. + if dot_idxs.next().is_none() { + return None; + } + + // Wildcards can only be in the first component + if wildcard_location > wildcard_end { + return None; + } + + let hostname_label_end = match hostname.find('.') { + Some(l) => l, + None => return None, + }; + + // check that the non-wildcard parts are identical + if pattern[wildcard_end..] != hostname[hostname_label_end..] { + return Some(false); + } + + let wildcard_prefix = &pattern[..wildcard_location]; + let wildcard_suffix = &pattern[wildcard_location + 1..wildcard_end]; + + let hostname_label = &hostname[..hostname_label_end]; + + // check the prefix of the first label + if !hostname_label.starts_with(wildcard_prefix) { + return Some(false); + } + + // and the suffix + if !hostname_label[wildcard_prefix.len()..].ends_with(wildcard_suffix) { + return Some(false); + } + + Some(true) + } + + fn matches_ip(expected: &IpAddr, actual: &[u8]) -> bool { + match (expected, actual.len()) { + (&IpAddr::V4(ref addr), 4) => actual == addr.octets(), + (&IpAddr::V6(ref addr), 16) => { + let segments = [((actual[0] as u16) << 8) | actual[1] as u16, + ((actual[2] as u16) << 8) | actual[3] as u16, + ((actual[4] as u16) << 8) | actual[5] as u16, + ((actual[6] as u16) << 8) | actual[7] as u16, + ((actual[8] as u16) << 8) | actual[9] as u16, + ((actual[10] as u16) << 8) | actual[11] as u16, + ((actual[12] as u16) << 8) | actual[13] as u16, + ((actual[14] as u16) << 8) | actual[15] as u16]; + segments == addr.segments() + } + _ => false, + } + } +} diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index cc9069dc..19b21d9d 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -22,19 +22,22 @@ use ffi; use {init, cvt, cvt_p}; use dh::Dh; use x509::{X509StoreContextRef, X509FileType, X509, X509Ref, X509VerifyError}; -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -use x509::verify::X509VerifyParamRef; +#[cfg(any(ossl102, ossl110))] +use verify::X509VerifyParamRef; use pkey::PKey; use error::ErrorStack; use opaque::Opaque; pub mod error; +mod connector; mod bio; #[cfg(test)] mod tests; use self::bio::BioMethod; +pub use ssl::connector::{ClientConnectorBuilder, ClientConnector, ServerConnectorBuilder, + ServerConnector}; #[doc(inline)] pub use ssl::error::Error; @@ -1030,6 +1033,11 @@ impl SslRef { /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or 1.1.0. #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] pub fn param_mut(&mut self) -> &mut X509VerifyParamRef { + self._param_mut() + } + + #[cfg(any(ossl102, ossl110))] + fn _param_mut(&mut self) -> &mut X509VerifyParamRef { unsafe { X509VerifyParamRef::from_ptr_mut(ffi::SSL_get0_param(self.as_ptr())) } @@ -1153,6 +1161,8 @@ impl Ssl { /// An error or intermediate state after a TLS handshake attempt. #[derive(Debug)] pub enum HandshakeError { + /// Setup failed. + SetupFailure(ErrorStack), /// The handshake failed. Failure(MidHandshakeSslStream), /// The handshake was interrupted midway through. @@ -1162,6 +1172,7 @@ pub enum HandshakeError { impl stderror::Error for HandshakeError { fn description(&self) -> &str { match *self { + HandshakeError::SetupFailure(_) => "stream setup failed", HandshakeError::Failure(_) => "the handshake failed", HandshakeError::Interrupted(_) => "the handshake was interrupted", } @@ -1169,6 +1180,7 @@ impl stderror::Error for HandshakeError { fn cause(&self) -> Option<&stderror::Error> { match *self { + HandshakeError::SetupFailure(ref e) => Some(e), HandshakeError::Failure(ref s) | HandshakeError::Interrupted(ref s) => Some(s.error()), } } @@ -1178,6 +1190,7 @@ impl fmt::Display for HandshakeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(f.write_str(stderror::Error::description(self))); match *self { + HandshakeError::SetupFailure(ref e) => try!(write!(f, ": {}", e)), HandshakeError::Failure(ref s) | HandshakeError::Interrupted(ref s) => { try!(write!(f, ": {}", s.error())); if let Some(err) = s.ssl().verify_result() { @@ -1189,6 +1202,12 @@ impl fmt::Display for HandshakeError { } } +impl From for HandshakeError { + fn from(e: ErrorStack) -> HandshakeError { + HandshakeError::SetupFailure(e) + } +} + /// An SSL stream midway through the handshake process. #[derive(Debug)] pub struct MidHandshakeSslStream { diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index ca4af6f7..f98f9928 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -18,8 +18,8 @@ use hash::MessageDigest; use ssl; use ssl::SSL_VERIFY_PEER; use ssl::{SslMethod, HandshakeError}; -use ssl::error::Error; -use ssl::{SslContext, SslStream, Ssl, ShutdownResult}; +use ssl::{SslContext, SslStream, Ssl, ShutdownResult, ClientConnectorBuilder, + ServerConnectorBuilder, Error}; use x509::X509StoreContextRef; use x509::X509FileType; use x509::X509; @@ -31,6 +31,9 @@ use std::net::UdpSocket; mod select; +static CERT: &'static [u8] = include_bytes!("../../../test/cert.pem"); +static KEY: &'static [u8] = include_bytes!("../../../test/key.pem"); + fn next_addr() -> SocketAddr { use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; static PORT: AtomicUsize = ATOMIC_USIZE_INIT; @@ -46,10 +49,6 @@ struct Server { impl Server { fn spawn(args: &[&str], input: Option>) -> (Server, SocketAddr) { - static CERT: &'static [u8] = include_bytes!("../../../test/cert.pem"); - static KEY: &'static [u8] = include_bytes!("../../../test/key.pem"); - - let td = TempDir::new("openssl").unwrap(); let cert = td.path().join("cert.pem"); let key = td.path().join("key.pem"); @@ -1047,7 +1046,7 @@ fn add_extra_chain_cert() { #[test] #[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -fn valid_hostname() { +fn verify_valid_hostname() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_default_verify_paths().unwrap(); ctx.set_verify(SSL_VERIFY_PEER); @@ -1071,7 +1070,7 @@ fn valid_hostname() { #[test] #[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -fn invalid_hostname() { +fn verify_invalid_hostname() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_default_verify_paths().unwrap(); ctx.set_verify(SSL_VERIFY_PEER); @@ -1084,6 +1083,61 @@ fn invalid_hostname() { assert!(ssl.connect(s).is_err()); } +#[test] +#[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( +fn connector_valid_hostname() { + let connector = ClientConnectorBuilder::tls().unwrap().build(); + + let s = TcpStream::connect("google.com:443").unwrap(); + let mut socket = connector.connect("google.com", s).unwrap(); + + socket.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); + let mut result = vec![]; + socket.read_to_end(&mut result).unwrap(); + + println!("{}", String::from_utf8_lossy(&result)); + assert!(result.starts_with(b"HTTP/1.0")); + assert!(result.ends_with(b"\r\n") || result.ends_with(b"")); +} + +#[test] +#[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( +fn connector_invalid_hostname() { + let connector = ClientConnectorBuilder::tls().unwrap().build(); + + let s = TcpStream::connect("google.com:443").unwrap(); + assert!(connector.connect("foobar.com", s).is_err()); +} + +#[test] +fn connector_client_server() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + + let t = thread::spawn(move || { + let key = PKey::private_key_from_pem(KEY).unwrap(); + let cert = X509::from_pem(CERT).unwrap(); + let connector = ServerConnectorBuilder::tls(&key, &cert, None::).unwrap().build(); + let stream = listener.accept().unwrap().0; + let mut stream = connector.connect(stream).unwrap(); + + stream.write_all(b"hello").unwrap(); + }); + + let mut connector = ClientConnectorBuilder::tls().unwrap(); + connector.context_mut().set_CA_file("test/root-ca.pem").unwrap(); + let connector = connector.build(); + + let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut stream = connector.connect("foobar.com", stream).unwrap(); + + let mut buf = [0; 5]; + stream.read_exact(&mut buf).unwrap(); + assert_eq!(b"hello", &buf); + + t.join().unwrap(); +} + #[test] fn shutdown() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index cc6b73bb..9fd6812a 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -1,4 +1,5 @@ use libc::{c_char, c_int, c_long, c_ulong, c_void}; +use std::borrow::Borrow; use std::cmp; use std::collections::HashMap; use std::error::Error; @@ -447,6 +448,17 @@ impl X509Ref { } } +impl ToOwned for X509Ref { + type Owned = X509; + + fn to_owned(&self) -> X509 { + unsafe { + compat::X509_up_ref(self.as_ptr()); + X509::from_ptr(self.as_ptr()) + } + } +} + /// An owned public key certificate. pub struct X509(*mut ffi::X509); @@ -491,10 +503,7 @@ impl Deref for X509 { impl Clone for X509 { fn clone(&self) -> X509 { - unsafe { - compat::X509_up_ref(self.as_ptr()); - X509::from_ptr(self.as_ptr()) - } + self.to_owned() } } @@ -504,6 +513,18 @@ impl Drop for X509 { } } +impl AsRef for X509 { + fn as_ref(&self) -> &X509Ref { + &*self + } +} + +impl Borrow for X509 { + fn borrow(&self) -> &X509Ref { + &*self + } +} + pub struct X509NameRef(Opaque); impl X509NameRef { From 57d10ebbc3c04d5089b034b9d88f40c302783c96 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 29 Oct 2016 14:19:09 -0700 Subject: [PATCH 105/186] Add PKeyRef --- openssl/src/pkey.rs | 111 +++++++++++++++++++++-------------- openssl/src/ssl/connector.rs | 6 +- openssl/src/ssl/mod.rs | 4 +- 3 files changed, 71 insertions(+), 50 deletions(-) diff --git a/openssl/src/pkey.rs b/openssl/src/pkey.rs index e62bbbd9..4cbfcce7 100644 --- a/openssl/src/pkey.rs +++ b/openssl/src/pkey.rs @@ -1,6 +1,7 @@ use libc::{c_void, c_char, c_int}; use std::ptr; use std::mem; +use std::ops::Deref; use ffi; use {cvt, cvt_p}; @@ -9,13 +10,66 @@ use dsa::Dsa; use rsa::Rsa; use error::ErrorStack; use util::{CallbackState, invoke_passwd_cb}; +use opaque::Opaque; +/// A borrowed `PKey`. +pub struct PKeyRef(Opaque); + +impl PKeyRef { + pub unsafe fn from_ptr<'a>(ptr: *mut ffi::EVP_PKEY) -> &'a PKeyRef { + &*(ptr as *mut _) + } + + pub fn as_ptr(&self) -> *mut ffi::EVP_PKEY { + self as *const _ as *mut _ + } + + /// Get a reference to the interal RSA key for direct access to the key components + pub fn rsa(&self) -> Result { + unsafe { + let rsa = try!(cvt_p(ffi::EVP_PKEY_get1_RSA(self.as_ptr()))); + // this is safe as the ffi increments a reference counter to the internal key + Ok(Rsa::from_ptr(rsa)) + } + } + + /// Stores private key as a PEM + // FIXME: also add password and encryption + pub fn private_key_to_pem(&self) -> Result, ErrorStack> { + let mem_bio = try!(MemBio::new()); + unsafe { + try!(cvt(ffi::PEM_write_bio_PrivateKey(mem_bio.as_ptr(), + self.as_ptr(), + ptr::null(), + ptr::null_mut(), + -1, + None, + ptr::null_mut()))); + + } + Ok(mem_bio.get_buf().to_owned()) + } + + /// Stores public key as a PEM + pub fn public_key_to_pem(&self) -> Result, ErrorStack> { + let mem_bio = try!(MemBio::new()); + unsafe { + try!(cvt(ffi::PEM_write_bio_PUBKEY(mem_bio.as_ptr(), self.as_ptr()))); + } + Ok(mem_bio.get_buf().to_owned()) + } + + pub fn public_eq(&self, other: &PKeyRef) -> bool { + unsafe { ffi::EVP_PKEY_cmp(self.as_ptr(), other.as_ptr()) == 1 } + } +} + +/// Represents a public key, optionally with a private key attached. pub struct PKey(*mut ffi::EVP_PKEY); unsafe impl Send for PKey {} unsafe impl Sync for PKey {} -/// Represents a public key, optionally with a private key attached. impl PKey { /// Create a new `PKey` containing an RSA key. pub fn from_rsa(rsa: Rsa) -> Result { @@ -101,7 +155,7 @@ impl PKey { } } - /// assign RSA key to this pkey + /// Assign an RSA key to this pkey. pub fn set_rsa(&mut self, rsa: &Rsa) -> Result<(), ErrorStack> { unsafe { // this needs to be a reference as the set1_RSA ups the reference count @@ -110,49 +164,6 @@ impl PKey { Ok(()) } } - - /// Get a reference to the interal RSA key for direct access to the key components - pub fn rsa(&self) -> Result { - unsafe { - let rsa = try!(cvt_p(ffi::EVP_PKEY_get1_RSA(self.0))); - // this is safe as the ffi increments a reference counter to the internal key - Ok(Rsa::from_ptr(rsa)) - } - } - - /// Stores private key as a PEM - // FIXME: also add password and encryption - pub fn private_key_to_pem(&self) -> Result, ErrorStack> { - let mem_bio = try!(MemBio::new()); - unsafe { - try!(cvt(ffi::PEM_write_bio_PrivateKey(mem_bio.as_ptr(), - self.0, - ptr::null(), - ptr::null_mut(), - -1, - None, - ptr::null_mut()))); - - } - Ok(mem_bio.get_buf().to_owned()) - } - - /// Stores public key as a PEM - pub fn public_key_to_pem(&self) -> Result, ErrorStack> { - let mem_bio = try!(MemBio::new()); - unsafe { - try!(cvt(ffi::PEM_write_bio_PUBKEY(mem_bio.as_ptr(), self.0))); - } - Ok(mem_bio.get_buf().to_owned()) - } - - pub fn as_ptr(&self) -> *mut ffi::EVP_PKEY { - return self.0; - } - - pub fn public_eq(&self, other: &PKey) -> bool { - unsafe { ffi::EVP_PKEY_cmp(self.0, other.0) == 1 } - } } impl Drop for PKey { @@ -163,6 +174,16 @@ impl Drop for PKey { } } +impl Deref for PKey { + type Target = PKeyRef; + + fn deref(&self) -> &PKeyRef { + unsafe { + PKeyRef::from_ptr(self.0) + } + } +} + #[cfg(test)] mod tests { #[test] diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index aed01f8c..62f0a284 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -4,7 +4,7 @@ use dh::Dh; use error::ErrorStack; use ssl::{self, SslMethod, SslContextBuilder, SslContext, Ssl, SSL_VERIFY_PEER, SslStream, HandshakeError}; -use pkey::PKey; +use pkey::PKeyRef; use x509::X509Ref; // apps/dh2048.pem @@ -85,7 +85,7 @@ impl ClientConnector { pub struct ServerConnectorBuilder(SslContextBuilder); impl ServerConnectorBuilder { - pub fn tls(private_key: &PKey, + pub fn tls(private_key: &PKeyRef, certificate: &X509Ref, chain: I) -> Result @@ -96,7 +96,7 @@ impl ServerConnectorBuilder { } fn new(method: SslMethod, - private_key: &PKey, + private_key: &PKeyRef, certificate: &X509Ref, chain: I) -> Result diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 19b21d9d..9e39d8bf 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -24,7 +24,7 @@ use dh::Dh; use x509::{X509StoreContextRef, X509FileType, X509, X509Ref, X509VerifyError}; #[cfg(any(ossl102, ossl110))] use verify::X509VerifyParamRef; -use pkey::PKey; +use pkey::PKeyRef; use error::ErrorStack; use opaque::Opaque; @@ -532,7 +532,7 @@ impl SslContextBuilder { } /// Specifies the private key - pub fn set_private_key(&mut self, key: &PKey) -> Result<(), ErrorStack> { + pub fn set_private_key(&mut self, key: &PKeyRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::SSL_CTX_use_PrivateKey(self.as_ptr(), key.as_ptr())).map(|_| ()) } From e72533c058967f56b302e40c63175cb1b078d052 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 29 Oct 2016 15:00:46 -0700 Subject: [PATCH 106/186] Docs for connectors --- openssl/src/ssl/connector.rs | 30 ++++++++++++++++++++++++++++++ openssl/src/ssl/mod.rs | 12 ++++++++++++ 2 files changed, 42 insertions(+) diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index 62f0a284..da2c03df 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -40,9 +40,13 @@ fn ctx(method: SslMethod) -> Result { Ok(ctx) } +/// A builder for `ClientConnector`s. pub struct ClientConnectorBuilder(SslContextBuilder); impl ClientConnectorBuilder { + /// Creates a new builder for TLS connections. + /// + /// The default configuration is based off of libcurl's and is subject to change. pub fn tls() -> Result { ClientConnectorBuilder::new(SslMethod::tls()) } @@ -55,22 +59,35 @@ impl ClientConnectorBuilder { Ok(ClientConnectorBuilder(ctx)) } + /// Returns a shared reference to the inner `SslContextBuilder`. pub fn context(&self) -> &SslContextBuilder { &self.0 } + /// Returns a mutable reference to the inner `SslContextBuilder`. pub fn context_mut(&mut self) -> &mut SslContextBuilder { &mut self.0 } + /// Consumes the builder, returning a `ClientConnector`. pub fn build(self) -> ClientConnector { ClientConnector(self.0.build()) } } +/// A type which wraps client-side streams in a TLS session. +/// +/// OpenSSL's default configuration is highly insecure. This connector manages the OpenSSL +/// structures, configuring cipher suites, session options, hostname verification, and more. +/// +/// OpenSSL's built in hostname verification is used when linking against OpenSSL 1.0.2 or 1.1.0, +/// and a custom implementation is used when linking against OpenSSL 1.0.1. pub struct ClientConnector(SslContext); impl ClientConnector { + /// Initiates a client-side TLS session on a stream. + /// + /// The domain is used for SNI and hostname verification. pub fn connect(&self, domain: &str, stream: S) -> Result, HandshakeError> where S: Read + Write { @@ -82,9 +99,14 @@ impl ClientConnector { } } +/// A builder for `ServerConnector`s. pub struct ServerConnectorBuilder(SslContextBuilder); impl ServerConnectorBuilder { + /// Creates a new builder for server-side TLS connections. + /// + /// The default configuration is based off of the intermediate profile of Mozilla's SSL + /// Configuration Generator, and is subject to change. pub fn tls(private_key: &PKeyRef, certificate: &X509Ref, chain: I) @@ -127,22 +149,30 @@ impl ServerConnectorBuilder { Ok(ServerConnectorBuilder(ctx)) } + /// Returns a shared reference to the inner `SslContextBuilder`. pub fn context(&self) -> &SslContextBuilder { &self.0 } + /// Returns a mutable reference to the inner `SslContextBuilder`. pub fn context_mut(&mut self) -> &mut SslContextBuilder { &mut self.0 } + /// Consumes the builder, returning a `ServerConnector`. pub fn build(self) -> ServerConnector { ServerConnector(self.0.build()) } } +/// A type which wraps server-side streams in a TLS session. +/// +/// OpenSSL's default configuration is highly insecure. This connector manages the OpenSSL +/// structures, configuring cipher suites, session options, and more. pub struct ServerConnector(SslContext); impl ServerConnector { + /// Initiates a server-side TLS session on a stream. pub fn connect(&self, stream: S) -> Result, HandshakeError> where S: Read + Write { diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 9e39d8bf..ddf27460 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -342,6 +342,7 @@ pub enum SniError { NoAck, } +/// A builder for `SslContext`s. pub struct SslContextBuilder(*mut ffi::SSL_CTX); impl Drop for SslContextBuilder { @@ -793,6 +794,7 @@ impl SslCipherRef { } } +/// A reference to an `Ssl`. pub struct SslRef(Opaque); unsafe impl Send for SslRef {} @@ -1104,6 +1106,11 @@ impl Ssl { } /// Creates an SSL/TLS client operating over the provided stream. + /// + /// # Warning + /// + /// OpenSSL's default configuration is insecure. It is highly recommended to use + /// `ClientConnector` rather than `Ssl` directly, as it manages that configuration. pub fn connect(self, stream: S) -> Result, HandshakeError> where S: Read + Write { @@ -1131,6 +1138,11 @@ impl Ssl { } /// Creates an SSL/TLS server operating over the provided stream. + /// + /// # Warning + /// + /// OpenSSL's default configuration is insecure. It is highly recommended to use + /// `ServerConnector` rather than `Ssl` directly, as it manages that configuration. pub fn accept(self, stream: S) -> Result, HandshakeError> where S: Read + Write { From 85169e5a61645a411e67b4753b7455a0514271b2 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 29 Oct 2016 15:02:07 -0700 Subject: [PATCH 107/186] Fix reexport --- openssl/src/x509/mod.rs | 2 +- openssl/src/x509/verify.rs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 openssl/src/x509/verify.rs diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 9fd6812a..31ed11b4 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -39,7 +39,7 @@ use ffi::{ }; #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -pub use verify; +pub mod verify; use x509::extension::{ExtensionType, Extension}; diff --git a/openssl/src/x509/verify.rs b/openssl/src/x509/verify.rs new file mode 100644 index 00000000..aa264ba9 --- /dev/null +++ b/openssl/src/x509/verify.rs @@ -0,0 +1 @@ +pub use ::verify::*; From c2b38d8bb3f141e531a3e636b8a86a073d78f316 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 29 Oct 2016 15:02:36 -0700 Subject: [PATCH 108/186] Move docs --- openssl/src/verify.rs | 4 ---- openssl/src/x509/verify.rs | 4 ++++ 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/openssl/src/verify.rs b/openssl/src/verify.rs index 77095edc..ceb3a6c8 100644 --- a/openssl/src/verify.rs +++ b/openssl/src/verify.rs @@ -1,7 +1,3 @@ -//! X509 certificate verification -//! -//! Requires the `v102` or `v110` features and OpenSSL 1.0.2 or 1.1.0. - use libc::c_uint; use ffi; diff --git a/openssl/src/x509/verify.rs b/openssl/src/x509/verify.rs index aa264ba9..8cb123e6 100644 --- a/openssl/src/x509/verify.rs +++ b/openssl/src/x509/verify.rs @@ -1 +1,5 @@ +//! X509 certificate verification +//! +//! Requires the `v102` or `v110` features and OpenSSL 1.0.2 or 1.1.0. + pub use ::verify::*; From c89f2c0be08bc77afc2f8a45e488ab8e394f0f3d Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 29 Oct 2016 16:37:26 -0700 Subject: [PATCH 109/186] Use PKeyRef in X509Generator --- openssl/src/x509/mod.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 31ed11b4..b7cbe363 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -18,7 +18,7 @@ use asn1::Asn1TimeRef; use bio::{MemBio, MemBioSlice}; use crypto::CryptoString; use hash::MessageDigest; -use pkey::PKey; +use pkey::{PKey, PKeyRef}; use rand::rand_bytes; use error::ErrorStack; use ffi; @@ -278,7 +278,7 @@ impl X509Generator { } /// Sets the certificate public-key, then self-sign and return it - pub fn sign(&self, p_key: &PKey) -> Result { + pub fn sign(&self, p_key: &PKeyRef) -> Result { ffi::init(); unsafe { @@ -330,7 +330,7 @@ impl X509Generator { } /// Obtain a certificate signing request (CSR) - pub fn request(&self, p_key: &PKey) -> Result { + pub fn request(&self, p_key: &PKeyRef) -> Result { let cert = match self.sign(p_key) { Ok(c) => c, Err(x) => return Err(x), From 761dd780c179d667c1b0ee6dd0a6e8e05c24ca46 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 29 Oct 2016 17:25:01 -0700 Subject: [PATCH 110/186] Add module level docs --- openssl/src/ssl/mod.rs | 69 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index ddf27460..ae7abea9 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -1,3 +1,72 @@ +//! SSL/TLS support. +//! +//! The `ClientConnector` and `ServerConnector` should be used in most cases - they handle +//! configuration of the OpenSSL primitives for you. +//! +//! # Examples +//! +//! To connect as a client to a remote server: +//! +//! ```no_run +//! use openssl::ssl::ClientConnectorBuilder; +//! use std::io::{Read, Write}; +//! use std::net::TcpStream; +//! +//! let connector = ClientConnectorBuilder::tls().unwrap().build(); +//! +//! let stream = TcpStream::connect("google.com:443").unwrap(); +//! let mut stream = connector.connect("google.com", stream).unwrap(); +//! +//! stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); +//! let mut res = vec![]; +//! stream.read_to_end(&mut res).unwrap(); +//! println!("{}", String::from_utf8_lossy(&res)); +//! ``` +//! +//! To accept connections as a server from remote clients: +//! +//! ```no_run +//! use openssl::pkcs12::Pkcs12; +//! use openssl::ssl::{ServerConnectorBuilder, SslStream}; +//! use std::fs::File; +//! use std::io::{Read, Write}; +//! use std::net::{TcpListener, TcpStream}; +//! use std::sync::Arc; +//! use std::thread; +//! +//! // In this example we retrieve our keypair and certificate chain from a PKCS #12 archive, +//! // but but they can also be retrieved from, for example, individual PEM- or DER-formatted +//! // files. See the documentation for the `PKey` and `X509` types for more details. +//! let mut file = File::open("identity.pfx").unwrap(); +//! let mut pkcs12 = vec![]; +//! file.read_to_end(&mut pkcs12).unwrap(); +//! let pkcs12 = Pkcs12::from_der(&pkcs12).unwrap(); +//! let identity = pkcs12.parse("password123").unwrap(); +//! +//! let connector = ServerConnectorBuilder::tls(&identity.pkey, &identity.cert, &identity.chain) +//! .unwrap() +//! .build(); +//! let connector = Arc::new(connector); +//! +//! let listener = TcpListener::bind("0.0.0.0:8443").unwrap(); +//! +//! fn handle_client(stream: SslStream) { +//! // ... +//! } +//! +//! for stream in listener.incoming() { +//! match stream { +//! Ok(stream) => { +//! let connector = connector.clone(); +//! thread::spawn(move || { +//! let stream = connector.connect(stream).unwrap(); +//! handle_client(stream); +//! }); +//! } +//! Err(e) => { /* connection failed */ } +//! } +//! } +//! ``` use libc::{c_int, c_void, c_long, c_ulong}; use std::any::Any; use std::any::TypeId; From 23fe1e85e96a1148da1b9bfee570880770eca3cb Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 29 Oct 2016 18:16:45 -0700 Subject: [PATCH 111/186] Pull Curl's CA list for Windows tests --- appveyor.yml | 2 ++ openssl/src/ssl/mod.rs | 2 +- openssl/src/ssl/tests/mod.rs | 5 ----- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 9a7a3dc7..3e23044e 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,4 +1,5 @@ environment: + SSL_CERT_FILE: "C:\\OpenSSL\\cacert.pem" matrix: # 1.1.0, 64/32 bit - TARGET: i686-pc-windows-gnu @@ -23,6 +24,7 @@ install: # install OpenSSL - ps: Start-FileDownload "http://slproweb.com/download/Win${env:BITS}OpenSSL-${env:OPENSSL_VERSION}.exe" - Win%BITS%OpenSSL-%OPENSSL_VERSION%.exe /SILENT /VERYSILENT /SP- /DIR="C:\OpenSSL" + - ps: Start-FileDownload "https://curl.haxx.se/ca/cacert.pem" -FileName "C:\OpenSSL\cacert.pem" # Install Rust - curl -sSf -o rustup-init.exe https://win.rustup.rs/ diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index ae7abea9..cd7c1426 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -7,7 +7,7 @@ //! //! To connect as a client to a remote server: //! -//! ```no_run +//! ``` //! use openssl::ssl::ClientConnectorBuilder; //! use std::io::{Read, Write}; //! use std::net::TcpStream; diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index f98f9928..5a8067c9 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -1018,7 +1018,6 @@ fn refcount_ssl_context() { } #[test] -#[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( fn default_verify_paths() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_default_verify_paths().unwrap(); @@ -1044,7 +1043,6 @@ fn add_extra_chain_cert() { } #[test] -#[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn verify_valid_hostname() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); @@ -1068,7 +1066,6 @@ fn verify_valid_hostname() { } #[test] -#[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] fn verify_invalid_hostname() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); @@ -1084,7 +1081,6 @@ fn verify_invalid_hostname() { } #[test] -#[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( fn connector_valid_hostname() { let connector = ClientConnectorBuilder::tls().unwrap().build(); @@ -1101,7 +1097,6 @@ fn connector_valid_hostname() { } #[test] -#[cfg_attr(windows, ignore)] // don't have a trusted CA list easily available :( fn connector_invalid_hostname() { let connector = ClientConnectorBuilder::tls().unwrap().build(); From eb735f519aa1a5b7033b640ee6229efa5f98c19c Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 11:05:29 -0700 Subject: [PATCH 112/186] Clean up generics a bit --- openssl/src/ssl/connector.rs | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index da2c03df..7d0bc4cd 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -105,25 +105,25 @@ pub struct ServerConnectorBuilder(SslContextBuilder); impl ServerConnectorBuilder { /// Creates a new builder for server-side TLS connections. /// - /// The default configuration is based off of the intermediate profile of Mozilla's SSL - /// Configuration Generator, and is subject to change. - pub fn tls(private_key: &PKeyRef, - certificate: &X509Ref, - chain: I) - -> Result - where I: IntoIterator, - T: AsRef + /// The default configuration is based off of the intermediate profile of Mozilla's server side + /// TLS configuration recommendations, and is subject to change. + pub fn tls(private_key: &PKeyRef, + certificate: &X509Ref, + chain: I) + -> Result + where I: IntoIterator, + I::Item: AsRef { ServerConnectorBuilder::new(SslMethod::tls(), private_key, certificate, chain) } - fn new(method: SslMethod, - private_key: &PKeyRef, - certificate: &X509Ref, - chain: I) - -> Result - where I: IntoIterator, - T: AsRef + fn new(method: SslMethod, + private_key: &PKeyRef, + certificate: &X509Ref, + chain: I) + -> Result + where I: IntoIterator, + I::Item: AsRef { let mut ctx = try!(ctx(method)); ctx.set_options(ssl::SSL_OP_SINGLE_DH_USE | ssl::SSL_OP_CIPHER_SERVER_PREFERENCE); From 8c58ecc2fa63fb4234b9e48ef9ba0113628ce35f Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 13:17:20 -0700 Subject: [PATCH 113/186] Implement EcKey cc #499 --- openssl-sys/src/lib.rs | 5 +++- openssl/src/ec_key.rs | 62 ++++++++++++++++++++++++++++++++++++++++++ openssl/src/lib.rs | 1 + 3 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 openssl/src/ec_key.rs diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index ac168c48..171525d6 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 COMP_METHOD {} +pub enum EC_KEY {} pub enum ENGINE {} pub enum EVP_CIPHER_CTX {} pub enum EVP_MD {} @@ -1341,8 +1342,10 @@ extern { #[cfg(not(ossl101))] pub fn DH_get_2048_256() -> *mut DH; - pub fn ERR_get_error() -> c_ulong; + pub fn EC_KEY_new_by_curve_name(nid: c_int) -> *mut EC_KEY; + pub fn EC_KEY_free(key: *mut EC_KEY); + pub fn ERR_get_error() -> c_ulong; pub fn ERR_lib_error_string(err: c_ulong) -> *const c_char; pub fn ERR_func_error_string(err: c_ulong) -> *const c_char; pub fn ERR_reason_error_string(err: c_ulong) -> *const c_char; diff --git a/openssl/src/ec_key.rs b/openssl/src/ec_key.rs new file mode 100644 index 00000000..5d634c5a --- /dev/null +++ b/openssl/src/ec_key.rs @@ -0,0 +1,62 @@ +use ffi; +use std::ops::Deref; + +use cvt_p; +use error::ErrorStack; +use nid::Nid; +use opaque::Opaque; + +pub struct EcKeyRef(Opaque); + +impl EcKeyRef { + pub unsafe fn from_ptr<'a>(ptr: *mut ffi::EC_KEY) -> &'a EcKeyRef { + &*(ptr as *mut _) + } + + pub fn as_ptr(&self) -> *mut ffi::EC_KEY { + self as *const _ as *mut _ + } +} + +pub struct EcKey(*mut ffi::EC_KEY); + +impl Drop for EcKey { + fn drop(&mut self) { + unsafe { + ffi::EC_KEY_free(self.0); + } + } +} + +impl EcKey { + pub fn new_by_curve_name(nid: Nid) -> Result { + unsafe { + cvt_p(ffi::EC_KEY_new_by_curve_name(nid.as_raw())).map(EcKey) + } + } + + pub unsafe fn from_ptr(ptr: *mut ffi::EC_KEY) -> EcKey { + EcKey(ptr) + } +} + +impl Deref for EcKey { + type Target = EcKeyRef; + + fn deref(&self) -> &EcKeyRef { + unsafe { + EcKeyRef::from_ptr(self.0) + } + } +} + +#[cfg(test)] +mod test { + use nid; + use super::*; + + #[test] + fn new_by_curve_name() { + EcKey::new_by_curve_name(nid::X9_62_PRIME256V1).unwrap(); + } +} diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index acdc2ea8..4212e9de 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -28,6 +28,7 @@ pub mod bn; pub mod crypto; pub mod dh; pub mod dsa; +pub mod ec_key; pub mod error; pub mod hash; pub mod memcmp; From 677718f8da0024248fb6dfaa8f201ee6a6b3a219 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 13:38:09 -0700 Subject: [PATCH 114/186] Configure ECDH parameters in connector --- openssl-sys/src/lib.rs | 5 +++++ openssl/src/dh.rs | 32 ++++++++++++++++++++++++++------ openssl/src/ssl/connector.rs | 17 +++++++++++++++++ openssl/src/ssl/mod.rs | 16 ++++++++++++++-- 4 files changed, 62 insertions(+), 8 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 171525d6..8fd287f7 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1043,6 +1043,7 @@ pub const RSA_PKCS1_OAEP_PADDING: c_int = 4; pub const RSA_X931_PADDING: c_int = 5; pub const SSL_CTRL_SET_TMP_DH: c_int = 3; +pub const SSL_CTRL_SET_TMP_ECDH: c_int = 4; pub const SSL_CTRL_EXTRA_CHAIN_CERT: c_int = 14; pub const SSL_CTRL_MODE: c_int = 33; pub const SSL_CTRL_SET_READ_AHEAD: c_int = 41; @@ -1214,6 +1215,10 @@ pub unsafe fn SSL_CTX_set_tmp_dh(ctx: *mut SSL_CTX, dh: *mut DH) -> c_long { SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TMP_DH, 0, dh as *mut c_void) } +pub unsafe fn SSL_CTX_set_tmp_ecdh(ctx: *mut SSL_CTX, key: *mut EC_KEY) -> c_long { + SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TMP_ECDH, 0, key as *mut c_void) +} + pub unsafe fn SSL_CTX_add_extra_chain_cert(ctx: *mut SSL_CTX, x509: *mut X509) -> c_long { SSL_CTX_ctrl(ctx, SSL_CTRL_EXTRA_CHAIN_CERT, 0, x509 as *mut c_void) } diff --git a/openssl/src/dh.rs b/openssl/src/dh.rs index 755e3e6b..b0c9737b 100644 --- a/openssl/src/dh.rs +++ b/openssl/src/dh.rs @@ -2,10 +2,24 @@ use ffi; use error::ErrorStack; use bio::MemBioSlice; use std::ptr; +use std::mem; +use std::ops::Deref; use {cvt, cvt_p}; use bn::BigNum; -use std::mem; +use opaque::Opaque; + +pub struct DhRef(Opaque); + +impl DhRef { + pub unsafe fn from_ptr<'a>(ptr: *mut ffi::DH) -> &'a DhRef { + &*(ptr as *mut _) + } + + pub fn as_ptr(&self) -> *mut ffi::DH { + self as *const _ as *mut _ + } +} pub struct Dh(*mut ffi::DH); @@ -56,16 +70,22 @@ impl Dh { cvt_p(ffi::DH_get_2048_256()).map(Dh) } } - - pub fn as_ptr(&self) -> *mut ffi::DH { - self.0 - } } impl Drop for Dh { fn drop(&mut self) { unsafe { - ffi::DH_free(self.as_ptr()) + ffi::DH_free(self.0) + } + } +} + +impl Deref for Dh { + type Target = DhRef; + + fn deref(&self) -> &DhRef { + unsafe { + DhRef::from_ptr(self.0) } } } diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index 7d0bc4cd..625c37e8 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -129,6 +129,7 @@ impl ServerConnectorBuilder { ctx.set_options(ssl::SSL_OP_SINGLE_DH_USE | ssl::SSL_OP_CIPHER_SERVER_PREFERENCE); let dh = try!(Dh::from_pem(DHPARAM_PEM.as_bytes())); try!(ctx.set_tmp_dh(&dh)); + try!(setup_curves(&mut ctx)); try!(ctx.set_cipher_list( "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:\ ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:\ @@ -165,6 +166,22 @@ impl ServerConnectorBuilder { } } +#[cfg(ossl101)] +fn setup_curves(ctx: &mut SslContextBuilder) -> Result<(), ErrorStack> { + let curve = try!(::ec_key::EcKey::new_by_curve_name(::nid::X9_62_PRIME256V1)); + ctx.set_tmp_ecdh(&curve) +} + +#[cfg(ossl102)] +fn setup_curves(ctx: &mut SslContextBuilder) -> Result<(), ErrorStack> { + ctx._set_ecdh_auto(true) +} + +#[cfg(ossl110)] +fn setup_curves(_: &mut SslContextBuilder) -> Result<(), ErrorStack> { + Ok(()) +} + /// A type which wraps server-side streams in a TLS session. /// /// OpenSSL's default configuration is highly insecure. This connector manages the OpenSSL diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index cd7c1426..ffcc61ab 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -89,7 +89,8 @@ use std::marker::PhantomData; use ffi; use {init, cvt, cvt_p}; -use dh::Dh; +use dh::DhRef; +use ec_key::EcKeyRef; use x509::{X509StoreContextRef, X509FileType, X509, X509Ref, X509VerifyError}; #[cfg(any(ossl102, ossl110))] use verify::X509VerifyParamRef; @@ -498,12 +499,18 @@ impl SslContextBuilder { } } - pub fn set_tmp_dh(&mut self, dh: &Dh) -> Result<(), ErrorStack> { + pub fn set_tmp_dh(&mut self, dh: &DhRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::SSL_CTX_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as c_int).map(|_| ()) } } + pub fn set_tmp_ecdh(&mut self, key: &EcKeyRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::SSL_CTX_set_tmp_ecdh(self.as_ptr(), key.as_ptr()) as c_int).map(|_| ()) + } + } + /// Use the default locations of trusted certificates for verification. /// /// These locations are read from the `SSL_CERT_FILE` and `SSL_CERT_DIR` @@ -623,6 +630,11 @@ impl SslContextBuilder { /// Requires the `v102` feature and OpenSSL 1.0.2. #[cfg(all(feature = "v102", ossl102))] pub fn set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> { + self._set_ecdh_auto(onoff) + } + + #[cfg(ossl102)] + fn _set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> { unsafe { cvt(ffi::SSL_CTX_set_ecdh_auto(self.as_ptr(), onoff as c_int)).map(|_| ()) } From ee79db61c23767f1c72ca70766b8dcda971cf5b9 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 13:41:24 -0700 Subject: [PATCH 115/186] Enable single ECDH use --- openssl/src/ssl/connector.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index 625c37e8..0ec6526e 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -126,7 +126,8 @@ impl ServerConnectorBuilder { I::Item: AsRef { let mut ctx = try!(ctx(method)); - ctx.set_options(ssl::SSL_OP_SINGLE_DH_USE | ssl::SSL_OP_CIPHER_SERVER_PREFERENCE); + ctx.set_options(ssl::SSL_OP_SINGLE_DH_USE | ssl::SSL_OP_SINGLE_ECDH_USE | + ssl::SSL_OP_CIPHER_SERVER_PREFERENCE); let dh = try!(Dh::from_pem(DHPARAM_PEM.as_bytes())); try!(ctx.set_tmp_dh(&dh)); try!(setup_curves(&mut ctx)); From 43b430e5b0723784862fb090ef091bc404542989 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 14:26:28 -0700 Subject: [PATCH 116/186] Pass SslMethod into constructors --- openssl/src/ssl/connector.rs | 20 +++----------------- openssl/src/ssl/mod.rs | 11 +++++++---- openssl/src/ssl/tests/mod.rs | 10 ++++++---- 3 files changed, 16 insertions(+), 25 deletions(-) diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index 0ec6526e..794523bb 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -47,11 +47,7 @@ impl ClientConnectorBuilder { /// Creates a new builder for TLS connections. /// /// The default configuration is based off of libcurl's and is subject to change. - pub fn tls() -> Result { - ClientConnectorBuilder::new(SslMethod::tls()) - } - - fn new(method: SslMethod) -> Result { + pub fn new(method: SslMethod) -> Result { let mut ctx = try!(ctx(method)); try!(ctx.set_default_verify_paths()); try!(ctx.set_cipher_list("ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH")); @@ -107,23 +103,13 @@ impl ServerConnectorBuilder { /// /// The default configuration is based off of the intermediate profile of Mozilla's server side /// TLS configuration recommendations, and is subject to change. - pub fn tls(private_key: &PKeyRef, + pub fn new(method: SslMethod, + private_key: &PKeyRef, certificate: &X509Ref, chain: I) -> Result where I: IntoIterator, I::Item: AsRef - { - ServerConnectorBuilder::new(SslMethod::tls(), private_key, certificate, chain) - } - - fn new(method: SslMethod, - private_key: &PKeyRef, - certificate: &X509Ref, - chain: I) - -> Result - where I: IntoIterator, - I::Item: AsRef { let mut ctx = try!(ctx(method)); ctx.set_options(ssl::SSL_OP_SINGLE_DH_USE | ssl::SSL_OP_SINGLE_ECDH_USE | diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index ffcc61ab..f363d452 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -8,11 +8,11 @@ //! To connect as a client to a remote server: //! //! ``` -//! use openssl::ssl::ClientConnectorBuilder; +//! use openssl::ssl::{SslMethod, ClientConnectorBuilder}; //! use std::io::{Read, Write}; //! use std::net::TcpStream; //! -//! let connector = ClientConnectorBuilder::tls().unwrap().build(); +//! let connector = ClientConnectorBuilder::new(SslMethod::tls()).unwrap().build(); //! //! let stream = TcpStream::connect("google.com:443").unwrap(); //! let mut stream = connector.connect("google.com", stream).unwrap(); @@ -27,7 +27,7 @@ //! //! ```no_run //! use openssl::pkcs12::Pkcs12; -//! use openssl::ssl::{ServerConnectorBuilder, SslStream}; +//! use openssl::ssl::{SslMethod, ServerConnectorBuilder, SslStream}; //! use std::fs::File; //! use std::io::{Read, Write}; //! use std::net::{TcpListener, TcpStream}; @@ -43,7 +43,10 @@ //! let pkcs12 = Pkcs12::from_der(&pkcs12).unwrap(); //! let identity = pkcs12.parse("password123").unwrap(); //! -//! let connector = ServerConnectorBuilder::tls(&identity.pkey, &identity.cert, &identity.chain) +//! let connector = ServerConnectorBuilder::new(SslMethod::tls(), +//! &identity.pkey, +//! &identity.cert, +//! &identity.chain) //! .unwrap() //! .build(); //! let connector = Arc::new(connector); diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 5a8067c9..5e5d8988 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -1082,7 +1082,7 @@ fn verify_invalid_hostname() { #[test] fn connector_valid_hostname() { - let connector = ClientConnectorBuilder::tls().unwrap().build(); + let connector = ClientConnectorBuilder::new(SslMethod::tls()).unwrap().build(); let s = TcpStream::connect("google.com:443").unwrap(); let mut socket = connector.connect("google.com", s).unwrap(); @@ -1098,7 +1098,7 @@ fn connector_valid_hostname() { #[test] fn connector_invalid_hostname() { - let connector = ClientConnectorBuilder::tls().unwrap().build(); + let connector = ClientConnectorBuilder::new(SslMethod::tls()).unwrap().build(); let s = TcpStream::connect("google.com:443").unwrap(); assert!(connector.connect("foobar.com", s).is_err()); @@ -1112,14 +1112,16 @@ fn connector_client_server() { let t = thread::spawn(move || { let key = PKey::private_key_from_pem(KEY).unwrap(); let cert = X509::from_pem(CERT).unwrap(); - let connector = ServerConnectorBuilder::tls(&key, &cert, None::).unwrap().build(); + let connector = ServerConnectorBuilder::new(SslMethod::tls(), &key, &cert, None::) + .unwrap() + .build(); let stream = listener.accept().unwrap().0; let mut stream = connector.connect(stream).unwrap(); stream.write_all(b"hello").unwrap(); }); - let mut connector = ClientConnectorBuilder::tls().unwrap(); + let mut connector = ClientConnectorBuilder::new(SslMethod::tls()).unwrap(); connector.context_mut().set_CA_file("test/root-ca.pem").unwrap(); let connector = connector.build(); From 7d13176cd1719dd0047c3fafad8e0fd6bbaa1711 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 14:34:05 -0700 Subject: [PATCH 117/186] Rename nwe to mozilla_intermediate --- openssl/src/ssl/connector.rs | 10 +++++----- openssl/src/ssl/mod.rs | 6 ++---- openssl/src/ssl/tests/mod.rs | 3 ++- 3 files changed, 9 insertions(+), 10 deletions(-) diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index 794523bb..0bac87cf 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -103,11 +103,11 @@ impl ServerConnectorBuilder { /// /// The default configuration is based off of the intermediate profile of Mozilla's server side /// TLS configuration recommendations, and is subject to change. - pub fn new(method: SslMethod, - private_key: &PKeyRef, - certificate: &X509Ref, - chain: I) - -> Result + pub fn mozilla_intermediate(method: SslMethod, + private_key: &PKeyRef, + certificate: &X509Ref, + chain: I) + -> Result where I: IntoIterator, I::Item: AsRef { diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index f363d452..802ce8f0 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -43,10 +43,8 @@ //! let pkcs12 = Pkcs12::from_der(&pkcs12).unwrap(); //! let identity = pkcs12.parse("password123").unwrap(); //! -//! let connector = ServerConnectorBuilder::new(SslMethod::tls(), -//! &identity.pkey, -//! &identity.cert, -//! &identity.chain) +//! let connector = ServerConnectorBuilder::mozilla_intermediate( +//! SslMethod::tls(), &identity.pkey, &identity.cert, &identity.chain) //! .unwrap() //! .build(); //! let connector = Arc::new(connector); diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 5e5d8988..0c0c7957 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -1112,7 +1112,8 @@ fn connector_client_server() { let t = thread::spawn(move || { let key = PKey::private_key_from_pem(KEY).unwrap(); let cert = X509::from_pem(CERT).unwrap(); - let connector = ServerConnectorBuilder::new(SslMethod::tls(), &key, &cert, None::) + let connector = ServerConnectorBuilder::mozilla_intermediate( + SslMethod::tls(), &key, &cert, None::) .unwrap() .build(); let stream = listener.accept().unwrap().0; From 52f288e090ef5d420ea0692c435c42c30570a957 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 14:57:22 -0700 Subject: [PATCH 118/186] Add a mozilla modern profile --- openssl/src/ssl/connector.rs | 35 +++++++++++++++++++++++++++++++++-- openssl/src/ssl/tests/mod.rs | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 66 insertions(+), 3 deletions(-) diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index 0bac87cf..701fdeaf 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -101,8 +101,8 @@ pub struct ServerConnectorBuilder(SslContextBuilder); impl ServerConnectorBuilder { /// Creates a new builder for server-side TLS connections. /// - /// The default configuration is based off of the intermediate profile of Mozilla's server side - /// TLS configuration recommendations, and is subject to change. + /// The configuration is based off of the intermediate profile of Mozilla's server side + /// TLS configuration recommendations. pub fn mozilla_intermediate(method: SslMethod, private_key: &PKeyRef, certificate: &X509Ref, @@ -128,6 +128,37 @@ impl ServerConnectorBuilder { DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:\ EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:\ AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS")); + ServerConnectorBuilder::finish_setup(ctx, private_key, certificate, chain) + } + + pub fn mozilla_modern(method: SslMethod, + private_key: &PKeyRef, + certificate: &X509Ref, + chain: I) + -> Result + where I: IntoIterator, + I::Item: AsRef + { + let mut ctx = try!(ctx(method)); + ctx.set_options(ssl::SSL_OP_SINGLE_ECDH_USE | ssl::SSL_OP_CIPHER_SERVER_PREFERENCE); + try!(setup_curves(&mut ctx)); + try!(ctx.set_cipher_list( + "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:\ + ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:\ + ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:\ + ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:\ + ECDHE-RSA-AES128-SHA256")); + ServerConnectorBuilder::finish_setup(ctx, private_key, certificate, chain) + } + + fn finish_setup(mut ctx: SslContextBuilder, + private_key: &PKeyRef, + certificate: &X509Ref, + chain: I) + -> Result + where I: IntoIterator, + I::Item: AsRef + { try!(ctx.set_private_key(private_key)); try!(ctx.set_certificate(certificate)); try!(ctx.check_private_key()); diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 0c0c7957..eeada33a 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -1105,7 +1105,7 @@ fn connector_invalid_hostname() { } #[test] -fn connector_client_server() { +fn connector_client_server_mozilla_intermediate() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); @@ -1136,6 +1136,38 @@ fn connector_client_server() { t.join().unwrap(); } +#[test] +fn connector_client_server_mozilla_modern() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + + let t = thread::spawn(move || { + let key = PKey::private_key_from_pem(KEY).unwrap(); + let cert = X509::from_pem(CERT).unwrap(); + let connector = ServerConnectorBuilder::mozilla_modern( + SslMethod::tls(), &key, &cert, None::) + .unwrap() + .build(); + let stream = listener.accept().unwrap().0; + let mut stream = connector.connect(stream).unwrap(); + + stream.write_all(b"hello").unwrap(); + }); + + let mut connector = ClientConnectorBuilder::new(SslMethod::tls()).unwrap(); + connector.context_mut().set_CA_file("test/root-ca.pem").unwrap(); + let connector = connector.build(); + + let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut stream = connector.connect("foobar.com", stream).unwrap(); + + let mut buf = [0; 5]; + stream.read_exact(&mut buf).unwrap(); + assert_eq!(b"hello", &buf); + + t.join().unwrap(); +} + #[test] fn shutdown() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); From d1179f1ad28f16c90eba8d89a03b2821aabd9469 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 15:14:29 -0700 Subject: [PATCH 119/186] Update docs --- openssl/src/ssl/connector.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index 701fdeaf..c283145e 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -99,10 +99,13 @@ impl ClientConnector { pub struct ServerConnectorBuilder(SslContextBuilder); impl ServerConnectorBuilder { - /// Creates a new builder for server-side TLS connections. + /// Creates a new builder configured to connect to non-legacy clients. This should generally be + /// considered a reasonable default choice. /// - /// The configuration is based off of the intermediate profile of Mozilla's server side - /// TLS configuration recommendations. + /// This corresponds to the intermediate configuration of Mozilla's server side TLS + /// recommendations. See its [documentation][docs] for more details on specifics. + /// + /// [docs]: https://wiki.mozilla.org/Security/Server_Side_TLS pub fn mozilla_intermediate(method: SslMethod, private_key: &PKeyRef, certificate: &X509Ref, @@ -131,6 +134,12 @@ impl ServerConnectorBuilder { ServerConnectorBuilder::finish_setup(ctx, private_key, certificate, chain) } + /// Creates a new builder configured to connect to modern clients. + /// + /// This corresponds to the modern configuration of Mozilla's server side TLS recommendations. + /// See its [documentation][docs] for more details on specifics. + /// + /// [docs]: https://wiki.mozilla.org/Security/Server_Side_TLS pub fn mozilla_modern(method: SslMethod, private_key: &PKeyRef, certificate: &X509Ref, From 9abbf6f80e98bbefea60d2410c69a08265cd3808 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 16:29:33 -0700 Subject: [PATCH 120/186] Use Python's cipher list on the client side. --- openssl/src/ssl/connector.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index c283145e..44e3488c 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -46,11 +46,14 @@ pub struct ClientConnectorBuilder(SslContextBuilder); impl ClientConnectorBuilder { /// Creates a new builder for TLS connections. /// - /// The default configuration is based off of libcurl's and is subject to change. + /// The default configuration is subject to change, and is currently derived from Python. pub fn new(method: SslMethod) -> Result { let mut ctx = try!(ctx(method)); try!(ctx.set_default_verify_paths()); - try!(ctx.set_cipher_list("ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH")); + // From https://github.com/python/cpython/blob/c30098c8c6014f3340a369a31df9c74bdbacc269/Lib/ssl.py#L191 + try!(ctx.set_cipher_list( + "ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:ECDH+AES128:\ + DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:!aNULL:!eNULL:!MD5:!3DES")); Ok(ClientConnectorBuilder(ctx)) } From 78696514071ef998a2cea67d01db37cf5f6188c6 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 16:34:50 -0700 Subject: [PATCH 121/186] Remove out of date comment --- openssl/src/ssl/connector.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index 44e3488c..f89acf1e 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -27,7 +27,6 @@ See https://tools.ietf.org/html/rfc2412 for how they were generated."#; fn ctx(method: SslMethod) -> Result { let mut ctx = try!(SslContextBuilder::new(method)); - // options to enable and cipher list lifted from libcurl let mut opts = ssl::SSL_OP_ALL; opts |= ssl::SSL_OP_NO_TICKET; opts |= ssl::SSL_OP_NO_COMPRESSION; From f75f82e466993848393c7a26ccb51dc31b4547fe Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 16:37:45 -0700 Subject: [PATCH 122/186] Rustfmt --- openssl/src/asn1.rs | 4 +- openssl/src/bio.rs | 9 +- openssl/src/bn.rs | 142 ++++++++++---------------- openssl/src/dh.rs | 29 ++---- openssl/src/dsa.rs | 25 +++-- openssl/src/ec_key.rs | 8 +- openssl/src/hash.rs | 72 +++++--------- openssl/src/lib.rs | 6 +- openssl/src/nid.rs | 76 +++++++++----- openssl/src/pkcs12.rs | 7 +- openssl/src/pkcs5.rs | 17 +++- openssl/src/pkey.rs | 4 +- openssl/src/rsa.rs | 77 +++++++-------- openssl/src/sign.rs | 129 ++++++++++++------------ openssl/src/ssl/bio.rs | 29 +++--- openssl/src/ssl/connector.rs | 7 +- openssl/src/ssl/mod.rs | 186 +++++++++++++---------------------- openssl/src/ssl/tests/mod.rs | 77 ++++++++------- openssl/src/symm.rs | 109 +++++++------------- openssl/src/util.rs | 13 +-- openssl/src/version.rs | 13 +-- openssl/src/x509/mod.rs | 33 ++----- openssl/src/x509/tests.rs | 7 +- 23 files changed, 459 insertions(+), 620 deletions(-) diff --git a/openssl/src/asn1.rs b/openssl/src/asn1.rs index e9c58e76..9a83a5da 100644 --- a/openssl/src/asn1.rs +++ b/openssl/src/asn1.rs @@ -64,9 +64,7 @@ impl Deref for Asn1Time { type Target = Asn1TimeRef; fn deref(&self) -> &Asn1TimeRef { - unsafe { - Asn1TimeRef::from_ptr(self.0) - } + unsafe { Asn1TimeRef::from_ptr(self.0) } } } diff --git a/openssl/src/bio.rs b/openssl/src/bio.rs index 199fc0c8..5fc4f31f 100644 --- a/openssl/src/bio.rs +++ b/openssl/src/bio.rs @@ -22,9 +22,8 @@ impl<'a> MemBioSlice<'a> { ffi::init(); assert!(buf.len() <= c_int::max_value() as usize); - let bio = unsafe { - try!(cvt_p(BIO_new_mem_buf(buf.as_ptr() as *const _, buf.len() as c_int))) - }; + let bio = + unsafe { try!(cvt_p(BIO_new_mem_buf(buf.as_ptr() as *const _, buf.len() as c_int))) }; Ok(MemBioSlice(bio, PhantomData)) } @@ -48,9 +47,7 @@ impl MemBio { pub fn new() -> Result { ffi::init(); - let bio = unsafe { - try!(cvt_p(ffi::BIO_new(ffi::BIO_s_mem()))) - }; + let bio = unsafe { try!(cvt_p(ffi::BIO_new(ffi::BIO_s_mem()))) }; Ok(MemBio(bio)) } diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs index fb0c286c..78684d0a 100644 --- a/openssl/src/bn.rs +++ b/openssl/src/bn.rs @@ -37,9 +37,7 @@ impl Drop for BnCtx { impl BnCtx { /// Returns a new `BnCtx`. pub fn new() -> Result { - unsafe { - cvt_p(ffi::BN_CTX_new()).map(BnCtx) - } + unsafe { cvt_p(ffi::BN_CTX_new()).map(BnCtx) } } pub fn as_ptr(&self) -> *mut ffi::BN_CTX { @@ -52,9 +50,7 @@ impl BnCtx { a: &BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_mul(r.as_ptr(), a.as_ptr(), b.as_ptr(), self.as_ptr())).map(|_| ()) - } + unsafe { cvt(ffi::BN_mul(r.as_ptr(), a.as_ptr(), b.as_ptr(), self.as_ptr())).map(|_| ()) } } /// Places the result of `a / b` in `dv` and `a mod b` in `rem`. @@ -76,19 +72,16 @@ impl BnCtx { /// Places the result of `a²` in `r`. pub fn sqr(&mut self, r: &mut BigNumRef, a: &BigNumRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_sqr(r.as_ptr(), a.as_ptr(), self.as_ptr())).map(|_| ()) - } + unsafe { cvt(ffi::BN_sqr(r.as_ptr(), a.as_ptr(), self.as_ptr())).map(|_| ()) } } /// Places the result of `a mod m` in `r`. pub fn nnmod(&mut self, r: &mut BigNumRef, a: &BigNumRef, - m: &BigNumRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_nnmod(r.as_ptr(), a.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) - } + m: &BigNumRef) + -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_nnmod(r.as_ptr(), a.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) } } /// Places the result of `(a + b) mod m` in `r`. @@ -131,20 +124,18 @@ impl BnCtx { pub fn mod_sqr(&mut self, r: &mut BigNumRef, a: &BigNumRef, - m: &BigNumRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_mod_sqr(r.as_ptr(), a.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) - } + m: &BigNumRef) + -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_mod_sqr(r.as_ptr(), a.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) } } /// Places the result of `a^p` in `r`. pub fn exp(&mut self, r: &mut BigNumRef, a: &BigNumRef, - p: &BigNumRef) -> Result<(), ErrorStack> { - unsafe{ - cvt(ffi::BN_exp(r.as_ptr(), a.as_ptr(), p.as_ptr(), self.0)).map(|_| ()) - } + p: &BigNumRef) + -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_exp(r.as_ptr(), a.as_ptr(), p.as_ptr(), self.0)).map(|_| ()) } } /// Places the result of `a^p mod m` in `r`. @@ -152,7 +143,8 @@ impl BnCtx { r: &mut BigNumRef, a: &BigNumRef, p: &BigNumRef, - m: &BigNumRef) -> Result<(), ErrorStack> { + m: &BigNumRef) + -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_mod_exp(r.as_ptr(), a.as_ptr(), p.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) } @@ -162,9 +154,11 @@ impl BnCtx { pub fn mod_inverse(&mut self, r: &mut BigNumRef, a: &BigNumRef, - n: &BigNumRef) -> Result<(), ErrorStack> { + n: &BigNumRef) + -> Result<(), ErrorStack> { unsafe { - cvt_p(ffi::BN_mod_inverse(r.as_ptr(), a.as_ptr(), n.as_ptr(), self.as_ptr())).map(|_| ()) + cvt_p(ffi::BN_mod_inverse(r.as_ptr(), a.as_ptr(), n.as_ptr(), self.as_ptr())) + .map(|_| ()) } } @@ -172,10 +166,9 @@ impl BnCtx { pub fn gcd(&mut self, r: &mut BigNumRef, a: &BigNumRef, - b: &BigNumRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_gcd(r.as_ptr(), a.as_ptr(), b.as_ptr(), self.as_ptr())).map(|_| ()) - } + b: &BigNumRef) + -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_gcd(r.as_ptr(), a.as_ptr(), b.as_ptr(), self.as_ptr())).map(|_| ()) } } /// Checks whether `p` is prime. @@ -185,7 +178,8 @@ impl BnCtx { /// Returns `true` if `p` is prime with an error probability of less than `0.25 ^ checks`. pub fn is_prime(&mut self, p: &BigNumRef, checks: i32) -> Result { unsafe { - cvt_n(ffi::BN_is_prime_ex(p.as_ptr(), checks.into(), self.as_ptr(), ptr::null_mut())).map(|r| r != 0) + cvt_n(ffi::BN_is_prime_ex(p.as_ptr(), checks.into(), self.as_ptr(), ptr::null_mut())) + .map(|r| r != 0) } } @@ -201,7 +195,8 @@ impl BnCtx { pub fn is_prime_fasttest(&mut self, p: &BigNumRef, checks: i32, - do_trial_division: bool) -> Result { + do_trial_division: bool) + -> Result { unsafe { cvt_n(ffi::BN_is_prime_fasttest_ex(p.as_ptr(), checks.into(), @@ -236,7 +231,8 @@ impl BnCtx { odd: bool) -> Result<(), ErrorStack> { unsafe { - cvt(ffi::BN_pseudo_rand(r.as_ptr(), bits.into(), prop as c_int, odd as c_int)).map(|_| ()) + cvt(ffi::BN_pseudo_rand(r.as_ptr(), bits.into(), prop as c_int, odd as c_int)) + .map(|_| ()) } } } @@ -259,23 +255,17 @@ impl BigNumRef { /// Adds a `u32` to `self`. pub fn add_word(&mut self, w: u32) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_add_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) - } + unsafe { cvt(ffi::BN_add_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) } } /// Subtracts a `u32` from `self`. pub fn sub_word(&mut self, w: u32) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_sub_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) - } + unsafe { cvt(ffi::BN_sub_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) } } /// Multiplies a `u32` by `self`. pub fn mul_word(&mut self, w: u32) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_mul_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) - } + unsafe { cvt(ffi::BN_mul_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) } } /// Divides `self` by a `u32`, returning the remainder. @@ -305,105 +295,77 @@ impl BigNumRef { /// Places a cryptographically-secure pseudo-random number nonnegative /// number less than `self` in `rnd`. pub fn rand_in_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_rand_range(self.as_ptr(), rnd.as_ptr())).map(|_| ()) - } + unsafe { cvt(ffi::BN_rand_range(self.as_ptr(), rnd.as_ptr())).map(|_| ()) } } /// The cryptographically weak counterpart to `rand_in_range`. pub fn pseudo_rand_in_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_pseudo_rand_range(self.as_ptr(), rnd.as_ptr())).map(|_| ()) - } + unsafe { cvt(ffi::BN_pseudo_rand_range(self.as_ptr(), rnd.as_ptr())).map(|_| ()) } } /// Sets bit `n`. Equivalent to `self |= (1 << n)`. /// /// When setting a bit outside of `self`, it is expanded. pub fn set_bit(&mut self, n: i32) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_set_bit(self.as_ptr(), n.into())).map(|_| ()) - } + unsafe { cvt(ffi::BN_set_bit(self.as_ptr(), n.into())).map(|_| ()) } } /// Clears bit `n`, setting it to 0. Equivalent to `self &= ~(1 << n)`. /// /// When clearing a bit outside of `self`, an error is returned. pub fn clear_bit(&mut self, n: i32) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_clear_bit(self.as_ptr(), n.into())).map(|_| ()) - } + unsafe { cvt(ffi::BN_clear_bit(self.as_ptr(), n.into())).map(|_| ()) } } /// Returns `true` if the `n`th bit of `self` is set to 1, `false` otherwise. pub fn is_bit_set(&self, n: i32) -> bool { - unsafe { - ffi::BN_is_bit_set(self.as_ptr(), n.into()) == 1 - } + unsafe { ffi::BN_is_bit_set(self.as_ptr(), n.into()) == 1 } } /// Truncates `self` to the lowest `n` bits. /// /// An error occurs if `self` is already shorter than `n` bits. pub fn mask_bits(&mut self, n: i32) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_mask_bits(self.as_ptr(), n.into())).map(|_| ()) - } + unsafe { cvt(ffi::BN_mask_bits(self.as_ptr(), n.into())).map(|_| ()) } } /// Places `self << 1` in `r`. pub fn lshift1(&self, r: &mut BigNumRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_lshift1(r.as_ptr(), self.as_ptr())).map(|_| ()) - } + unsafe { cvt(ffi::BN_lshift1(r.as_ptr(), self.as_ptr())).map(|_| ()) } } /// Places `self >> 1` in `r`. pub fn rshift1(&self, r: &mut BigNumRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_rshift1(r.as_ptr(), self.as_ptr())).map(|_| ()) - } + unsafe { cvt(ffi::BN_rshift1(r.as_ptr(), self.as_ptr())).map(|_| ()) } } /// Places `self + b` in `r`. pub fn add(&self, r: &mut BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_add(r.as_ptr(), self.as_ptr(), b.as_ptr())).map(|_| ()) - } + unsafe { cvt(ffi::BN_add(r.as_ptr(), self.as_ptr(), b.as_ptr())).map(|_| ()) } } /// Places `self - b` in `r`. pub fn sub(&self, r: &mut BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_sub(r.as_ptr(), self.as_ptr(), b.as_ptr())).map(|_| ()) - } + unsafe { cvt(ffi::BN_sub(r.as_ptr(), self.as_ptr(), b.as_ptr())).map(|_| ()) } } /// Places `self << n` in `r`. pub fn lshift(&self, r: &mut BigNumRef, b: i32) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_lshift(r.as_ptr(), self.as_ptr(), b.into())).map(|_| ()) - } + unsafe { cvt(ffi::BN_lshift(r.as_ptr(), self.as_ptr(), b.into())).map(|_| ()) } } /// Places `self >> n` in `r`. pub fn rshift(&self, r: &mut BigNumRef, n: i32) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_rshift(r.as_ptr(), self.as_ptr(), n.into())).map(|_| ()) - } + unsafe { cvt(ffi::BN_rshift(r.as_ptr(), self.as_ptr(), n.into())).map(|_| ()) } } pub fn to_owned(&self) -> Result { - unsafe { - cvt_p(ffi::BN_dup(self.as_ptr())).map(|b| BigNum::from_ptr(b)) - } + unsafe { cvt_p(ffi::BN_dup(self.as_ptr())).map(|b| BigNum::from_ptr(b)) } } /// Sets the sign of `self`. pub fn set_negative(&mut self, negative: bool) { - unsafe { - ffi::BN_set_negative(self.as_ptr(), negative as c_int) - } + unsafe { ffi::BN_set_negative(self.as_ptr(), negative as c_int) } } /// Compare the absolute values of `self` and `oth`. @@ -417,9 +379,7 @@ impl BigNumRef { /// assert_eq!(s.ucmp(&o), Ordering::Equal); /// ``` pub fn ucmp(&self, oth: &BigNumRef) -> Ordering { - unsafe { - ffi::BN_ucmp(self.as_ptr(), oth.as_ptr()).cmp(&0) - } + unsafe { ffi::BN_ucmp(self.as_ptr(), oth.as_ptr()).cmp(&0) } } pub fn is_negative(&self) -> bool { @@ -592,7 +552,9 @@ impl BigNum { impl Drop for BigNum { fn drop(&mut self) { - unsafe { ffi::BN_clear_free(self.as_ptr()); } + unsafe { + ffi::BN_clear_free(self.as_ptr()); + } } } @@ -600,17 +562,13 @@ impl Deref for BigNum { type Target = BigNumRef; fn deref(&self) -> &BigNumRef { - unsafe { - BigNumRef::from_ptr(self.0) - } + unsafe { BigNumRef::from_ptr(self.0) } } } impl DerefMut for BigNum { fn deref_mut(&mut self) -> &mut BigNumRef { - unsafe { - BigNumRef::from_ptr_mut(self.0) - } + unsafe { BigNumRef::from_ptr_mut(self.0) } } } diff --git a/openssl/src/dh.rs b/openssl/src/dh.rs index b0c9737b..f2659eb3 100644 --- a/openssl/src/dh.rs +++ b/openssl/src/dh.rs @@ -50,33 +50,25 @@ impl Dh { /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] pub fn get_1024_160() -> Result { - unsafe { - cvt_p(ffi::DH_get_1024_160()).map(Dh) - } + unsafe { cvt_p(ffi::DH_get_1024_160()).map(Dh) } } /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] pub fn get_2048_224() -> Result { - unsafe { - cvt_p(ffi::DH_get_2048_224()).map(Dh) - } + unsafe { cvt_p(ffi::DH_get_2048_224()).map(Dh) } } /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] pub fn get_2048_256() -> Result { - unsafe { - cvt_p(ffi::DH_get_2048_256()).map(Dh) - } + unsafe { cvt_p(ffi::DH_get_2048_256()).map(Dh) } } } impl Drop for Dh { fn drop(&mut self) { - unsafe { - ffi::DH_free(self.0) - } + unsafe { ffi::DH_free(self.0) } } } @@ -84,9 +76,7 @@ impl Deref for Dh { type Target = DhRef; fn deref(&self) -> &DhRef { - unsafe { - DhRef::from_ptr(self.0) - } + unsafe { DhRef::from_ptr(self.0) } } } @@ -104,7 +94,8 @@ mod compat { pub unsafe fn DH_set0_pqg(dh: *mut ffi::DH, p: *mut ffi::BIGNUM, q: *mut ffi::BIGNUM, - g: *mut ffi::BIGNUM) -> c_int { + g: *mut ffi::BIGNUM) + -> c_int { (*dh).p = p; (*dh).q = q; (*dh).g = g; @@ -142,7 +133,7 @@ mod tests { CACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE\ 621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D227\ 6E11715F693877FAD7EF09CADB094AE91E1A1597") - .unwrap(); + .unwrap(); let g = BigNum::from_hex_str("3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0\ BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773\ BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2D\ @@ -152,10 +143,10 @@ mod tests { D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92\ B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148\ D47954515E2327CFEF98C582664B4C0F6CC41659") - .unwrap(); + .unwrap(); let q = BigNum::from_hex_str("8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F\ 5FBD3") - .unwrap(); + .unwrap(); let dh = Dh::from_params(p, g, q).unwrap(); ctx.set_tmp_dh(&dh).unwrap(); } diff --git a/openssl/src/dsa.rs b/openssl/src/dsa.rs index 46bdfaff..9351d852 100644 --- a/openssl/src/dsa.rs +++ b/openssl/src/dsa.rs @@ -105,8 +105,7 @@ impl Dsa { } /// Writes an DSA private key as unencrypted PEM formatted data - pub fn private_key_to_pem(&self) -> Result, ErrorStack> - { + pub fn private_key_to_pem(&self) -> Result, ErrorStack> { assert!(self.has_private_key()); let mem_bio = try!(MemBio::new()); @@ -120,8 +119,7 @@ impl Dsa { } /// Reads an DSA public key from PEM formatted data. - pub fn public_key_from_pem(buf: &[u8]) -> Result - { + pub fn public_key_from_pem(buf: &[u8]) -> Result { ffi::init(); let mem_bio = try!(MemBioSlice::new(buf)); @@ -250,15 +248,16 @@ mod test { let mut password_queried = false; let key = include_bytes!("../test/dsa-encrypted.pem"); Dsa::private_key_from_pem_cb(key, |password| { - password_queried = true; - password[0] = b'm' as c_char; - password[1] = b'y' as c_char; - password[2] = b'p' as c_char; - password[3] = b'a' as c_char; - password[4] = b's' as c_char; - password[5] = b's' as c_char; - 6 - }).unwrap(); + password_queried = true; + password[0] = b'm' as c_char; + password[1] = b'y' as c_char; + password[2] = b'p' as c_char; + password[3] = b'a' as c_char; + password[4] = b's' as c_char; + password[5] = b's' as c_char; + 6 + }) + .unwrap(); assert!(password_queried); } diff --git a/openssl/src/ec_key.rs b/openssl/src/ec_key.rs index 5d634c5a..81b790aa 100644 --- a/openssl/src/ec_key.rs +++ b/openssl/src/ec_key.rs @@ -30,9 +30,7 @@ impl Drop for EcKey { impl EcKey { pub fn new_by_curve_name(nid: Nid) -> Result { - unsafe { - cvt_p(ffi::EC_KEY_new_by_curve_name(nid.as_raw())).map(EcKey) - } + unsafe { cvt_p(ffi::EC_KEY_new_by_curve_name(nid.as_raw())).map(EcKey) } } pub unsafe fn from_ptr(ptr: *mut ffi::EC_KEY) -> EcKey { @@ -44,9 +42,7 @@ impl Deref for EcKey { type Target = EcKeyRef; fn deref(&self) -> &EcKeyRef { - unsafe { - EcKeyRef::from_ptr(self.0) - } + unsafe { EcKeyRef::from_ptr(self.0) } } } diff --git a/openssl/src/hash.rs b/openssl/src/hash.rs index 4093ab79..c91976bf 100644 --- a/openssl/src/hash.rs +++ b/openssl/src/hash.rs @@ -15,45 +15,31 @@ pub struct MessageDigest(*const ffi::EVP_MD); impl MessageDigest { pub fn md5() -> MessageDigest { - unsafe { - MessageDigest(ffi::EVP_md5()) - } + unsafe { MessageDigest(ffi::EVP_md5()) } } pub fn sha1() -> MessageDigest { - unsafe { - MessageDigest(ffi::EVP_sha1()) - } + unsafe { MessageDigest(ffi::EVP_sha1()) } } pub fn sha224() -> MessageDigest { - unsafe { - MessageDigest(ffi::EVP_sha224()) - } + unsafe { MessageDigest(ffi::EVP_sha224()) } } pub fn sha256() -> MessageDigest { - unsafe { - MessageDigest(ffi::EVP_sha256()) - } + unsafe { MessageDigest(ffi::EVP_sha256()) } } pub fn sha384() -> MessageDigest { - unsafe { - MessageDigest(ffi::EVP_sha384()) - } + unsafe { MessageDigest(ffi::EVP_sha384()) } } pub fn sha512() -> MessageDigest { - unsafe { - MessageDigest(ffi::EVP_sha512()) - } + unsafe { MessageDigest(ffi::EVP_sha512()) } } pub fn ripemd160() -> MessageDigest { - unsafe { - MessageDigest(ffi::EVP_ripemd160()) - } + unsafe { MessageDigest(ffi::EVP_ripemd160()) } } pub fn as_ptr(&self) -> *const ffi::EVP_MD { @@ -136,7 +122,9 @@ impl Hasher { } Finalized => (), } - unsafe { try!(cvt(ffi::EVP_DigestInit_ex(self.ctx, self.md, 0 as *mut _))); } + unsafe { + try!(cvt(ffi::EVP_DigestInit_ex(self.ctx, self.md, 0 as *mut _))); + } self.state = Reset; Ok(()) } @@ -239,32 +227,20 @@ mod tests { // Test vectors from http://www.nsrl.nist.gov/testdata/ #[allow(non_upper_case_globals)] - const md5_tests: [(&'static str, &'static str); 13] = [("", - "d41d8cd98f00b204e9800998ecf8427e"), - ("7F", - "83acb6e67e50e31db6ed341dd2de1595"), - ("EC9C", - "0b07f0d4ca797d8ac58874f887cb0b68"), - ("FEE57A", - "e0d583171eb06d56198fc0ef22173907"), - ("42F497E0", - "7c430f178aefdf1487fee7144e9641e2"), - ("C53B777F1C", - "75ef141d64cb37ec423da2d9d440c925"), - ("89D5B576327B", - "ebbaf15eb0ed784c6faa9dc32831bf33"), - ("5D4CCE781EB190", - "ce175c4b08172019f05e6b5279889f2c"), - ("81901FE94932D7B9", - "cd4d2f62b8cdb3a0cf968a735a239281"), - ("C9FFDEE7788EFB4EC9", - "e0841a231ab698db30c6c0f3f246c014"), - ("66AC4B7EBA95E53DC10B", - "a3b3cea71910d9af56742aa0bb2fe329"), - ("A510CD18F7A56852EB0319", - "577e216843dd11573574d3fb209b97d8"), - ("AAED18DBE8938C19ED734A8D", - "6f80fb775f27e0a4ce5c2f42fc72c5f1")]; + const md5_tests: [(&'static str, &'static str); 13] = + [("", "d41d8cd98f00b204e9800998ecf8427e"), + ("7F", "83acb6e67e50e31db6ed341dd2de1595"), + ("EC9C", "0b07f0d4ca797d8ac58874f887cb0b68"), + ("FEE57A", "e0d583171eb06d56198fc0ef22173907"), + ("42F497E0", "7c430f178aefdf1487fee7144e9641e2"), + ("C53B777F1C", "75ef141d64cb37ec423da2d9d440c925"), + ("89D5B576327B", "ebbaf15eb0ed784c6faa9dc32831bf33"), + ("5D4CCE781EB190", "ce175c4b08172019f05e6b5279889f2c"), + ("81901FE94932D7B9", "cd4d2f62b8cdb3a0cf968a735a239281"), + ("C9FFDEE7788EFB4EC9", "e0841a231ab698db30c6c0f3f246c014"), + ("66AC4B7EBA95E53DC10B", "a3b3cea71910d9af56742aa0bb2fe329"), + ("A510CD18F7A56852EB0319", "577e216843dd11573574d3fb209b97d8"), + ("AAED18DBE8938C19ED734A8D", "6f80fb775f27e0a4ce5c2f42fc72c5f1")]; #[test] fn test_md5() { diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index 4212e9de..f335c097 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -63,9 +63,5 @@ pub fn cvt(r: c_int) -> Result { } pub fn cvt_n(r: c_int) -> Result { - if r < 0 { - Err(ErrorStack::get()) - } else { - Ok(r) - } + if r < 0 { Err(ErrorStack::get()) } else { Ok(r) } } diff --git a/openssl/src/nid.rs b/openssl/src/nid.rs index b58e3a3d..afbd60a5 100644 --- a/openssl/src/nid.rs +++ b/openssl/src/nid.rs @@ -254,8 +254,10 @@ pub const SDSICERTIFICATE: Nid = Nid(ffi::NID_sdsiCertificate); pub const X509CRL: Nid = Nid(ffi::NID_x509Crl); pub const PBE_WITHSHA1AND128BITRC4: Nid = Nid(ffi::NID_pbe_WithSHA1And128BitRC4); pub const PBE_WITHSHA1AND40BITRC4: Nid = Nid(ffi::NID_pbe_WithSHA1And40BitRC4); -pub const PBE_WITHSHA1AND3_KEY_TRIPLEDES_CBC: Nid = Nid(ffi::NID_pbe_WithSHA1And3_Key_TripleDES_CBC); -pub const PBE_WITHSHA1AND2_KEY_TRIPLEDES_CBC: Nid = Nid(ffi::NID_pbe_WithSHA1And2_Key_TripleDES_CBC); +pub const PBE_WITHSHA1AND3_KEY_TRIPLEDES_CBC: Nid = + Nid(ffi::NID_pbe_WithSHA1And3_Key_TripleDES_CBC); +pub const PBE_WITHSHA1AND2_KEY_TRIPLEDES_CBC: Nid = + Nid(ffi::NID_pbe_WithSHA1And2_Key_TripleDES_CBC); pub const PBE_WITHSHA1AND128BITRC2_CBC: Nid = Nid(ffi::NID_pbe_WithSHA1And128BitRC2_CBC); pub const PBE_WITHSHA1AND40BITRC2_CBC: Nid = Nid(ffi::NID_pbe_WithSHA1And40BitRC2_CBC); pub const KEYBAG: Nid = Nid(ffi::NID_keyBag); @@ -847,7 +849,8 @@ pub const IPSEC4: Nid = Nid(ffi::NID_ipsec4); pub const WHIRLPOOL: Nid = Nid(ffi::NID_whirlpool); pub const CRYPTOPRO: Nid = Nid(ffi::NID_cryptopro); pub const CRYPTOCOM: Nid = Nid(ffi::NID_cryptocom); -pub const ID_GOSTR3411_94_WITH_GOSTR3410_2001: Nid = Nid(ffi::NID_id_GostR3411_94_with_GostR3410_2001); +pub const ID_GOSTR3411_94_WITH_GOSTR3410_2001: Nid = + Nid(ffi::NID_id_GostR3411_94_with_GostR3410_2001); pub const ID_GOSTR3411_94_WITH_GOSTR3410_94: Nid = Nid(ffi::NID_id_GostR3411_94_with_GostR3410_94); pub const ID_GOSTR3411_94: Nid = Nid(ffi::NID_id_GostR3411_94); pub const ID_HMACGOSTR3411_94: Nid = Nid(ffi::NID_id_HMACGostR3411_94); @@ -859,32 +862,52 @@ pub const ID_GOST28147_89_MAC: Nid = Nid(ffi::NID_id_Gost28147_89_MAC); pub const ID_GOSTR3411_94_PRF: Nid = Nid(ffi::NID_id_GostR3411_94_prf); pub const ID_GOSTR3410_2001DH: Nid = Nid(ffi::NID_id_GostR3410_2001DH); pub const ID_GOSTR3410_94DH: Nid = Nid(ffi::NID_id_GostR3410_94DH); -pub const ID_GOST28147_89_CRYPTOPRO_KEYMESHING: Nid = Nid(ffi::NID_id_Gost28147_89_CryptoPro_KeyMeshing); +pub const ID_GOST28147_89_CRYPTOPRO_KEYMESHING: Nid = + Nid(ffi::NID_id_Gost28147_89_CryptoPro_KeyMeshing); pub const ID_GOST28147_89_NONE_KEYMESHING: Nid = Nid(ffi::NID_id_Gost28147_89_None_KeyMeshing); pub const ID_GOSTR3411_94_TESTPARAMSET: Nid = Nid(ffi::NID_id_GostR3411_94_TestParamSet); pub const ID_GOSTR3411_94_CRYPTOPROPARAMSET: Nid = Nid(ffi::NID_id_GostR3411_94_CryptoProParamSet); pub const ID_GOST28147_89_TESTPARAMSET: Nid = Nid(ffi::NID_id_Gost28147_89_TestParamSet); -pub const ID_GOST28147_89_CRYPTOPRO_A_PARAMSET: Nid = Nid(ffi::NID_id_Gost28147_89_CryptoPro_A_ParamSet); -pub const ID_GOST28147_89_CRYPTOPRO_B_PARAMSET: Nid = Nid(ffi::NID_id_Gost28147_89_CryptoPro_B_ParamSet); -pub const ID_GOST28147_89_CRYPTOPRO_C_PARAMSET: Nid = Nid(ffi::NID_id_Gost28147_89_CryptoPro_C_ParamSet); -pub const ID_GOST28147_89_CRYPTOPRO_D_PARAMSET: Nid = Nid(ffi::NID_id_Gost28147_89_CryptoPro_D_ParamSet); -pub const ID_GOST28147_89_CRYPTOPRO_OSCAR_1_1_PARAMSET: Nid = Nid(ffi::NID_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet); -pub const ID_GOST28147_89_CRYPTOPRO_OSCAR_1_0_PARAMSET: Nid = Nid(ffi::NID_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet); -pub const ID_GOST28147_89_CRYPTOPRO_RIC_1_PARAMSET: Nid = Nid(ffi::NID_id_Gost28147_89_CryptoPro_RIC_1_ParamSet); +pub const ID_GOST28147_89_CRYPTOPRO_A_PARAMSET: Nid = + Nid(ffi::NID_id_Gost28147_89_CryptoPro_A_ParamSet); +pub const ID_GOST28147_89_CRYPTOPRO_B_PARAMSET: Nid = + Nid(ffi::NID_id_Gost28147_89_CryptoPro_B_ParamSet); +pub const ID_GOST28147_89_CRYPTOPRO_C_PARAMSET: Nid = + Nid(ffi::NID_id_Gost28147_89_CryptoPro_C_ParamSet); +pub const ID_GOST28147_89_CRYPTOPRO_D_PARAMSET: Nid = + Nid(ffi::NID_id_Gost28147_89_CryptoPro_D_ParamSet); +pub const ID_GOST28147_89_CRYPTOPRO_OSCAR_1_1_PARAMSET: Nid = + Nid(ffi::NID_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet); +pub const ID_GOST28147_89_CRYPTOPRO_OSCAR_1_0_PARAMSET: Nid = + Nid(ffi::NID_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet); +pub const ID_GOST28147_89_CRYPTOPRO_RIC_1_PARAMSET: Nid = + Nid(ffi::NID_id_Gost28147_89_CryptoPro_RIC_1_ParamSet); pub const ID_GOSTR3410_94_TESTPARAMSET: Nid = Nid(ffi::NID_id_GostR3410_94_TestParamSet); -pub const ID_GOSTR3410_94_CRYPTOPRO_A_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_94_CryptoPro_A_ParamSet); -pub const ID_GOSTR3410_94_CRYPTOPRO_B_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_94_CryptoPro_B_ParamSet); -pub const ID_GOSTR3410_94_CRYPTOPRO_C_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_94_CryptoPro_C_ParamSet); -pub const ID_GOSTR3410_94_CRYPTOPRO_D_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_94_CryptoPro_D_ParamSet); -pub const ID_GOSTR3410_94_CRYPTOPRO_XCHA_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchA_ParamSet); -pub const ID_GOSTR3410_94_CRYPTOPRO_XCHB_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchB_ParamSet); -pub const ID_GOSTR3410_94_CRYPTOPRO_XCHC_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchC_ParamSet); +pub const ID_GOSTR3410_94_CRYPTOPRO_A_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_94_CryptoPro_A_ParamSet); +pub const ID_GOSTR3410_94_CRYPTOPRO_B_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_94_CryptoPro_B_ParamSet); +pub const ID_GOSTR3410_94_CRYPTOPRO_C_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_94_CryptoPro_C_ParamSet); +pub const ID_GOSTR3410_94_CRYPTOPRO_D_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_94_CryptoPro_D_ParamSet); +pub const ID_GOSTR3410_94_CRYPTOPRO_XCHA_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchA_ParamSet); +pub const ID_GOSTR3410_94_CRYPTOPRO_XCHB_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchB_ParamSet); +pub const ID_GOSTR3410_94_CRYPTOPRO_XCHC_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchC_ParamSet); pub const ID_GOSTR3410_2001_TESTPARAMSET: Nid = Nid(ffi::NID_id_GostR3410_2001_TestParamSet); -pub const ID_GOSTR3410_2001_CRYPTOPRO_A_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_2001_CryptoPro_A_ParamSet); -pub const ID_GOSTR3410_2001_CRYPTOPRO_B_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_2001_CryptoPro_B_ParamSet); -pub const ID_GOSTR3410_2001_CRYPTOPRO_C_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_2001_CryptoPro_C_ParamSet); -pub const ID_GOSTR3410_2001_CRYPTOPRO_XCHA_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet); -pub const ID_GOSTR3410_2001_CRYPTOPRO_XCHB_PARAMSET: Nid = Nid(ffi::NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet); +pub const ID_GOSTR3410_2001_CRYPTOPRO_A_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_2001_CryptoPro_A_ParamSet); +pub const ID_GOSTR3410_2001_CRYPTOPRO_B_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_2001_CryptoPro_B_ParamSet); +pub const ID_GOSTR3410_2001_CRYPTOPRO_C_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_2001_CryptoPro_C_ParamSet); +pub const ID_GOSTR3410_2001_CRYPTOPRO_XCHA_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet); +pub const ID_GOSTR3410_2001_CRYPTOPRO_XCHB_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet); pub const ID_GOSTR3410_94_A: Nid = Nid(ffi::NID_id_GostR3410_94_a); pub const ID_GOSTR3410_94_ABIS: Nid = Nid(ffi::NID_id_GostR3410_94_aBis); pub const ID_GOSTR3410_94_B: Nid = Nid(ffi::NID_id_GostR3410_94_b); @@ -892,8 +915,10 @@ pub const ID_GOSTR3410_94_BBIS: Nid = Nid(ffi::NID_id_GostR3410_94_bBis); pub const ID_GOST28147_89_CC: Nid = Nid(ffi::NID_id_Gost28147_89_cc); pub const ID_GOSTR3410_94_CC: Nid = Nid(ffi::NID_id_GostR3410_94_cc); pub const ID_GOSTR3410_2001_CC: Nid = Nid(ffi::NID_id_GostR3410_2001_cc); -pub const ID_GOSTR3411_94_WITH_GOSTR3410_94_CC: Nid = Nid(ffi::NID_id_GostR3411_94_with_GostR3410_94_cc); -pub const ID_GOSTR3411_94_WITH_GOSTR3410_2001_CC: Nid = Nid(ffi::NID_id_GostR3411_94_with_GostR3410_2001_cc); +pub const ID_GOSTR3411_94_WITH_GOSTR3410_94_CC: Nid = + Nid(ffi::NID_id_GostR3411_94_with_GostR3410_94_cc); +pub const ID_GOSTR3411_94_WITH_GOSTR3410_2001_CC: Nid = + Nid(ffi::NID_id_GostR3411_94_with_GostR3410_2001_cc); pub const ID_GOSTR3410_2001_PARAMSET_CC: Nid = Nid(ffi::NID_id_GostR3410_2001_ParamSet_cc); pub const CAMELLIA_128_CBC: Nid = Nid(ffi::NID_camellia_128_cbc); pub const CAMELLIA_192_CBC: Nid = Nid(ffi::NID_camellia_192_cbc); @@ -927,4 +952,3 @@ pub const RC4_HMAC_MD5: Nid = Nid(ffi::NID_rc4_hmac_md5); pub const AES_128_CBC_HMAC_SHA1: Nid = Nid(ffi::NID_aes_128_cbc_hmac_sha1); pub const AES_192_CBC_HMAC_SHA1: Nid = Nid(ffi::NID_aes_192_cbc_hmac_sha1); pub const AES_256_CBC_HMAC_SHA1: Nid = Nid(ffi::NID_aes_256_cbc_hmac_sha1); - diff --git a/openssl/src/pkcs12.rs b/openssl/src/pkcs12.rs index d5d4750a..ab0934a8 100644 --- a/openssl/src/pkcs12.rs +++ b/openssl/src/pkcs12.rs @@ -16,7 +16,9 @@ pub struct Pkcs12(*mut ffi::PKCS12); impl Drop for Pkcs12 { fn drop(&mut self) { - unsafe { ffi::PKCS12_free(self.0); } + unsafe { + ffi::PKCS12_free(self.0); + } } } @@ -88,8 +90,7 @@ mod compat { (*stack).num } - pub unsafe fn OPENSSL_sk_value(stack: *const ffi::_STACK, idx: c_int) - -> *mut c_void { + pub unsafe fn OPENSSL_sk_value(stack: *const ffi::_STACK, idx: c_int) -> *mut c_void { *(*stack).data.offset(idx as isize) as *mut c_void } } diff --git a/openssl/src/pkcs5.rs b/openssl/src/pkcs5.rs index b0c899e5..8d6dcce8 100644 --- a/openssl/src/pkcs5.rs +++ b/openssl/src/pkcs5.rs @@ -112,7 +112,12 @@ mod tests { &[0x55_u8, 0xac_u8, 0x04_u8, 0x6e_u8, 0x56_u8, 0xe3_u8, 0x08_u8, 0x9f_u8, 0xec_u8, 0x16_u8, 0x91_u8, 0xc2_u8, 0x25_u8, 0x44_u8, 0xb6_u8, 0x05_u8][..]); - super::pbkdf2_hmac(b"Password", b"NaCl", 80000, MessageDigest::sha256(), &mut buf).unwrap(); + super::pbkdf2_hmac(b"Password", + b"NaCl", + 80000, + MessageDigest::sha256(), + &mut buf) + .unwrap(); assert_eq!(buf, &[0x4d_u8, 0xdc_u8, 0xd8_u8, 0xf6_u8, 0x0b_u8, 0x98_u8, 0xbe_u8, 0x21_u8, 0x83_u8, 0x0c_u8, 0xee_u8, 0x5e_u8, 0xf2_u8, 0x27_u8, 0x01_u8, 0xf9_u8][..]); @@ -135,7 +140,12 @@ mod tests { 0x60_u8, 0x60_u8, 0xa0_u8, 0x9f_u8, 0x76_u8, 0x41_u8, 0x5e_u8, 0x9f_u8, 0x71_u8, 0xea_u8, 0x47_u8, 0xf9_u8, 0xe9_u8, 0x06_u8, 0x43_u8, 0x06_u8][..]); - super::pbkdf2_hmac(b"pass\0word", b"sa\0lt", 1, MessageDigest::sha512(), &mut buf).unwrap(); + super::pbkdf2_hmac(b"pass\0word", + b"sa\0lt", + 1, + MessageDigest::sha512(), + &mut buf) + .unwrap(); assert_eq!(&buf[..], &[0x71_u8, 0xa0_u8, 0xec_u8, 0x84_u8, 0x2a_u8, 0xbd_u8, 0x5c_u8, 0x67_u8, 0x8b_u8, 0xcf_u8, 0xd1_u8, 0x45_u8, 0xf0_u8, 0x9d_u8, 0x83_u8, 0x52_u8, @@ -150,7 +160,8 @@ mod tests { b"salt\0\0\0", 50, MessageDigest::sha512(), - &mut buf).unwrap(); + &mut buf) + .unwrap(); assert_eq!(&buf[..], &[0x01_u8, 0x68_u8, 0x71_u8, 0xa4_u8, 0xc4_u8, 0xb7_u8, 0x5f_u8, 0x96_u8, 0x85_u8, 0x7f_u8, 0xd2_u8, 0xb9_u8, 0xf8_u8, 0xca_u8, 0x28_u8, 0x02_u8, diff --git a/openssl/src/pkey.rs b/openssl/src/pkey.rs index 4cbfcce7..fc48c8b4 100644 --- a/openssl/src/pkey.rs +++ b/openssl/src/pkey.rs @@ -178,9 +178,7 @@ impl Deref for PKey { type Target = PKeyRef; fn deref(&self) -> &PKeyRef { - unsafe { - PKeyRef::from_ptr(self.0) - } + unsafe { PKeyRef::from_ptr(self.0) } } } diff --git a/openssl/src/rsa.rs b/openssl/src/rsa.rs index e63e567d..666b99dd 100644 --- a/openssl/src/rsa.rs +++ b/openssl/src/rsa.rs @@ -178,7 +178,7 @@ impl Rsa { to.as_mut_ptr(), self.0, padding.0))); - Ok(len as usize) + Ok(len as usize) } } @@ -203,7 +203,7 @@ impl Rsa { to.as_mut_ptr(), self.0, padding.0))); - Ok(len as usize) + Ok(len as usize) } } @@ -338,23 +338,19 @@ mod compat { [p, q] } - pub unsafe fn set_key(r: *mut RSA, - n: *mut BIGNUM, - e: *mut BIGNUM, - d: *mut BIGNUM) -> c_int { + pub unsafe fn set_key(r: *mut RSA, n: *mut BIGNUM, e: *mut BIGNUM, d: *mut BIGNUM) -> c_int { ffi::RSA_set0_key(r, n, e, d) } - pub unsafe fn set_factors(r: *mut RSA, - p: *mut BIGNUM, - q: *mut BIGNUM) -> c_int { + pub unsafe fn set_factors(r: *mut RSA, p: *mut BIGNUM, q: *mut BIGNUM) -> c_int { ffi::RSA_set0_factors(r, p, q) } pub unsafe fn set_crt_params(r: *mut RSA, dmp1: *mut BIGNUM, dmq1: *mut BIGNUM, - iqmp: *mut BIGNUM) -> c_int { + iqmp: *mut BIGNUM) + -> c_int { ffi::RSA_set0_crt_params(r, dmp1, dmq1, iqmp) } } @@ -372,19 +368,14 @@ mod compat { [(*r).p, (*r).q] } - pub unsafe fn set_key(r: *mut RSA, - n: *mut BIGNUM, - e: *mut BIGNUM, - d: *mut BIGNUM) -> c_int { + pub unsafe fn set_key(r: *mut RSA, n: *mut BIGNUM, e: *mut BIGNUM, d: *mut BIGNUM) -> c_int { (*r).n = n; (*r).e = e; (*r).d = d; 1 // TODO: is this right? should it be 0? what's success? } - pub unsafe fn set_factors(r: *mut RSA, - p: *mut BIGNUM, - q: *mut BIGNUM) -> c_int { + pub unsafe fn set_factors(r: *mut RSA, p: *mut BIGNUM, q: *mut BIGNUM) -> c_int { (*r).p = p; (*r).q = q; 1 // TODO: is this right? should it be 0? what's success? @@ -393,7 +384,8 @@ mod compat { pub unsafe fn set_crt_params(r: *mut RSA, dmp1: *mut BIGNUM, dmq1: *mut BIGNUM, - iqmp: *mut BIGNUM) -> c_int { + iqmp: *mut BIGNUM) + -> c_int { (*r).dmp1 = dmp1; (*r).dmq1 = dmq1; (*r).iqmp = iqmp; @@ -413,15 +405,16 @@ mod test { let mut password_queried = false; let key = include_bytes!("../test/rsa-encrypted.pem"); Rsa::private_key_from_pem_cb(key, |password| { - password_queried = true; - password[0] = b'm' as c_char; - password[1] = b'y' as c_char; - password[2] = b'p' as c_char; - password[3] = b'a' as c_char; - password[4] = b's' as c_char; - password[5] = b's' as c_char; - 6 - }).unwrap(); + password_queried = true; + password[0] = b'm' as c_char; + password[1] = b'y' as c_char; + password[2] = b'p' as c_char; + password[3] = b'a' as c_char; + password[4] = b's' as c_char; + password[5] = b's' as c_char; + 6 + }) + .unwrap(); assert!(password_queried); } @@ -441,11 +434,11 @@ mod test { let mut dec_result = vec![0; private_key.size()]; let len = private_key.private_decrypt(&result, &mut dec_result, PKCS1_PADDING).unwrap(); - assert_eq!(&dec_result[..len], original_data); + assert_eq!(&dec_result[..len], original_data); } #[test] - fn test_private_encrypt() { + fn test_private_encrypt() { let k0 = super::Rsa::generate(512).unwrap(); let k0pkey = k0.public_key_to_pem().unwrap(); let k1 = super::Rsa::public_key_from_pem(&k0pkey).unwrap(); @@ -457,21 +450,21 @@ mod test { let mut dmesg = vec![0; k1.size()]; let len = k1.public_decrypt(&emesg, &mut dmesg, PKCS1_PADDING).unwrap(); assert_eq!(msg, &dmesg[..len]); - } + } - #[test] - fn test_public_encrypt() { - let k0 = super::Rsa::generate(512).unwrap(); - let k0pkey = k0.private_key_to_pem().unwrap(); - let k1 = super::Rsa::private_key_from_pem(&k0pkey).unwrap(); + #[test] + fn test_public_encrypt() { + let k0 = super::Rsa::generate(512).unwrap(); + let k0pkey = k0.private_key_to_pem().unwrap(); + let k1 = super::Rsa::private_key_from_pem(&k0pkey).unwrap(); - let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; + let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; - let mut emesg = vec![0; k0.size()]; - k0.public_encrypt(&msg, &mut emesg, PKCS1_PADDING).unwrap(); - let mut dmesg = vec![0; k1.size()]; - let len = k1.private_decrypt(&emesg, &mut dmesg, PKCS1_PADDING).unwrap(); - assert_eq!(msg, &dmesg[..len]); - } + let mut emesg = vec![0; k0.size()]; + k0.public_encrypt(&msg, &mut emesg, PKCS1_PADDING).unwrap(); + let mut dmesg = vec![0; k1.size()]; + let len = k1.private_decrypt(&emesg, &mut dmesg, PKCS1_PADDING).unwrap(); + assert_eq!(msg, &dmesg[..len]); + } } diff --git a/openssl/src/sign.rs b/openssl/src/sign.rs index a1a37ce6..eeee5cc7 100644 --- a/openssl/src/sign.rs +++ b/openssl/src/sign.rs @@ -166,9 +166,7 @@ impl<'a> Verifier<'a> { pub fn finish(&self, signature: &[u8]) -> Result { unsafe { - let r = EVP_DigestVerifyFinal(self.0, - signature.as_ptr() as *const _, - signature.len()); + let r = EVP_DigestVerifyFinal(self.0, signature.as_ptr() as *const _, signature.len()); match r { 1 => Ok(true), 0 => { @@ -199,7 +197,8 @@ use ffi::EVP_DigestVerifyFinal; #[allow(bad_style)] unsafe fn EVP_DigestVerifyFinal(ctx: *mut ffi::EVP_MD_CTX, sigret: *const ::libc::c_uchar, - siglen: ::libc::size_t) -> ::libc::c_int { + siglen: ::libc::size_t) + -> ::libc::c_int { ffi::EVP_DigestVerifyFinal(ctx, sigret as *mut _, siglen) } @@ -216,27 +215,27 @@ mod test { static INPUT: &'static [u8] = &[101, 121, 74, 104, 98, 71, 99, 105, 79, 105, 74, 83, 85, 122, 73, 49, 78, 105, 74, 57, - 46, 101, 121, 74, 112, 99, 51, 77, 105, 79, 105, 74, 113, 98, 50, 85, 105, 76, 65, 48, - 75, 73, 67, 74, 108, 101, 72, 65, 105, 79, 106, 69, 122, 77, 68, 65, 52, 77, 84, 107, - 122, 79, 68, 65, 115, 68, 81, 111, 103, 73, 109, 104, 48, 100, 72, 65, 54, 76, 121, - 57, 108, 101, 71, 70, 116, 99, 71, 120, 108, 76, 109, 78, 118, 98, 83, 57, 112, 99, - 49, 57, 121, 98, 50, 57, 48, 73, 106, 112, 48, 99, 110, 86, 108, 102, 81]; + 46, 101, 121, 74, 112, 99, 51, 77, 105, 79, 105, 74, 113, 98, 50, 85, 105, 76, 65, 48, + 75, 73, 67, 74, 108, 101, 72, 65, 105, 79, 106, 69, 122, 77, 68, 65, 52, 77, 84, 107, + 122, 79, 68, 65, 115, 68, 81, 111, 103, 73, 109, 104, 48, 100, 72, 65, 54, 76, 121, 57, + 108, 101, 71, 70, 116, 99, 71, 120, 108, 76, 109, 78, 118, 98, 83, 57, 112, 99, 49, 57, + 121, 98, 50, 57, 48, 73, 106, 112, 48, 99, 110, 86, 108, 102, 81]; static SIGNATURE: &'static [u8] = &[112, 46, 33, 137, 67, 232, 143, 209, 30, 181, 216, 45, 191, 120, 69, 243, 65, 6, 174, - 27, 129, 255, 247, 115, 17, 22, 173, 209, 113, 125, 131, 101, 109, 66, 10, 253, 60, - 150, 238, 221, 115, 162, 102, 62, 81, 102, 104, 123, 0, 11, 135, 34, 110, 1, 135, 237, - 16, 115, 249, 69, 229, 130, 173, 252, 239, 22, 216, 90, 121, 142, 232, 198, 109, 219, - 61, 184, 151, 91, 23, 208, 148, 2, 190, 237, 213, 217, 217, 112, 7, 16, 141, 178, 129, - 96, 213, 248, 4, 12, 167, 68, 87, 98, 184, 31, 190, 127, 249, 217, 46, 10, 231, 111, - 36, 242, 91, 51, 187, 230, 244, 74, 230, 30, 177, 4, 10, 203, 32, 4, 77, 62, 249, 18, - 142, 212, 1, 48, 121, 91, 212, 189, 59, 65, 238, 202, 208, 102, 171, 101, 25, 129, - 253, 228, 141, 247, 127, 55, 45, 195, 139, 159, 175, 221, 59, 239, 177, 139, 93, 163, - 204, 60, 46, 176, 47, 158, 58, 65, 214, 18, 202, 173, 21, 145, 18, 115, 160, 95, 35, - 185, 232, 56, 250, 175, 132, 157, 105, 132, 41, 239, 90, 30, 136, 121, 130, 54, 195, - 212, 14, 96, 69, 34, 165, 68, 200, 242, 122, 122, 45, 184, 6, 99, 209, 108, 247, 202, - 234, 86, 222, 64, 92, 178, 33, 90, 69, 178, 194, 85, 102, 181, 90, 193, 167, 72, 160, - 112, 223, 200, 163, 42, 70, 149, 67, 208, 25, 238, 251, 71]; + 27, 129, 255, 247, 115, 17, 22, 173, 209, 113, 125, 131, 101, 109, 66, 10, 253, 60, 150, + 238, 221, 115, 162, 102, 62, 81, 102, 104, 123, 0, 11, 135, 34, 110, 1, 135, 237, 16, + 115, 249, 69, 229, 130, 173, 252, 239, 22, 216, 90, 121, 142, 232, 198, 109, 219, 61, + 184, 151, 91, 23, 208, 148, 2, 190, 237, 213, 217, 217, 112, 7, 16, 141, 178, 129, 96, + 213, 248, 4, 12, 167, 68, 87, 98, 184, 31, 190, 127, 249, 217, 46, 10, 231, 111, 36, + 242, 91, 51, 187, 230, 244, 74, 230, 30, 177, 4, 10, 203, 32, 4, 77, 62, 249, 18, 142, + 212, 1, 48, 121, 91, 212, 189, 59, 65, 238, 202, 208, 102, 171, 101, 25, 129, 253, 228, + 141, 247, 127, 55, 45, 195, 139, 159, 175, 221, 59, 239, 177, 139, 93, 163, 204, 60, 46, + 176, 47, 158, 58, 65, 214, 18, 202, 173, 21, 145, 18, 115, 160, 95, 35, 185, 232, 56, + 250, 175, 132, 157, 105, 132, 41, 239, 90, 30, 136, 121, 130, 54, 195, 212, 14, 96, 69, + 34, 165, 68, 200, 242, 122, 122, 45, 184, 6, 99, 209, 108, 247, 202, 234, 86, 222, 64, + 92, 178, 33, 90, 69, 178, 194, 85, 102, 181, 90, 193, 167, 72, 160, 112, 223, 200, 163, + 42, 70, 149, 67, 208, 25, 238, 251, 71]; #[test] fn rsa_sign() { @@ -320,7 +319,7 @@ mod test { verifier.update(&input).unwrap(); match verifier.finish(&sig) { Ok(true) => panic!("unexpected success"), - Ok(false) | Err(_) => {}, + Ok(false) | Err(_) => {} } } @@ -337,29 +336,29 @@ mod test { fn hmac_md5() { // test vectors from RFC 2202 let tests: [(Vec, Vec, Vec); 7] = - [(iter::repeat(0x0b_u8).take(16).collect(), - b"Hi There".to_vec(), - "9294727a3638bb1c13f48ef8158bfc9d".from_hex().unwrap()), - (b"Jefe".to_vec(), - b"what do ya want for nothing?".to_vec(), - "750c783e6ab0b503eaa86e310a5db738".from_hex().unwrap()), - (iter::repeat(0xaa_u8).take(16).collect(), - iter::repeat(0xdd_u8).take(50).collect(), - "56be34521d144c88dbb8c733f0e8b3f6".from_hex().unwrap()), - ("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(), - iter::repeat(0xcd_u8).take(50).collect(), - "697eaf0aca3a3aea3a75164746ffaa79".from_hex().unwrap()), - (iter::repeat(0x0c_u8).take(16).collect(), - b"Test With Truncation".to_vec(), - "56461ef2342edc00f9bab995690efd4c".from_hex().unwrap()), - (iter::repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(), - "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()), - (iter::repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key \ + [(iter::repeat(0x0b_u8).take(16).collect(), + b"Hi There".to_vec(), + "9294727a3638bb1c13f48ef8158bfc9d".from_hex().unwrap()), + (b"Jefe".to_vec(), + b"what do ya want for nothing?".to_vec(), + "750c783e6ab0b503eaa86e310a5db738".from_hex().unwrap()), + (iter::repeat(0xaa_u8).take(16).collect(), + iter::repeat(0xdd_u8).take(50).collect(), + "56be34521d144c88dbb8c733f0e8b3f6".from_hex().unwrap()), + ("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(), + iter::repeat(0xcd_u8).take(50).collect(), + "697eaf0aca3a3aea3a75164746ffaa79".from_hex().unwrap()), + (iter::repeat(0x0c_u8).take(16).collect(), + b"Test With Truncation".to_vec(), + "56461ef2342edc00f9bab995690efd4c".from_hex().unwrap()), + (iter::repeat(0xaa_u8).take(80).collect(), + b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(), + "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()), + (iter::repeat(0xaa_u8).take(80).collect(), + b"Test Using Larger Than Block-Size Key \ and Larger Than One Block-Size Data" .to_vec(), - "6f630fad67cda0ee1fb1f562db3aa53e".from_hex().unwrap())]; + "6f630fad67cda0ee1fb1f562db3aa53e".from_hex().unwrap())]; test_hmac(MessageDigest::md5(), &tests); } @@ -368,29 +367,29 @@ mod test { fn hmac_sha1() { // test vectors from RFC 2202 let tests: [(Vec, Vec, Vec); 7] = - [(iter::repeat(0x0b_u8).take(20).collect(), - b"Hi There".to_vec(), - "b617318655057264e28bc0b6fb378c8ef146be00".from_hex().unwrap()), - (b"Jefe".to_vec(), - b"what do ya want for nothing?".to_vec(), - "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79".from_hex().unwrap()), - (iter::repeat(0xaa_u8).take(20).collect(), - iter::repeat(0xdd_u8).take(50).collect(), - "125d7342b9ac11cd91a39af48aa17b4f63f175d3".from_hex().unwrap()), - ("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(), - iter::repeat(0xcd_u8).take(50).collect(), - "4c9007f4026250c6bc8414f9bf50c86c2d7235da".from_hex().unwrap()), - (iter::repeat(0x0c_u8).take(20).collect(), - b"Test With Truncation".to_vec(), - "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04".from_hex().unwrap()), - (iter::repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(), - "aa4ae5e15272d00e95705637ce8a3b55ed402112".from_hex().unwrap()), - (iter::repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key \ + [(iter::repeat(0x0b_u8).take(20).collect(), + b"Hi There".to_vec(), + "b617318655057264e28bc0b6fb378c8ef146be00".from_hex().unwrap()), + (b"Jefe".to_vec(), + b"what do ya want for nothing?".to_vec(), + "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79".from_hex().unwrap()), + (iter::repeat(0xaa_u8).take(20).collect(), + iter::repeat(0xdd_u8).take(50).collect(), + "125d7342b9ac11cd91a39af48aa17b4f63f175d3".from_hex().unwrap()), + ("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(), + iter::repeat(0xcd_u8).take(50).collect(), + "4c9007f4026250c6bc8414f9bf50c86c2d7235da".from_hex().unwrap()), + (iter::repeat(0x0c_u8).take(20).collect(), + b"Test With Truncation".to_vec(), + "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04".from_hex().unwrap()), + (iter::repeat(0xaa_u8).take(80).collect(), + b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(), + "aa4ae5e15272d00e95705637ce8a3b55ed402112".from_hex().unwrap()), + (iter::repeat(0xaa_u8).take(80).collect(), + b"Test Using Larger Than Block-Size Key \ and Larger Than One Block-Size Data" .to_vec(), - "e8e99d0f45237d786d6bbaa7965c7808bbff1a91".from_hex().unwrap())]; + "e8e99d0f45237d786d6bbaa7965c7808bbff1a91".from_hex().unwrap())]; test_hmac(MessageDigest::sha1(), &tests); } diff --git a/openssl/src/ssl/bio.rs b/openssl/src/ssl/bio.rs index a0215c2f..486b4dba 100644 --- a/openssl/src/ssl/bio.rs +++ b/openssl/src/ssl/bio.rs @@ -1,6 +1,6 @@ use libc::{c_char, c_int, c_long, c_void, strlen}; -use ffi::{BIO, BIO_CTRL_FLUSH, BIO_new, BIO_clear_retry_flags, - BIO_set_retry_read, BIO_set_retry_write}; +use ffi::{BIO, BIO_CTRL_FLUSH, BIO_new, BIO_clear_retry_flags, BIO_set_retry_read, + BIO_set_retry_write}; use std::any::Any; use std::io; use std::io::prelude::*; @@ -76,7 +76,7 @@ fn catch_unwind(f: F) -> Result> ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(f)) } -unsafe extern fn bwrite(bio: *mut BIO, buf: *const c_char, len: c_int) -> c_int { +unsafe extern "C" fn bwrite(bio: *mut BIO, buf: *const c_char, len: c_int) -> c_int { BIO_clear_retry_flags(bio); let state = state::(bio); @@ -98,7 +98,7 @@ unsafe extern fn bwrite(bio: *mut BIO, buf: *const c_char, len: c_int) } } -unsafe extern fn bread(bio: *mut BIO, buf: *mut c_char, len: c_int) -> c_int { +unsafe extern "C" fn bread(bio: *mut BIO, buf: *mut c_char, len: c_int) -> c_int { BIO_clear_retry_flags(bio); let state = state::(bio); @@ -128,15 +128,15 @@ fn retriable_error(err: &io::Error) -> bool { } } -unsafe extern fn bputs(bio: *mut BIO, s: *const c_char) -> c_int { +unsafe extern "C" fn bputs(bio: *mut BIO, s: *const c_char) -> c_int { bwrite::(bio, s, strlen(s) as c_int) } -unsafe extern fn ctrl(bio: *mut BIO, - cmd: c_int, - _num: c_long, - _ptr: *mut c_void) - -> c_long { +unsafe extern "C" fn ctrl(bio: *mut BIO, + cmd: c_int, + _num: c_long, + _ptr: *mut c_void) + -> c_long { if cmd == BIO_CTRL_FLUSH { let state = state::(bio); @@ -156,7 +156,7 @@ unsafe extern fn ctrl(bio: *mut BIO, } } -unsafe extern fn create(bio: *mut BIO) -> c_int { +unsafe extern "C" fn create(bio: *mut BIO) -> c_int { compat::BIO_set_init(bio, 0); compat::BIO_set_num(bio, 0); compat::BIO_set_data(bio, ptr::null_mut()); @@ -164,7 +164,7 @@ unsafe extern fn create(bio: *mut BIO) -> c_int { 1 } -unsafe extern fn destroy(bio: *mut BIO) -> c_int { +unsafe extern "C" fn destroy(bio: *mut BIO) -> c_int { if bio.is_null() { return 0; } @@ -193,8 +193,7 @@ mod compat { impl BIO_METHOD { pub fn new() -> BIO_METHOD { unsafe { - let ptr = ffi::BIO_meth_new(ffi::BIO_TYPE_NONE, - b"rust\0".as_ptr() as *const _); + let ptr = ffi::BIO_meth_new(ffi::BIO_TYPE_NONE, b"rust\0".as_ptr() as *const _); assert!(!ptr.is_null()); let ret = BIO_METHOD(ptr); assert!(ffi::BIO_meth_set_write(ptr, super::bwrite::) != 0); @@ -203,7 +202,7 @@ mod compat { assert!(ffi::BIO_meth_set_ctrl(ptr, super::ctrl::) != 0); assert!(ffi::BIO_meth_set_create(ptr, super::create) != 0); assert!(ffi::BIO_meth_set_destroy(ptr, super::destroy::) != 0); - return ret + return ret; } } diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index f89acf1e..bea54a4e 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -118,7 +118,7 @@ impl ServerConnectorBuilder { { let mut ctx = try!(ctx(method)); ctx.set_options(ssl::SSL_OP_SINGLE_DH_USE | ssl::SSL_OP_SINGLE_ECDH_USE | - ssl::SSL_OP_CIPHER_SERVER_PREFERENCE); + ssl::SSL_OP_CIPHER_SERVER_PREFERENCE); let dh = try!(Dh::from_pem(DHPARAM_PEM.as_bytes())); try!(ctx.set_tmp_dh(&dh)); try!(setup_curves(&mut ctx)); @@ -168,7 +168,7 @@ impl ServerConnectorBuilder { chain: I) -> Result where I: IntoIterator, - I::Item: AsRef + I::Item: AsRef { try!(ctx.set_private_key(private_key)); try!(ctx.set_certificate(certificate)); @@ -238,7 +238,8 @@ fn setup_verify(ssl: &mut Ssl, domain: &str) -> Result<(), ErrorStack> { #[cfg(not(any(ossl102, ossl110)))] fn setup_verify(ssl: &mut Ssl, domain: &str) -> Result<(), ErrorStack> { let domain = domain.to_owned(); - ssl.set_verify_callback(SSL_VERIFY_PEER, move |p, x| verify::verify_callback(&domain, p, x)); + ssl.set_verify_callback(SSL_VERIFY_PEER, + move |p, x| verify::verify_callback(&domain, p, x)); Ok(()) } diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 802ce8f0..c1630996 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -221,12 +221,12 @@ lazy_static! { static ref ALPN_PROTOS_IDX: c_int = get_new_idx::>(); } -unsafe extern fn free_data_box(_parent: *mut c_void, - ptr: *mut c_void, - _ad: *mut ffi::CRYPTO_EX_DATA, - _idx: c_int, - _argl: c_long, - _argp: *mut c_void) { +unsafe extern "C" fn free_data_box(_parent: *mut c_void, + ptr: *mut c_void, + _ad: *mut ffi::CRYPTO_EX_DATA, + _idx: c_int, + _argl: c_long, + _argp: *mut c_void) { if !ptr.is_null() { Box::::from_raw(ptr as *mut T); } @@ -250,7 +250,7 @@ fn get_new_ssl_idx() -> c_int { } } -extern fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int +extern "C" fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int where F: Fn(bool, &X509StoreContextRef) -> bool + Any + 'static + Sync + Send { unsafe { @@ -266,14 +266,13 @@ extern fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) } } -extern fn ssl_raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int +extern "C" fn ssl_raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int where F: Fn(bool, &X509StoreContextRef) -> bool + Any + 'static + Sync + Send { unsafe { let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx(); let ssl = ffi::X509_STORE_CTX_get_ex_data(x509_ctx, idx); - let verify = ffi::SSL_get_ex_data(ssl as *const _, - get_ssl_verify_data_idx::()); + let verify = ffi::SSL_get_ex_data(ssl as *const _, get_ssl_verify_data_idx::()); let verify: &F = &*(verify as *mut F); let ctx = X509StoreContextRef::from_ptr(x509_ctx); @@ -282,7 +281,7 @@ extern fn ssl_raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_ } } -extern fn raw_sni(ssl: *mut ffi::SSL, al: *mut c_int, _arg: *mut c_void) -> c_int +extern "C" fn raw_sni(ssl: *mut ffi::SSL, al: *mut c_int, _arg: *mut c_void) -> c_int where F: Fn(&mut SslRef) -> Result<(), SniError> + Any + 'static + Sync + Send { unsafe { @@ -338,24 +337,24 @@ unsafe fn select_proto_using(ssl: *mut ffi::SSL, /// supported by the server. It achieves this by delegating to the `SSL_select_next_proto` /// function. The list of protocols supported by the client is found in the extra data of the /// OpenSSL context. -extern fn raw_next_proto_select_cb(ssl: *mut ffi::SSL, - out: *mut *mut c_uchar, - outlen: *mut c_uchar, - inbuf: *const c_uchar, - inlen: c_uint, - _arg: *mut c_void) - -> c_int { +extern "C" fn raw_next_proto_select_cb(ssl: *mut ffi::SSL, + out: *mut *mut c_uchar, + outlen: *mut c_uchar, + inbuf: *const c_uchar, + inlen: c_uint, + _arg: *mut c_void) + -> c_int { unsafe { select_proto_using(ssl, out, outlen, inbuf, inlen, *NPN_PROTOS_IDX) } } #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -extern fn raw_alpn_select_cb(ssl: *mut ffi::SSL, - out: *mut *const c_uchar, - outlen: *mut c_uchar, - inbuf: *const c_uchar, - inlen: c_uint, - _arg: *mut c_void) - -> c_int { +extern "C" fn raw_alpn_select_cb(ssl: *mut ffi::SSL, + out: *mut *const c_uchar, + outlen: *mut c_uchar, + inbuf: *const c_uchar, + inlen: c_uint, + _arg: *mut c_void) + -> c_int { unsafe { select_proto_using(ssl, out as *mut _, outlen, inbuf, inlen, *ALPN_PROTOS_IDX) } } @@ -366,11 +365,11 @@ extern fn raw_alpn_select_cb(ssl: *mut ffi::SSL, /// that it supports. /// The list of supported protocols is found in the extra data of the OpenSSL /// context. -extern fn raw_next_protos_advertise_cb(ssl: *mut ffi::SSL, - out: *mut *const c_uchar, - outlen: *mut c_uint, - _arg: *mut c_void) - -> c_int { +extern "C" fn raw_next_protos_advertise_cb(ssl: *mut ffi::SSL, + out: *mut *const c_uchar, + outlen: *mut c_uint, + _arg: *mut c_void) + -> c_int { unsafe { // First, get the list of (supported) protocols saved in the context extra data. let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); @@ -458,7 +457,9 @@ impl SslContextBuilder { { unsafe { let verify = Box::new(verify); - ffi::SSL_CTX_set_ex_data(self.as_ptr(), get_verify_data_idx::(), mem::transmute(verify)); + ffi::SSL_CTX_set_ex_data(self.as_ptr(), + get_verify_data_idx::(), + mem::transmute(verify)); ffi::SSL_CTX_set_verify(self.as_ptr(), mode.bits as c_int, Some(raw_verify::)); } } @@ -475,8 +476,8 @@ impl SslContextBuilder { ffi::SSL_CTX_set_ex_data(self.as_ptr(), get_verify_data_idx::(), mem::transmute(callback)); - let f: extern fn(_, _, _) -> _ = raw_sni::; - let f: extern fn() = mem::transmute(f); + let f: extern "C" fn(_, _, _) -> _ = raw_sni::; + let f: extern "C" fn() = mem::transmute(f); ffi::SSL_CTX_set_tlsext_servername_callback(self.as_ptr(), Some(f)); } } @@ -495,21 +496,15 @@ impl SslContextBuilder { } fn set_mode(&mut self, mode: c_long) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::SSL_CTX_set_mode(self.as_ptr(), mode) as c_int).map(|_| ()) - } + unsafe { cvt(ffi::SSL_CTX_set_mode(self.as_ptr(), mode) as c_int).map(|_| ()) } } pub fn set_tmp_dh(&mut self, dh: &DhRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::SSL_CTX_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as c_int).map(|_| ()) - } + unsafe { cvt(ffi::SSL_CTX_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as c_int).map(|_| ()) } } pub fn set_tmp_ecdh(&mut self, key: &EcKeyRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::SSL_CTX_set_tmp_ecdh(self.as_ptr(), key.as_ptr()) as c_int).map(|_| ()) - } + unsafe { cvt(ffi::SSL_CTX_set_tmp_ecdh(self.as_ptr(), key.as_ptr()) as c_int).map(|_| ()) } } /// Use the default locations of trusted certificates for verification. @@ -518,9 +513,7 @@ impl SslContextBuilder { /// environment variables if present, or defaults specified at OpenSSL /// build time otherwise. pub fn set_default_verify_paths(&mut self) -> Result<(), ErrorStack> { - unsafe{ - cvt(ffi::SSL_CTX_set_default_verify_paths(self.as_ptr())).map(|_| ()) - } + unsafe { cvt(ffi::SSL_CTX_set_default_verify_paths(self.as_ptr())).map(|_| ()) } } #[allow(non_snake_case)] @@ -568,21 +561,19 @@ impl SslContextBuilder { } /// Specifies the file that contains certificate chain - pub fn set_certificate_chain_file>(&mut self, file: P) - -> Result<(), ErrorStack> { + pub fn set_certificate_chain_file>(&mut self, + file: P) + -> Result<(), ErrorStack> { let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap(); unsafe { - cvt(ffi::SSL_CTX_use_certificate_chain_file(self.as_ptr(), - file.as_ptr() as *const _)) + cvt(ffi::SSL_CTX_use_certificate_chain_file(self.as_ptr(), file.as_ptr() as *const _)) .map(|_| ()) } } /// Specifies the certificate pub fn set_certificate(&mut self, cert: &X509Ref) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::SSL_CTX_use_certificate(self.as_ptr(), cert.as_ptr())).map(|_| ()) - } + unsafe { cvt(ffi::SSL_CTX_use_certificate(self.as_ptr(), cert.as_ptr())).map(|_| ()) } } /// Adds a certificate to the certificate chain presented together with the @@ -611,9 +602,7 @@ impl SslContextBuilder { /// Specifies the private key pub fn set_private_key(&mut self, key: &PKeyRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::SSL_CTX_use_PrivateKey(self.as_ptr(), key.as_ptr())).map(|_| ()) - } + unsafe { cvt(ffi::SSL_CTX_use_PrivateKey(self.as_ptr(), key.as_ptr())).map(|_| ()) } } pub fn set_cipher_list(&mut self, cipher_list: &str) -> Result<(), ErrorStack> { @@ -636,9 +625,7 @@ impl SslContextBuilder { #[cfg(ossl102)] fn _set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::SSL_CTX_set_ecdh_auto(self.as_ptr(), onoff as c_int)).map(|_| ()) - } + unsafe { cvt(ffi::SSL_CTX_set_ecdh_auto(self.as_ptr(), onoff as c_int)).map(|_| ()) } } pub fn set_options(&mut self, option: SslOptions) -> SslOptions { @@ -724,9 +711,7 @@ impl SslContextBuilder { /// Checks consistency between the private key and certificate. pub fn check_private_key(&self) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::SSL_CTX_check_private_key(self.as_ptr())).map(|_| ()) - } + unsafe { cvt(ffi::SSL_CTX_check_private_key(self.as_ptr())).map(|_| ()) } } pub fn build(self) -> SslContext { @@ -785,17 +770,13 @@ impl Deref for SslContext { type Target = SslContextRef; fn deref(&self) -> &SslContextRef { - unsafe { - SslContextRef::from_ptr(self.0) - } + unsafe { SslContextRef::from_ptr(self.0) } } } impl DerefMut for SslContext { fn deref_mut(&mut self) -> &mut SslContextRef { - unsafe { - SslContextRef::from_ptr_mut(self.0) - } + unsafe { SslContextRef::from_ptr_mut(self.0) } } } @@ -1099,9 +1080,7 @@ impl SslRef { /// Changes the context corresponding to the current connection. pub fn set_ssl_context(&mut self, ctx: &SslContextRef) -> Result<(), ErrorStack> { - unsafe { - cvt_p(ffi::SSL_set_SSL_CTX(self.as_ptr(), ctx.as_ptr())).map(|_| ()) - } + unsafe { cvt_p(ffi::SSL_set_SSL_CTX(self.as_ptr(), ctx.as_ptr())).map(|_| ()) } } /// Returns the context corresponding to the current connection @@ -1122,16 +1101,12 @@ impl SslRef { #[cfg(any(ossl102, ossl110))] fn _param_mut(&mut self) -> &mut X509VerifyParamRef { - unsafe { - X509VerifyParamRef::from_ptr_mut(ffi::SSL_get0_param(self.as_ptr())) - } + unsafe { X509VerifyParamRef::from_ptr_mut(ffi::SSL_get0_param(self.as_ptr())) } } /// Returns the result of X509 certificate verification. pub fn verify_result(&self) -> Option { - unsafe { - X509VerifyError::from_raw(ffi::SSL_get_verify_result(self.as_ptr())) - } + unsafe { X509VerifyError::from_raw(ffi::SSL_get_verify_result(self.as_ptr())) } } } @@ -1161,17 +1136,13 @@ impl Deref for Ssl { type Target = SslRef; fn deref(&self) -> &SslRef { - unsafe { - SslRef::from_ptr(self.0) - } + unsafe { SslRef::from_ptr(self.0) } } } impl DerefMut for Ssl { fn deref_mut(&mut self) -> &mut SslRef { - unsafe { - SslRef::from_ptr_mut(self.0) - } + unsafe { SslRef::from_ptr_mut(self.0) } } } @@ -1275,7 +1246,8 @@ impl stderror::Error for HandshakeError { fn cause(&self) -> Option<&stderror::Error> { match *self { HandshakeError::SetupFailure(ref e) => Some(e), - HandshakeError::Failure(ref s) | HandshakeError::Interrupted(ref s) => Some(s.error()), + HandshakeError::Failure(ref s) | + HandshakeError::Interrupted(ref s) => Some(s.error()), } } } @@ -1285,7 +1257,8 @@ impl fmt::Display for HandshakeError { try!(f.write_str(stderror::Error::description(self))); match *self { HandshakeError::SetupFailure(ref e) => try!(write!(f, ": {}", e)), - HandshakeError::Failure(ref s) | HandshakeError::Interrupted(ref s) => { + HandshakeError::Failure(ref s) | + HandshakeError::Interrupted(ref s) => { try!(write!(f, ": {}", s.error())); if let Some(err) = s.ssl().verify_result() { try!(write!(f, ": {}", err)); @@ -1368,9 +1341,9 @@ impl fmt::Debug for SslStream { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("SslStream") - .field("stream", &self.get_ref()) - .field("ssl", &self.ssl()) - .finish() + .field("stream", &self.get_ref()) + .field("ssl", &self.ssl()) + .finish() } } @@ -1577,15 +1550,11 @@ mod compat { } pub fn tls_method() -> *const ffi::SSL_METHOD { - unsafe { - ffi::TLS_method() - } + unsafe { ffi::TLS_method() } } pub fn dtls_method() -> *const ffi::SSL_METHOD { - unsafe { - ffi::DTLS_method() - } + unsafe { ffi::DTLS_method() } } } @@ -1598,22 +1567,17 @@ mod compat { use libc::{self, c_long, c_ulong, c_int}; pub unsafe fn SSL_CTX_get_options(ctx: *const ffi::SSL_CTX) -> c_ulong { - ffi::SSL_CTX_ctrl(ctx as *mut _, - ffi::SSL_CTRL_OPTIONS, - 0, - ptr::null_mut()) as c_ulong + ffi::SSL_CTX_ctrl(ctx as *mut _, ffi::SSL_CTRL_OPTIONS, 0, ptr::null_mut()) as c_ulong } - pub unsafe fn SSL_CTX_set_options(ctx: *const ffi::SSL_CTX, - op: c_ulong) -> c_ulong { + pub unsafe fn SSL_CTX_set_options(ctx: *const ffi::SSL_CTX, op: c_ulong) -> c_ulong { ffi::SSL_CTX_ctrl(ctx as *mut _, ffi::SSL_CTRL_OPTIONS, op as c_long, ptr::null_mut()) as c_ulong } - pub unsafe fn SSL_CTX_clear_options(ctx: *const ffi::SSL_CTX, - op: c_ulong) -> c_ulong { + pub unsafe fn SSL_CTX_clear_options(ctx: *const ffi::SSL_CTX, op: c_ulong) -> c_ulong { ffi::SSL_CTX_ctrl(ctx as *mut _, ffi::SSL_CTRL_CLEAR_OPTIONS, op as c_long, @@ -1621,19 +1585,11 @@ mod compat { } pub unsafe fn get_new_idx(f: ffi::CRYPTO_EX_free) -> c_int { - ffi::SSL_CTX_get_ex_new_index(0, - ptr::null_mut(), - None, - None, - Some(f)) + ffi::SSL_CTX_get_ex_new_index(0, ptr::null_mut(), None, None, Some(f)) } pub unsafe fn get_new_ssl_idx(f: ffi::CRYPTO_EX_free) -> c_int { - ffi::SSL_get_ex_new_index(0, - ptr::null_mut(), - None, - None, - Some(f)) + ffi::SSL_get_ex_new_index(0, ptr::null_mut(), None, None, Some(f)) } pub unsafe fn SSL_CTX_up_ref(ssl: *mut ffi::SSL_CTX) -> libc::c_int { @@ -1646,14 +1602,10 @@ mod compat { } pub fn tls_method() -> *const ffi::SSL_METHOD { - unsafe { - ffi::SSLv23_method() - } + unsafe { ffi::SSLv23_method() } } pub fn dtls_method() -> *const ffi::SSL_METHOD { - unsafe { - ffi::DTLSv1_method() - } + unsafe { ffi::DTLSv1_method() } } } diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index eeada33a..5e42d5c0 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -57,25 +57,29 @@ impl Server { let addr = next_addr(); let mut child = Command::new("openssl") - .arg("s_server") - .arg("-accept") - .arg(addr.port().to_string()) - .args(args) - .arg("-cert") - .arg(&cert) - .arg("-key") - .arg(&key) - .arg("-no_dhe") - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .stdin(Stdio::piped()) - .spawn() - .unwrap(); + .arg("s_server") + .arg("-accept") + .arg(addr.port().to_string()) + .args(args) + .arg("-cert") + .arg(&cert) + .arg("-key") + .arg(&key) + .arg("-no_dhe") + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .stdin(Stdio::piped()) + .spawn() + .unwrap(); let stdin = child.stdin.take().unwrap(); if let Some(mut input) = input { thread::spawn(move || input(stdin)); } - (Server { p: child, _temp: td }, addr) + (Server { + p: child, + _temp: td, + }, + addr) } fn new_tcp(args: &[&str]) -> (Server, TcpStream) { @@ -111,12 +115,12 @@ impl Server { let mut input = input.into_iter(); let (s, addr) = Server::spawn(&["-dtls1"], Some(Box::new(move |mut io| { - for s in input.by_ref() { - if io.write_all(s.as_bytes()).is_err() { - break; - } - } - }))); + for s in input.by_ref() { + if io.write_all(s.as_bytes()).is_err() { + break; + } + } + }))); // Need to wait for the UDP socket to get bound in our child process, // but don't currently have a great way to do that so just wait for a // bit. @@ -294,10 +298,10 @@ run_test!(verify_trusted_get_error_err, |method, stream| { run_test!(verify_callback_data, |method, stream| { let mut ctx = SslContext::builder(method).unwrap(); - // Node id was generated as SHA256 hash of certificate "test/cert.pem" - // in DER format. - // Command: openssl x509 -in test/cert.pem -outform DER | openssl dgst -sha256 - // Please update if "test/cert.pem" will ever change +// Node id was generated as SHA256 hash of certificate "test/cert.pem" +// in DER format. +// Command: openssl x509 -in test/cert.pem -outform DER | openssl dgst -sha256 +// Please update if "test/cert.pem" will ever change let node_hash_str = "59172d9313e84459bcff27f967e79e6e9217e584"; let node_id = node_hash_str.from_hex().unwrap(); ctx.set_verify_callback(SSL_VERIFY_PEER, move |_preverify_ok, x509_ctx| { @@ -632,7 +636,7 @@ fn test_npn_server_advertise_multiple() { assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) .is_ok()); ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM) - .unwrap(); + .unwrap(); ctx.build() }; // Have the listener wait on the connection in a different thread. @@ -673,7 +677,7 @@ fn test_alpn_server_advertise_multiple() { assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) .is_ok()); ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM) - .unwrap(); + .unwrap(); ctx.build() }; // Have the listener wait on the connection in a different thread. @@ -714,7 +718,7 @@ fn test_alpn_server_select_none() { assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) .is_ok()); ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM) - .unwrap(); + .unwrap(); ctx.build() }; // Have the listener wait on the connection in a different thread. @@ -815,8 +819,7 @@ fn wait_io(stream: &TcpStream, read: bool, timeout_ms: u32) -> bool { } } -fn handshake(res: Result, HandshakeError>) - -> SslStream { +fn handshake(res: Result, HandshakeError>) -> SslStream { match res { Ok(s) => s, Err(HandshakeError::Interrupted(s)) => { @@ -1112,8 +1115,10 @@ fn connector_client_server_mozilla_intermediate() { let t = thread::spawn(move || { let key = PKey::private_key_from_pem(KEY).unwrap(); let cert = X509::from_pem(CERT).unwrap(); - let connector = ServerConnectorBuilder::mozilla_intermediate( - SslMethod::tls(), &key, &cert, None::) + let connector = ServerConnectorBuilder::mozilla_intermediate(SslMethod::tls(), + &key, + &cert, + None::) .unwrap() .build(); let stream = listener.accept().unwrap().0; @@ -1144,10 +1149,10 @@ fn connector_client_server_mozilla_modern() { let t = thread::spawn(move || { let key = PKey::private_key_from_pem(KEY).unwrap(); let cert = X509::from_pem(CERT).unwrap(); - let connector = ServerConnectorBuilder::mozilla_modern( - SslMethod::tls(), &key, &cert, None::) - .unwrap() - .build(); + let connector = + ServerConnectorBuilder::mozilla_modern(SslMethod::tls(), &key, &cert, None::) + .unwrap() + .build(); let stream = listener.accept().unwrap().0; let mut stream = connector.connect(stream).unwrap(); diff --git a/openssl/src/symm.rs b/openssl/src/symm.rs index bffe337a..d4b15f28 100644 --- a/openssl/src/symm.rs +++ b/openssl/src/symm.rs @@ -17,117 +17,79 @@ pub struct Cipher(*const ffi::EVP_CIPHER); impl Cipher { pub fn aes_128_ecb() -> Cipher { - unsafe { - Cipher(ffi::EVP_aes_128_ecb()) - } + unsafe { Cipher(ffi::EVP_aes_128_ecb()) } } pub fn aes_128_cbc() -> Cipher { - unsafe { - Cipher(ffi::EVP_aes_128_cbc()) - } + unsafe { Cipher(ffi::EVP_aes_128_cbc()) } } pub fn aes_128_xts() -> Cipher { - unsafe { - Cipher(ffi::EVP_aes_128_xts()) - } + unsafe { Cipher(ffi::EVP_aes_128_xts()) } } pub fn aes_128_ctr() -> Cipher { - unsafe { - Cipher(ffi::EVP_aes_128_ctr()) - } + unsafe { Cipher(ffi::EVP_aes_128_ctr()) } } pub fn aes_128_cfb1() -> Cipher { - unsafe { - Cipher(ffi::EVP_aes_128_cfb1()) - } + unsafe { Cipher(ffi::EVP_aes_128_cfb1()) } } pub fn aes_128_cfb128() -> Cipher { - unsafe { - Cipher(ffi::EVP_aes_128_cfb128()) - } + unsafe { Cipher(ffi::EVP_aes_128_cfb128()) } } pub fn aes_128_cfb8() -> Cipher { - unsafe { - Cipher(ffi::EVP_aes_128_cfb8()) - } + unsafe { Cipher(ffi::EVP_aes_128_cfb8()) } } pub fn aes_128_gcm() -> Cipher { - unsafe { - Cipher(ffi::EVP_aes_128_gcm()) - } + unsafe { Cipher(ffi::EVP_aes_128_gcm()) } } pub fn aes_256_ecb() -> Cipher { - unsafe { - Cipher(ffi::EVP_aes_256_ecb()) - } + unsafe { Cipher(ffi::EVP_aes_256_ecb()) } } pub fn aes_256_cbc() -> Cipher { - unsafe { - Cipher(ffi::EVP_aes_256_cbc()) - } + unsafe { Cipher(ffi::EVP_aes_256_cbc()) } } pub fn aes_256_xts() -> Cipher { - unsafe { - Cipher(ffi::EVP_aes_256_xts()) - } + unsafe { Cipher(ffi::EVP_aes_256_xts()) } } pub fn aes_256_ctr() -> Cipher { - unsafe { - Cipher(ffi::EVP_aes_256_ctr()) - } + unsafe { Cipher(ffi::EVP_aes_256_ctr()) } } pub fn aes_256_cfb1() -> Cipher { - unsafe { - Cipher(ffi::EVP_aes_256_cfb1()) - } + unsafe { Cipher(ffi::EVP_aes_256_cfb1()) } } pub fn aes_256_cfb128() -> Cipher { - unsafe { - Cipher(ffi::EVP_aes_256_cfb128()) - } + unsafe { Cipher(ffi::EVP_aes_256_cfb128()) } } pub fn aes_256_cfb8() -> Cipher { - unsafe { - Cipher(ffi::EVP_aes_256_cfb8()) - } + unsafe { Cipher(ffi::EVP_aes_256_cfb8()) } } pub fn aes_256_gcm() -> Cipher { - unsafe { - Cipher(ffi::EVP_aes_256_gcm()) - } + unsafe { Cipher(ffi::EVP_aes_256_gcm()) } } pub fn des_cbc() -> Cipher { - unsafe { - Cipher(ffi::EVP_des_cbc()) - } + unsafe { Cipher(ffi::EVP_des_cbc()) } } pub fn des_ecb() -> Cipher { - unsafe { - Cipher(ffi::EVP_des_ecb()) - } + unsafe { Cipher(ffi::EVP_des_ecb()) } } pub fn rc4() -> Cipher { - unsafe { - Cipher(ffi::EVP_rc4()) - } + unsafe { Cipher(ffi::EVP_rc4()) } } pub unsafe fn from_ptr(ptr: *const ffi::EVP_CIPHER) -> Cipher { @@ -140,9 +102,7 @@ impl Cipher { /// Returns the length of keys used with this cipher. pub fn key_len(&self) -> usize { - unsafe { - EVP_CIPHER_key_length(self.0) as usize - } + unsafe { EVP_CIPHER_key_length(self.0) as usize } } /// Returns the length of the IV used with this cipher, or `None` if the @@ -150,11 +110,7 @@ impl Cipher { pub fn iv_len(&self) -> Option { unsafe { let len = EVP_CIPHER_iv_length(self.0) as usize; - if len == 0 { - None - } else { - Some(len) - } + if len == 0 { None } else { Some(len) } } } @@ -164,9 +120,7 @@ impl Cipher { /// /// Stream ciphers such as RC4 have a block size of 1. pub fn block_size(&self) -> usize { - unsafe { - EVP_CIPHER_block_size(self.0) as usize - } + unsafe { EVP_CIPHER_block_size(self.0) as usize } } } @@ -183,7 +137,11 @@ impl Crypter { /// /// Panics if an IV is required by the cipher but not provided, or if the /// IV's length does not match the expected length (see `Cipher::iv_len`). - pub fn new(t: Cipher, mode: Mode, key: &[u8], iv: Option<&[u8]>) -> Result { + pub fn new(t: Cipher, + mode: Mode, + key: &[u8], + iv: Option<&[u8]>) + -> Result { ffi::init(); unsafe { @@ -233,7 +191,9 @@ impl Crypter { /// If padding is disabled, total amount of data encrypted/decrypted must /// be a multiple of the cipher's block size. pub fn pad(&mut self, padding: bool) { - unsafe { ffi::EVP_CIPHER_CTX_set_padding(self.ctx, padding as c_int); } + unsafe { + ffi::EVP_CIPHER_CTX_set_padding(self.ctx, padding as c_int); + } } /// Feeds data from `input` through the cipher, writing encrypted/decrypted @@ -375,7 +335,8 @@ mod tests { let mut c = super::Crypter::new(super::Cipher::aes_256_ecb(), super::Mode::Encrypt, &k0, - None).unwrap(); + None) + .unwrap(); c.pad(false); let mut r0 = vec![0; c0.len() + super::Cipher::aes_256_ecb().block_size()]; let count = c.update(&p0, &mut r0).unwrap(); @@ -386,7 +347,8 @@ mod tests { let mut c = super::Crypter::new(super::Cipher::aes_256_ecb(), super::Mode::Decrypt, &k0, - None).unwrap(); + None) + .unwrap(); c.pad(false); let mut p1 = vec![0; r0.len() + super::Cipher::aes_256_ecb().block_size()]; let count = c.update(&r0, &mut p1).unwrap(); @@ -409,7 +371,8 @@ mod tests { let mut cr = super::Crypter::new(super::Cipher::aes_256_cbc(), super::Mode::Decrypt, &data, - Some(&iv)).unwrap(); + Some(&iv)) + .unwrap(); cr.pad(false); let mut unciphered_data = vec![0; data.len() + super::Cipher::aes_256_cbc().block_size()]; let count = cr.update(&ciphered_data, &mut unciphered_data).unwrap(); diff --git a/openssl/src/util.rs b/openssl/src/util.rs index 68d9b32a..49f38c3d 100644 --- a/openssl/src/util.rs +++ b/openssl/src/util.rs @@ -36,12 +36,13 @@ impl Drop for CallbackState { /// Password callback function, passed to private key loading functions. /// /// `cb_state` is expected to be a pointer to a `CallbackState`. -pub unsafe extern fn invoke_passwd_cb(buf: *mut c_char, - size: c_int, - _rwflag: c_int, - cb_state: *mut c_void) - -> c_int - where F: FnOnce(&mut [c_char]) -> usize { +pub unsafe extern "C" fn invoke_passwd_cb(buf: *mut c_char, + size: c_int, + _rwflag: c_int, + cb_state: *mut c_void) + -> c_int + where F: FnOnce(&mut [c_char]) -> usize +{ let callback = &mut *(cb_state as *mut CallbackState); let result = panic::catch_unwind(AssertUnwindSafe(|| { diff --git a/openssl/src/version.rs b/openssl/src/version.rs index 245305e8..d7db39a7 100644 --- a/openssl/src/version.rs +++ b/openssl/src/version.rs @@ -14,15 +14,10 @@ use std::ffi::CStr; #[cfg(ossl10x)] -use ffi::{ - SSLEAY_VERSION as OPENSSL_VERSION, - SSLEAY_CFLAGS as OPENSSL_CFLAGS, - SSLEAY_BUILT_ON as OPENSSL_BUILT_ON, - SSLEAY_PLATFORM as OPENSSL_PLATFORM, - SSLEAY_DIR as OPENSSL_DIR, - SSLeay as OpenSSL_version_num, - SSLeay_version as OpenSSL_version, -}; +use ffi::{SSLEAY_VERSION as OPENSSL_VERSION, SSLEAY_CFLAGS as OPENSSL_CFLAGS, + SSLEAY_BUILT_ON as OPENSSL_BUILT_ON, SSLEAY_PLATFORM as OPENSSL_PLATFORM, + SSLEAY_DIR as OPENSSL_DIR, SSLeay as OpenSSL_version_num, + SSLeay_version as OpenSSL_version}; #[cfg(ossl110)] use ffi::{OPENSSL_VERSION, OPENSSL_CFLAGS}; diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index b7cbe363..b49a9848 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -26,17 +26,10 @@ use nid::Nid; use opaque::Opaque; #[cfg(ossl10x)] -use ffi::{ - X509_set_notBefore, - X509_set_notAfter, - ASN1_STRING_data, -}; +use ffi::{X509_set_notBefore, X509_set_notAfter, ASN1_STRING_data}; #[cfg(ossl110)] -use ffi::{ - X509_set1_notBefore as X509_set_notBefore, - X509_set1_notAfter as X509_set_notAfter, - ASN1_STRING_get0_data as ASN1_STRING_data, -}; +use ffi::{X509_set1_notBefore as X509_set_notBefore, X509_set1_notAfter as X509_set_notAfter, + ASN1_STRING_get0_data as ASN1_STRING_data}; #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] pub mod verify; @@ -68,9 +61,7 @@ impl X509StoreContextRef { } pub fn error(&self) -> Option { - unsafe { - X509VerifyError::from_raw(ffi::X509_STORE_CTX_get_error(self.as_ptr()) as c_long) - } + unsafe { X509VerifyError::from_raw(ffi::X509_STORE_CTX_get_error(self.as_ptr()) as c_long) } } pub fn current_cert(&self) -> Option<&X509Ref> { @@ -386,9 +377,7 @@ impl X509Ref { return None; } - Some(GeneralNames { - stack: stack as *mut _, - }) + Some(GeneralNames { stack: stack as *mut _ }) } } @@ -495,9 +484,7 @@ impl Deref for X509 { type Target = X509Ref; fn deref(&self) -> &X509Ref { - unsafe { - X509Ref::from_ptr(self.0) - } + unsafe { X509Ref::from_ptr(self.0) } } } @@ -749,8 +736,8 @@ impl Drop for GeneralNames { fn drop(&mut self) { unsafe { // This transmute is dubious but it's what openssl itself does... - let free: unsafe extern fn(*mut ffi::GENERAL_NAME) = ffi::GENERAL_NAME_free; - let free: unsafe extern fn(*mut c_void) = mem::transmute(free); + let free: unsafe extern "C" fn(*mut ffi::GENERAL_NAME) = ffi::GENERAL_NAME_free; + let free: unsafe extern "C" fn(*mut c_void) = mem::transmute(free); ffi::sk_pop_free(&mut (*self.stack).stack, Some(free)); } } @@ -759,8 +746,8 @@ impl Drop for GeneralNames { fn drop(&mut self) { unsafe { // This transmute is dubious but it's what openssl itself does... - let free: unsafe extern fn(*mut ffi::GENERAL_NAME) = ffi::GENERAL_NAME_free; - let free: unsafe extern fn(*mut c_void) = mem::transmute(free); + let free: unsafe extern "C" fn(*mut ffi::GENERAL_NAME) = ffi::GENERAL_NAME_free; + let free: unsafe extern "C" fn(*mut c_void) = mem::transmute(free); ffi::OPENSSL_sk_pop_free(self.stack as *mut _, Some(free)); } } diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index 185c4910..1c248ba2 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -60,10 +60,9 @@ 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())) - .sign(&pkey); + .add_extension(OtherNid(nid::AUTHORITY_KEY_IDENTIFIER, "keyid:always".to_owned())) + .add_extension(OtherNid(nid::SUBJECT_KEY_IDENTIFIER, "hash".to_owned())) + .sign(&pkey); assert!(result.is_err()); } From c3b6eff1910aad742971b8c08fa7cf2c3303a9a9 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 16:44:21 -0700 Subject: [PATCH 123/186] Add DsaRef --- openssl/src/dsa.rs | 170 +++++++++++++++++++++++++-------------------- 1 file changed, 94 insertions(+), 76 deletions(-) diff --git a/openssl/src/dsa.rs b/openssl/src/dsa.rs index 9351d852..cec1466d 100644 --- a/openssl/src/dsa.rs +++ b/openssl/src/dsa.rs @@ -1,13 +1,15 @@ -use ffi; -use std::fmt; use error::ErrorStack; -use std::ptr; +use ffi; use libc::{c_int, c_char, c_void}; +use std::fmt; +use std::ops::Deref; +use std::ptr; use {cvt, cvt_p}; use bn::BigNumRef; use bio::{MemBio, MemBioSlice}; use util::{CallbackState, invoke_passwd_cb}; +use opaque::Opaque; /// Builder for upfront DSA parameter generation pub struct DsaParams(*mut ffi::DSA); @@ -46,6 +48,90 @@ impl Drop for DsaParams { } } +pub struct DsaRef(Opaque); + +impl DsaRef { + pub unsafe fn from_ptr<'a>(ptr: *mut ffi::DSA) -> &'a DsaRef { + &*(ptr as *mut _) + } + + pub fn as_ptr(&self) -> *mut ffi::DSA { + self as *const _ as *mut _ + } + + /// Writes an DSA private key as unencrypted PEM formatted data + pub fn private_key_to_pem(&self) -> Result, ErrorStack> { + assert!(self.has_private_key()); + let mem_bio = try!(MemBio::new()); + + unsafe { + try!(cvt(ffi::PEM_write_bio_DSAPrivateKey(mem_bio.as_ptr(), self.as_ptr(), + ptr::null(), ptr::null_mut(), 0, + None, ptr::null_mut()))) + }; + + Ok(mem_bio.get_buf().to_owned()) + } + + /// Writes an DSA public key as PEM formatted data + pub fn public_key_to_pem(&self) -> Result, ErrorStack> { + let mem_bio = try!(MemBio::new()); + unsafe { + try!(cvt(ffi::PEM_write_bio_DSA_PUBKEY(mem_bio.as_ptr(), self.as_ptr()))); + } + Ok(mem_bio.get_buf().to_owned()) + } + + pub fn size(&self) -> Option { + if self.q().is_some() { + unsafe { Some(ffi::DSA_size(self.as_ptr()) as u32) } + } else { + None + } + } + + pub fn p(&self) -> Option<&BigNumRef> { + unsafe { + let p = compat::pqg(self.as_ptr())[0]; + if p.is_null() { + None + } else { + Some(BigNumRef::from_ptr(p as *mut _)) + } + } + } + + pub fn q(&self) -> Option<&BigNumRef> { + unsafe { + let q = compat::pqg(self.as_ptr())[1]; + if q.is_null() { + None + } else { + Some(BigNumRef::from_ptr(q as *mut _)) + } + } + } + + pub fn g(&self) -> Option<&BigNumRef> { + unsafe { + let g = compat::pqg(self.as_ptr())[2]; + if g.is_null() { + None + } else { + Some(BigNumRef::from_ptr(g as *mut _)) + } + } + } + + pub fn has_public_key(&self) -> bool { + unsafe { !compat::keys(self.as_ptr())[0].is_null() } + } + + pub fn has_private_key(&self) -> bool { + unsafe { !compat::keys(self.as_ptr())[1].is_null() } + } +} + pub struct Dsa(*mut ffi::DSA); impl Drop for Dsa { @@ -104,20 +190,6 @@ impl Dsa { } } - /// Writes an DSA private key as unencrypted PEM formatted data - pub fn private_key_to_pem(&self) -> Result, ErrorStack> { - assert!(self.has_private_key()); - let mem_bio = try!(MemBio::new()); - - unsafe { - try!(cvt(ffi::PEM_write_bio_DSAPrivateKey(mem_bio.as_ptr(), self.0, - ptr::null(), ptr::null_mut(), 0, - None, ptr::null_mut()))) - }; - - Ok(mem_bio.get_buf().to_owned()) - } - /// Reads an DSA public key from PEM formatted data. pub fn public_key_from_pem(buf: &[u8]) -> Result { ffi::init(); @@ -131,67 +203,13 @@ impl Dsa { Ok(Dsa(dsa)) } } +} - /// Writes an DSA public key as PEM formatted data - pub fn public_key_to_pem(&self) -> Result, ErrorStack> { - let mem_bio = try!(MemBio::new()); - unsafe { - try!(cvt(ffi::PEM_write_bio_DSA_PUBKEY(mem_bio.as_ptr(), self.0))); - } - Ok(mem_bio.get_buf().to_owned()) - } +impl Deref for Dsa { + type Target = DsaRef; - pub fn size(&self) -> Option { - if self.q().is_some() { - unsafe { Some(ffi::DSA_size(self.0) as u32) } - } else { - None - } - } - - pub fn as_ptr(&self) -> *mut ffi::DSA { - self.0 - } - - pub fn p(&self) -> Option<&BigNumRef> { - unsafe { - let p = compat::pqg(self.0)[0]; - if p.is_null() { - None - } else { - Some(BigNumRef::from_ptr(p as *mut _)) - } - } - } - - pub fn q(&self) -> Option<&BigNumRef> { - unsafe { - let q = compat::pqg(self.0)[1]; - if q.is_null() { - None - } else { - Some(BigNumRef::from_ptr(q as *mut _)) - } - } - } - - pub fn g(&self) -> Option<&BigNumRef> { - unsafe { - let g = compat::pqg(self.0)[2]; - if g.is_null() { - None - } else { - Some(BigNumRef::from_ptr(g as *mut _)) - } - } - } - - pub fn has_public_key(&self) -> bool { - unsafe { !compat::keys(self.0)[0].is_null() } - } - - pub fn has_private_key(&self) -> bool { - unsafe { !compat::keys(self.0)[1].is_null() } + fn deref(&self) -> &DsaRef { + unsafe { DsaRef::from_ptr(self.0) } } } From 610403a562450099a3744a60c23678ffc3b0dd5f Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 16:59:06 -0700 Subject: [PATCH 124/186] Add RsaRef --- openssl/src/pkey.rs | 4 +- openssl/src/rsa.rs | 400 +++++++++++++++++++++++--------------------- 2 files changed, 211 insertions(+), 193 deletions(-) diff --git a/openssl/src/pkey.rs b/openssl/src/pkey.rs index fc48c8b4..8e4041b1 100644 --- a/openssl/src/pkey.rs +++ b/openssl/src/pkey.rs @@ -7,7 +7,7 @@ use ffi; use {cvt, cvt_p}; use bio::{MemBio, MemBioSlice}; use dsa::Dsa; -use rsa::Rsa; +use rsa::{Rsa, RsaRef}; use error::ErrorStack; use util::{CallbackState, invoke_passwd_cb}; use opaque::Opaque; @@ -156,7 +156,7 @@ impl PKey { } /// Assign an RSA key to this pkey. - pub fn set_rsa(&mut self, rsa: &Rsa) -> Result<(), ErrorStack> { + pub fn set_rsa(&mut self, rsa: &RsaRef) -> Result<(), ErrorStack> { unsafe { // this needs to be a reference as the set1_RSA ups the reference count let rsa_ptr = rsa.as_ptr(); diff --git a/openssl/src/rsa.rs b/openssl/src/rsa.rs index 666b99dd..c6c96223 100644 --- a/openssl/src/rsa.rs +++ b/openssl/src/rsa.rs @@ -2,6 +2,7 @@ use ffi; use std::fmt; use std::ptr; use std::mem; +use std::ops::Deref; use libc::{c_int, c_void, c_char}; use {cvt, cvt_p, cvt_n}; @@ -9,6 +10,7 @@ use bn::{BigNum, BigNumRef}; use bio::{MemBio, MemBioSlice}; use error::ErrorStack; use util::{CallbackState, invoke_passwd_cb}; +use opaque::Opaque; /// Type of encryption padding to use. #[derive(Copy, Clone)] @@ -18,6 +20,204 @@ pub const NO_PADDING: Padding = Padding(ffi::RSA_NO_PADDING); pub const PKCS1_PADDING: Padding = Padding(ffi::RSA_PKCS1_PADDING); pub const PKCS1_OAEP_PADDING: Padding = Padding(ffi::RSA_PKCS1_OAEP_PADDING); +pub struct RsaRef(Opaque); + +impl RsaRef { + pub unsafe fn from_ptr<'a>(ptr: *mut ffi::RSA) -> &'a RsaRef { + &*(ptr as *mut _) + } + + pub fn as_ptr(&self) -> *mut ffi::RSA { + self as *const _ as *mut _ + } + + /// Writes an RSA private key as unencrypted PEM formatted data + pub fn private_key_to_pem(&self) -> Result, ErrorStack> { + let mem_bio = try!(MemBio::new()); + + unsafe { + try!(cvt(ffi::PEM_write_bio_RSAPrivateKey(mem_bio.as_ptr(), + self.as_ptr(), + ptr::null(), + ptr::null_mut(), + 0, + None, + ptr::null_mut()))); + } + Ok(mem_bio.get_buf().to_owned()) + } + + /// Writes an RSA public key as PEM formatted data + pub fn public_key_to_pem(&self) -> Result, ErrorStack> { + let mem_bio = try!(MemBio::new()); + + unsafe { + try!(cvt(ffi::PEM_write_bio_RSA_PUBKEY(mem_bio.as_ptr(), self.as_ptr()))); + } + + Ok(mem_bio.get_buf().to_owned()) + } + + pub fn size(&self) -> usize { + unsafe { + assert!(self.n().is_some()); + + ffi::RSA_size(self.as_ptr()) as usize + } + } + + /// Decrypts data using the private key, returning the number of decrypted bytes. + /// + /// # Panics + /// + /// Panics if `self` has no private components, or if `to` is smaller + /// than `self.size()`. + pub fn private_decrypt(&self, + from: &[u8], + to: &mut [u8], + padding: Padding) + -> Result { + assert!(self.d().is_some(), "private components missing"); + assert!(from.len() <= i32::max_value() as usize); + assert!(to.len() >= self.size()); + + unsafe { + let len = try!(cvt_n(ffi::RSA_private_decrypt(from.len() as c_int, + from.as_ptr(), + to.as_mut_ptr(), + self.as_ptr(), + padding.0))); + Ok(len as usize) + } + } + + /// Encrypts data using the private key, returning the number of encrypted bytes. + /// + /// # Panics + /// + /// Panics if `self` has no private components, or if `to` is smaller + /// than `self.size()`. + pub fn private_encrypt(&self, + from: &[u8], + to: &mut [u8], + padding: Padding) + -> Result { + assert!(self.d().is_some(), "private components missing"); + assert!(from.len() <= i32::max_value() as usize); + assert!(to.len() >= self.size()); + + unsafe { + let len = try!(cvt_n(ffi::RSA_private_encrypt(from.len() as c_int, + from.as_ptr(), + to.as_mut_ptr(), + self.as_ptr(), + padding.0))); + Ok(len as usize) + } + } + + /// Decrypts data using the public key, returning the number of decrypted bytes. + /// + /// # Panics + /// + /// Panics if `to` is smaller than `self.size()`. + pub fn public_decrypt(&self, + from: &[u8], + to: &mut [u8], + padding: Padding) + -> Result { + assert!(from.len() <= i32::max_value() as usize); + assert!(to.len() >= self.size()); + + unsafe { + let len = try!(cvt_n(ffi::RSA_public_decrypt(from.len() as c_int, + from.as_ptr(), + to.as_mut_ptr(), + self.as_ptr(), + padding.0))); + Ok(len as usize) + } + } + + /// Encrypts data using the private key, returning the number of encrypted bytes. + /// + /// # Panics + /// + /// Panics if `to` is smaller than `self.size()`. + pub fn public_encrypt(&self, + from: &[u8], + to: &mut [u8], + padding: Padding) + -> Result { + assert!(from.len() <= i32::max_value() as usize); + assert!(to.len() >= self.size()); + + unsafe { + let len = try!(cvt_n(ffi::RSA_public_encrypt(from.len() as c_int, + from.as_ptr(), + to.as_mut_ptr(), + self.as_ptr(), + padding.0))); + Ok(len as usize) + } + } + + pub fn n(&self) -> Option<&BigNumRef> { + unsafe { + let n = compat::key(self.as_ptr())[0]; + if n.is_null() { + None + } else { + Some(BigNumRef::from_ptr(n as *mut _)) + } + } + } + + pub fn d(&self) -> Option<&BigNumRef> { + unsafe { + let d = compat::key(self.as_ptr())[2]; + if d.is_null() { + None + } else { + Some(BigNumRef::from_ptr(d as *mut _)) + } + } + } + + pub fn e(&self) -> Option<&BigNumRef> { + unsafe { + let e = compat::key(self.as_ptr())[1]; + if e.is_null() { + None + } else { + Some(BigNumRef::from_ptr(e as *mut _)) + } + } + } + + pub fn p(&self) -> Option<&BigNumRef> { + unsafe { + let p = compat::factors(self.as_ptr())[0]; + if p.is_null() { + None + } else { + Some(BigNumRef::from_ptr(p as *mut _)) + } + } + } + + pub fn q(&self) -> Option<&BigNumRef> { + unsafe { + let q = compat::factors(self.as_ptr())[1]; + if q.is_null() { + None + } else { + Some(BigNumRef::from_ptr(q as *mut _)) + } + } + } +} + pub struct Rsa(*mut ffi::RSA); impl Drop for Rsa { @@ -121,201 +321,19 @@ impl Rsa { Ok(Rsa(rsa)) } } - - /// Writes an RSA private key as unencrypted PEM formatted data - pub fn private_key_to_pem(&self) -> Result, ErrorStack> { - let mem_bio = try!(MemBio::new()); - - unsafe { - try!(cvt(ffi::PEM_write_bio_RSAPrivateKey(mem_bio.as_ptr(), - self.0, - ptr::null(), - ptr::null_mut(), - 0, - None, - ptr::null_mut()))); - } - Ok(mem_bio.get_buf().to_owned()) - } - - /// Writes an RSA public key as PEM formatted data - pub fn public_key_to_pem(&self) -> Result, ErrorStack> { - let mem_bio = try!(MemBio::new()); - - unsafe { - try!(cvt(ffi::PEM_write_bio_RSA_PUBKEY(mem_bio.as_ptr(), self.0))); - } - - Ok(mem_bio.get_buf().to_owned()) - } - - pub fn size(&self) -> usize { - unsafe { - assert!(self.n().is_some()); - - ffi::RSA_size(self.0) as usize - } - } - - /// Decrypts data using the private key, returning the number of decrypted bytes. - /// - /// # Panics - /// - /// Panics if `self` has no private components, or if `to` is smaller - /// than `self.size()`. - pub fn private_decrypt(&self, - from: &[u8], - to: &mut [u8], - padding: Padding) - -> Result { - assert!(self.d().is_some(), "private components missing"); - assert!(from.len() <= i32::max_value() as usize); - assert!(to.len() >= self.size()); - - unsafe { - let len = try!(cvt_n(ffi::RSA_private_decrypt(from.len() as c_int, - from.as_ptr(), - to.as_mut_ptr(), - self.0, - padding.0))); - Ok(len as usize) - } - } - - /// Encrypts data using the private key, returning the number of encrypted bytes. - /// - /// # Panics - /// - /// Panics if `self` has no private components, or if `to` is smaller - /// than `self.size()`. - pub fn private_encrypt(&self, - from: &[u8], - to: &mut [u8], - padding: Padding) - -> Result { - assert!(self.d().is_some(), "private components missing"); - assert!(from.len() <= i32::max_value() as usize); - assert!(to.len() >= self.size()); - - unsafe { - let len = try!(cvt_n(ffi::RSA_private_encrypt(from.len() as c_int, - from.as_ptr(), - to.as_mut_ptr(), - self.0, - padding.0))); - Ok(len as usize) - } - } - - /// Decrypts data using the public key, returning the number of decrypted bytes. - /// - /// # Panics - /// - /// Panics if `to` is smaller than `self.size()`. - pub fn public_decrypt(&self, - from: &[u8], - to: &mut [u8], - padding: Padding) - -> Result { - assert!(from.len() <= i32::max_value() as usize); - assert!(to.len() >= self.size()); - - unsafe { - let len = try!(cvt_n(ffi::RSA_public_decrypt(from.len() as c_int, - from.as_ptr(), - to.as_mut_ptr(), - self.0, - padding.0))); - Ok(len as usize) - } - } - - /// Encrypts data using the private key, returning the number of encrypted bytes. - /// - /// # Panics - /// - /// Panics if `to` is smaller than `self.size()`. - pub fn public_encrypt(&self, - from: &[u8], - to: &mut [u8], - padding: Padding) - -> Result { - assert!(from.len() <= i32::max_value() as usize); - assert!(to.len() >= self.size()); - - unsafe { - let len = try!(cvt_n(ffi::RSA_public_encrypt(from.len() as c_int, - from.as_ptr(), - to.as_mut_ptr(), - self.0, - padding.0))); - Ok(len as usize) - } - } - - pub fn as_ptr(&self) -> *mut ffi::RSA { - self.0 - } - - pub fn n(&self) -> Option<&BigNumRef> { - unsafe { - let n = compat::key(self.0)[0]; - if n.is_null() { - None - } else { - Some(BigNumRef::from_ptr(n as *mut _)) - } - } - } - - pub fn d(&self) -> Option<&BigNumRef> { - unsafe { - let d = compat::key(self.0)[2]; - if d.is_null() { - None - } else { - Some(BigNumRef::from_ptr(d as *mut _)) - } - } - } - - pub fn e(&self) -> Option<&BigNumRef> { - unsafe { - let e = compat::key(self.0)[1]; - if e.is_null() { - None - } else { - Some(BigNumRef::from_ptr(e as *mut _)) - } - } - } - - pub fn p(&self) -> Option<&BigNumRef> { - unsafe { - let p = compat::factors(self.0)[0]; - if p.is_null() { - None - } else { - Some(BigNumRef::from_ptr(p as *mut _)) - } - } - } - - pub fn q(&self) -> Option<&BigNumRef> { - unsafe { - let q = compat::factors(self.0)[1]; - if q.is_null() { - None - } else { - Some(BigNumRef::from_ptr(q as *mut _)) - } - } - } } impl fmt::Debug for Rsa { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "RSA") + write!(f, "Rsa") + } +} + +impl Deref for Rsa { + type Target = RsaRef; + + fn deref(&self) -> &RsaRef { + unsafe { RsaRef::from_ptr(self.0) } } } From 287f6df6c6d76754c713120d02d3d9c5e5624089 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 17:04:55 -0700 Subject: [PATCH 125/186] Remove DsaParams --- openssl/src/dsa.rs | 56 ++++++++++++---------------------------------- 1 file changed, 14 insertions(+), 42 deletions(-) diff --git a/openssl/src/dsa.rs b/openssl/src/dsa.rs index cec1466d..e92b8ca3 100644 --- a/openssl/src/dsa.rs +++ b/openssl/src/dsa.rs @@ -11,43 +11,6 @@ use bio::{MemBio, MemBioSlice}; use util::{CallbackState, invoke_passwd_cb}; use opaque::Opaque; -/// Builder for upfront DSA parameter generation -pub struct DsaParams(*mut ffi::DSA); - -impl DsaParams { - pub fn with_size(size: u32) -> Result { - unsafe { - let dsa = DsaParams(try!(cvt_p(ffi::DSA_new()))); - try!(cvt(ffi::DSA_generate_parameters_ex(dsa.0, - size as c_int, - ptr::null(), - 0, - ptr::null_mut(), - ptr::null_mut(), - ptr::null_mut()))); - Ok(dsa) - } - } - - /// Generate a key pair from the initialized parameters - pub fn generate(self) -> Result { - unsafe { - try!(cvt(ffi::DSA_generate_key(self.0))); - let dsa = Dsa(self.0); - ::std::mem::forget(self); - Ok(dsa) - } - } -} - -impl Drop for DsaParams { - fn drop(&mut self) { - unsafe { - ffi::DSA_free(self.0); - } - } -} - pub struct DsaRef(Opaque); impl DsaRef { @@ -147,11 +110,20 @@ impl Dsa { Dsa(dsa) } - /// Generate a DSA key pair - /// For more complicated key generation scenarios see the `DSAParams` type - pub fn generate(size: u32) -> Result { - let params = try!(DsaParams::with_size(size)); - params.generate() + /// Generate a DSA key pair. + pub fn generate(bits: u32) -> Result { + unsafe { + let dsa = Dsa(try!(cvt_p(ffi::DSA_new()))); + try!(cvt(ffi::DSA_generate_parameters_ex(dsa.0, + bits as c_int, + ptr::null(), + 0, + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut()))); + try!(cvt(ffi::DSA_generate_key(dsa .0))); + Ok(dsa) + } } /// Reads a DSA private key from PEM formatted data. From bd457dba1860576f2308414daaafc3dc5b22f420 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 17:18:37 -0700 Subject: [PATCH 126/186] Move HandshakeError to submodule --- openssl/src/ssl/error.rs | 55 +++++++++++++++++++++++++++++++++++++ openssl/src/ssl/mod.rs | 58 ++-------------------------------------- 2 files changed, 57 insertions(+), 56 deletions(-) diff --git a/openssl/src/ssl/error.rs b/openssl/src/ssl/error.rs index 95213361..518ae90f 100644 --- a/openssl/src/ssl/error.rs +++ b/openssl/src/ssl/error.rs @@ -1,8 +1,11 @@ +use std::any::Any; use std::error; use std::error::Error as StdError; use std::fmt; use std::io; + use error::ErrorStack; +use ssl::MidHandshakeSslStream; /// An SSL error. #[derive(Debug)] @@ -62,3 +65,55 @@ impl From for Error { Error::Ssl(e) } } + +/// An error or intermediate state after a TLS handshake attempt. +#[derive(Debug)] +pub enum HandshakeError { + /// Setup failed. + SetupFailure(ErrorStack), + /// The handshake failed. + Failure(MidHandshakeSslStream), + /// The handshake was interrupted midway through. + Interrupted(MidHandshakeSslStream), +} + +impl StdError for HandshakeError { + fn description(&self) -> &str { + match *self { + HandshakeError::SetupFailure(_) => "stream setup failed", + HandshakeError::Failure(_) => "the handshake failed", + HandshakeError::Interrupted(_) => "the handshake was interrupted", + } + } + + fn cause(&self) -> Option<&StdError> { + match *self { + HandshakeError::SetupFailure(ref e) => Some(e), + HandshakeError::Failure(ref s) | + HandshakeError::Interrupted(ref s) => Some(s.error()), + } + } +} + +impl fmt::Display for HandshakeError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(f.write_str(StdError::description(self))); + match *self { + HandshakeError::SetupFailure(ref e) => try!(write!(f, ": {}", e)), + HandshakeError::Failure(ref s) | + HandshakeError::Interrupted(ref s) => { + try!(write!(f, ": {}", s.error())); + if let Some(err) = s.ssl().verify_result() { + try!(write!(f, ": {}", err)); + } + } + } + Ok(()) + } +} + +impl From for HandshakeError { + fn from(e: ErrorStack) -> HandshakeError { + HandshakeError::SetupFailure(e) + } +} diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index c1630996..71127138 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -73,7 +73,6 @@ use std::any::Any; use std::any::TypeId; use std::cmp; use std::collections::HashMap; -use std::error as stderror; use std::ffi::{CStr, CString}; use std::fmt; use std::io; @@ -99,7 +98,7 @@ use pkey::PKeyRef; use error::ErrorStack; use opaque::Opaque; -pub mod error; +mod error; mod connector; mod bio; #[cfg(test)] @@ -109,8 +108,7 @@ use self::bio::BioMethod; pub use ssl::connector::{ClientConnectorBuilder, ClientConnector, ServerConnectorBuilder, ServerConnector}; -#[doc(inline)] -pub use ssl::error::Error; +pub use ssl::error::{Error, HandshakeError}; bitflags! { pub flags SslOptions: c_ulong { @@ -1223,58 +1221,6 @@ impl Ssl { } } -/// An error or intermediate state after a TLS handshake attempt. -#[derive(Debug)] -pub enum HandshakeError { - /// Setup failed. - SetupFailure(ErrorStack), - /// The handshake failed. - Failure(MidHandshakeSslStream), - /// The handshake was interrupted midway through. - Interrupted(MidHandshakeSslStream), -} - -impl stderror::Error for HandshakeError { - fn description(&self) -> &str { - match *self { - HandshakeError::SetupFailure(_) => "stream setup failed", - HandshakeError::Failure(_) => "the handshake failed", - HandshakeError::Interrupted(_) => "the handshake was interrupted", - } - } - - fn cause(&self) -> Option<&stderror::Error> { - match *self { - HandshakeError::SetupFailure(ref e) => Some(e), - HandshakeError::Failure(ref s) | - HandshakeError::Interrupted(ref s) => Some(s.error()), - } - } -} - -impl fmt::Display for HandshakeError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(f.write_str(stderror::Error::description(self))); - match *self { - HandshakeError::SetupFailure(ref e) => try!(write!(f, ": {}", e)), - HandshakeError::Failure(ref s) | - HandshakeError::Interrupted(ref s) => { - try!(write!(f, ": {}", s.error())); - if let Some(err) = s.ssl().verify_result() { - try!(write!(f, ": {}", err)); - } - } - } - Ok(()) - } -} - -impl From for HandshakeError { - fn from(e: ErrorStack) -> HandshakeError { - HandshakeError::SetupFailure(e) - } -} - /// An SSL stream midway through the handshake process. #[derive(Debug)] pub struct MidHandshakeSslStream { From 997e92e052301e633fd6560bc5a369fc0d965f8d Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 18:49:29 -0700 Subject: [PATCH 127/186] Merge ssl option setup The client will ignore server-side options so we may as well stick them all in the same spot. --- openssl/src/ssl/connector.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index bea54a4e..94784e81 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -34,6 +34,9 @@ fn ctx(method: SslMethod) -> Result { opts &= !ssl::SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; opts |= ssl::SSL_OP_NO_SSLV2; opts |= ssl::SSL_OP_NO_SSLV3; + opts |= ssl::SSL_OP_SINGLE_DH_USE; + opts |= ssl::SSL_OP_SINGLE_ECDH_USE; + opts |= ssl::SSL_OP_CIPHER_SERVER_PREFERENCE; ctx.set_options(opts); Ok(ctx) @@ -117,8 +120,6 @@ impl ServerConnectorBuilder { I::Item: AsRef { let mut ctx = try!(ctx(method)); - ctx.set_options(ssl::SSL_OP_SINGLE_DH_USE | ssl::SSL_OP_SINGLE_ECDH_USE | - ssl::SSL_OP_CIPHER_SERVER_PREFERENCE); let dh = try!(Dh::from_pem(DHPARAM_PEM.as_bytes())); try!(ctx.set_tmp_dh(&dh)); try!(setup_curves(&mut ctx)); @@ -151,7 +152,6 @@ impl ServerConnectorBuilder { I::Item: AsRef { let mut ctx = try!(ctx(method)); - ctx.set_options(ssl::SSL_OP_SINGLE_ECDH_USE | ssl::SSL_OP_CIPHER_SERVER_PREFERENCE); try!(setup_curves(&mut ctx)); try!(ctx.set_cipher_list( "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:\ From add8e4023e826a21616e909921a9f1ae2a4b4223 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 19:39:18 -0700 Subject: [PATCH 128/186] Rename connectors --- openssl/src/ssl/connector.rs | 50 ++++++++++++++++++------------------ openssl/src/ssl/mod.rs | 28 ++++++++++---------- openssl/src/ssl/tests/mod.rs | 20 +++++++-------- 3 files changed, 50 insertions(+), 48 deletions(-) diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index 94784e81..dd7656dd 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -42,14 +42,14 @@ fn ctx(method: SslMethod) -> Result { Ok(ctx) } -/// A builder for `ClientConnector`s. -pub struct ClientConnectorBuilder(SslContextBuilder); +/// A builder for `SslConnector`s. +pub struct SslConnectorBuilder(SslContextBuilder); -impl ClientConnectorBuilder { +impl SslConnectorBuilder { /// Creates a new builder for TLS connections. /// /// The default configuration is subject to change, and is currently derived from Python. - pub fn new(method: SslMethod) -> Result { + pub fn new(method: SslMethod) -> Result { let mut ctx = try!(ctx(method)); try!(ctx.set_default_verify_paths()); // From https://github.com/python/cpython/blob/c30098c8c6014f3340a369a31df9c74bdbacc269/Lib/ssl.py#L191 @@ -57,7 +57,7 @@ impl ClientConnectorBuilder { "ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:ECDH+AES128:\ DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:!aNULL:!eNULL:!MD5:!3DES")); - Ok(ClientConnectorBuilder(ctx)) + Ok(SslConnectorBuilder(ctx)) } /// Returns a shared reference to the inner `SslContextBuilder`. @@ -70,9 +70,9 @@ impl ClientConnectorBuilder { &mut self.0 } - /// Consumes the builder, returning a `ClientConnector`. - pub fn build(self) -> ClientConnector { - ClientConnector(self.0.build()) + /// Consumes the builder, returning a `SslConnector`. + pub fn build(self) -> SslConnector { + SslConnector(self.0.build()) } } @@ -83,9 +83,9 @@ impl ClientConnectorBuilder { /// /// OpenSSL's built in hostname verification is used when linking against OpenSSL 1.0.2 or 1.1.0, /// and a custom implementation is used when linking against OpenSSL 1.0.1. -pub struct ClientConnector(SslContext); +pub struct SslConnector(SslContext); -impl ClientConnector { +impl SslConnector { /// Initiates a client-side TLS session on a stream. /// /// The domain is used for SNI and hostname verification. @@ -100,10 +100,10 @@ impl ClientConnector { } } -/// A builder for `ServerConnector`s. -pub struct ServerConnectorBuilder(SslContextBuilder); +/// A builder for `SslAcceptor`s. +pub struct SslAcceptorBuilder(SslContextBuilder); -impl ServerConnectorBuilder { +impl SslAcceptorBuilder { /// Creates a new builder configured to connect to non-legacy clients. This should generally be /// considered a reasonable default choice. /// @@ -115,7 +115,7 @@ impl ServerConnectorBuilder { private_key: &PKeyRef, certificate: &X509Ref, chain: I) - -> Result + -> Result where I: IntoIterator, I::Item: AsRef { @@ -134,7 +134,7 @@ impl ServerConnectorBuilder { DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:\ EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:\ AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS")); - ServerConnectorBuilder::finish_setup(ctx, private_key, certificate, chain) + SslAcceptorBuilder::finish_setup(ctx, private_key, certificate, chain) } /// Creates a new builder configured to connect to modern clients. @@ -147,7 +147,7 @@ impl ServerConnectorBuilder { private_key: &PKeyRef, certificate: &X509Ref, chain: I) - -> Result + -> Result where I: IntoIterator, I::Item: AsRef { @@ -159,14 +159,14 @@ impl ServerConnectorBuilder { ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:\ ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:\ ECDHE-RSA-AES128-SHA256")); - ServerConnectorBuilder::finish_setup(ctx, private_key, certificate, chain) + SslAcceptorBuilder::finish_setup(ctx, private_key, certificate, chain) } fn finish_setup(mut ctx: SslContextBuilder, private_key: &PKeyRef, certificate: &X509Ref, chain: I) - -> Result + -> Result where I: IntoIterator, I::Item: AsRef { @@ -176,7 +176,7 @@ impl ServerConnectorBuilder { for cert in chain { try!(ctx.add_extra_chain_cert(cert.as_ref().to_owned())); } - Ok(ServerConnectorBuilder(ctx)) + Ok(SslAcceptorBuilder(ctx)) } /// Returns a shared reference to the inner `SslContextBuilder`. @@ -189,9 +189,9 @@ impl ServerConnectorBuilder { &mut self.0 } - /// Consumes the builder, returning a `ServerConnector`. - pub fn build(self) -> ServerConnector { - ServerConnector(self.0.build()) + /// Consumes the builder, returning a `SslAcceptor`. + pub fn build(self) -> SslAcceptor { + SslAcceptor(self.0.build()) } } @@ -215,11 +215,11 @@ fn setup_curves(_: &mut SslContextBuilder) -> Result<(), ErrorStack> { /// /// OpenSSL's default configuration is highly insecure. This connector manages the OpenSSL /// structures, configuring cipher suites, session options, and more. -pub struct ServerConnector(SslContext); +pub struct SslAcceptor(SslContext); -impl ServerConnector { +impl SslAcceptor { /// Initiates a server-side TLS session on a stream. - pub fn connect(&self, stream: S) -> Result, HandshakeError> + pub fn accept(&self, stream: S) -> Result, HandshakeError> where S: Read + Write { let ssl = try!(Ssl::new(&self.0)); diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 71127138..8cc1c600 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -1,6 +1,6 @@ //! SSL/TLS support. //! -//! The `ClientConnector` and `ServerConnector` should be used in most cases - they handle +//! The `SslConnector` and `SslAcceptor` should be used in most cases - they handle //! configuration of the OpenSSL primitives for you. //! //! # Examples @@ -8,11 +8,11 @@ //! To connect as a client to a remote server: //! //! ``` -//! use openssl::ssl::{SslMethod, ClientConnectorBuilder}; +//! use openssl::ssl::{SslMethod, SslConnectorBuilder}; //! use std::io::{Read, Write}; //! use std::net::TcpStream; //! -//! let connector = ClientConnectorBuilder::new(SslMethod::tls()).unwrap().build(); +//! let connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap().build(); //! //! let stream = TcpStream::connect("google.com:443").unwrap(); //! let mut stream = connector.connect("google.com", stream).unwrap(); @@ -27,7 +27,7 @@ //! //! ```no_run //! use openssl::pkcs12::Pkcs12; -//! use openssl::ssl::{SslMethod, ServerConnectorBuilder, SslStream}; +//! use openssl::ssl::{SslMethod, SslAcceptorBuilder, SslStream}; //! use std::fs::File; //! use std::io::{Read, Write}; //! use std::net::{TcpListener, TcpStream}; @@ -43,11 +43,13 @@ //! let pkcs12 = Pkcs12::from_der(&pkcs12).unwrap(); //! let identity = pkcs12.parse("password123").unwrap(); //! -//! let connector = ServerConnectorBuilder::mozilla_intermediate( -//! SslMethod::tls(), &identity.pkey, &identity.cert, &identity.chain) +//! let acceptor = SslAcceptorBuilder::mozilla_intermediate(SslMethod::tls(), +//! &identity.pkey, +//! &identity.cert, +//! &identity.chain) //! .unwrap() //! .build(); -//! let connector = Arc::new(connector); +//! let acceptor = Arc::new(acceptor); //! //! let listener = TcpListener::bind("0.0.0.0:8443").unwrap(); //! @@ -58,9 +60,9 @@ //! for stream in listener.incoming() { //! match stream { //! Ok(stream) => { -//! let connector = connector.clone(); +//! let acceptor = acceptor.clone(); //! thread::spawn(move || { -//! let stream = connector.connect(stream).unwrap(); +//! let stream = acceptor.accept(stream).unwrap(); //! handle_client(stream); //! }); //! } @@ -106,8 +108,8 @@ mod tests; use self::bio::BioMethod; -pub use ssl::connector::{ClientConnectorBuilder, ClientConnector, ServerConnectorBuilder, - ServerConnector}; +pub use ssl::connector::{SslConnectorBuilder, SslConnector, SslAcceptorBuilder, + SslAcceptor}; pub use ssl::error::{Error, HandshakeError}; bitflags! { @@ -1161,7 +1163,7 @@ impl Ssl { /// # Warning /// /// OpenSSL's default configuration is insecure. It is highly recommended to use - /// `ClientConnector` rather than `Ssl` directly, as it manages that configuration. + /// `SslConnector` rather than `Ssl` directly, as it manages that configuration. pub fn connect(self, stream: S) -> Result, HandshakeError> where S: Read + Write { @@ -1193,7 +1195,7 @@ impl Ssl { /// # Warning /// /// OpenSSL's default configuration is insecure. It is highly recommended to use - /// `ServerConnector` rather than `Ssl` directly, as it manages that configuration. + /// `SslAcceptor` rather than `Ssl` directly, as it manages that configuration. pub fn accept(self, stream: S) -> Result, HandshakeError> where S: Read + Write { diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 5e42d5c0..5ddcb031 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -18,8 +18,8 @@ use hash::MessageDigest; use ssl; use ssl::SSL_VERIFY_PEER; use ssl::{SslMethod, HandshakeError}; -use ssl::{SslContext, SslStream, Ssl, ShutdownResult, ClientConnectorBuilder, - ServerConnectorBuilder, Error}; +use ssl::{SslContext, SslStream, Ssl, ShutdownResult, SslConnectorBuilder, + SslAcceptorBuilder, Error}; use x509::X509StoreContextRef; use x509::X509FileType; use x509::X509; @@ -1085,7 +1085,7 @@ fn verify_invalid_hostname() { #[test] fn connector_valid_hostname() { - let connector = ClientConnectorBuilder::new(SslMethod::tls()).unwrap().build(); + let connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap().build(); let s = TcpStream::connect("google.com:443").unwrap(); let mut socket = connector.connect("google.com", s).unwrap(); @@ -1101,7 +1101,7 @@ fn connector_valid_hostname() { #[test] fn connector_invalid_hostname() { - let connector = ClientConnectorBuilder::new(SslMethod::tls()).unwrap().build(); + let connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap().build(); let s = TcpStream::connect("google.com:443").unwrap(); assert!(connector.connect("foobar.com", s).is_err()); @@ -1115,19 +1115,19 @@ fn connector_client_server_mozilla_intermediate() { let t = thread::spawn(move || { let key = PKey::private_key_from_pem(KEY).unwrap(); let cert = X509::from_pem(CERT).unwrap(); - let connector = ServerConnectorBuilder::mozilla_intermediate(SslMethod::tls(), + let connector = SslAcceptorBuilder::mozilla_intermediate(SslMethod::tls(), &key, &cert, None::) .unwrap() .build(); let stream = listener.accept().unwrap().0; - let mut stream = connector.connect(stream).unwrap(); + let mut stream = connector.accept(stream).unwrap(); stream.write_all(b"hello").unwrap(); }); - let mut connector = ClientConnectorBuilder::new(SslMethod::tls()).unwrap(); + let mut connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap(); connector.context_mut().set_CA_file("test/root-ca.pem").unwrap(); let connector = connector.build(); @@ -1150,16 +1150,16 @@ fn connector_client_server_mozilla_modern() { let key = PKey::private_key_from_pem(KEY).unwrap(); let cert = X509::from_pem(CERT).unwrap(); let connector = - ServerConnectorBuilder::mozilla_modern(SslMethod::tls(), &key, &cert, None::) + SslAcceptorBuilder::mozilla_modern(SslMethod::tls(), &key, &cert, None::) .unwrap() .build(); let stream = listener.accept().unwrap().0; - let mut stream = connector.connect(stream).unwrap(); + let mut stream = connector.accept(stream).unwrap(); stream.write_all(b"hello").unwrap(); }); - let mut connector = ClientConnectorBuilder::new(SslMethod::tls()).unwrap(); + let mut connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap(); connector.context_mut().set_CA_file("test/root-ca.pem").unwrap(); let connector = connector.build(); From 5b0fc9a185bdcf204ff450f0d64cbc2198d154c4 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 20:34:35 -0700 Subject: [PATCH 129/186] Impl Sync and Send for SslContextBuilder --- openssl/src/ssl/mod.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 8cc1c600..954bb5e7 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -415,6 +415,9 @@ pub enum SniError { /// A builder for `SslContext`s. pub struct SslContextBuilder(*mut ffi::SSL_CTX); +unsafe impl Sync for SslContextBuilder {} +unsafe impl Send for SslContextBuilder {} + impl Drop for SslContextBuilder { fn drop(&mut self) { unsafe { ffi::SSL_CTX_free(self.as_ptr()) } From e0211dac30756f19f515962afb3f50a6ca489a69 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 21:39:26 -0700 Subject: [PATCH 130/186] Rename set_CA_file --- openssl/src/ssl/mod.rs | 3 +-- openssl/src/ssl/tests/mod.rs | 32 ++++++++++++++++---------------- 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 954bb5e7..2aea5af4 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -519,9 +519,8 @@ impl SslContextBuilder { unsafe { cvt(ffi::SSL_CTX_set_default_verify_paths(self.as_ptr())).map(|_| ()) } } - #[allow(non_snake_case)] /// Specifies the file that contains trusted CA certificates. - pub fn set_CA_file>(&mut self, file: P) -> Result<(), ErrorStack> { + pub fn set_ca_file>(&mut self, file: P) -> Result<(), ErrorStack> { let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap(); unsafe { cvt(ffi::SSL_CTX_load_verify_locations(self.as_ptr(), diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 5ddcb031..61eac063 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -209,7 +209,7 @@ run_test!(verify_trusted, |method, stream| { let mut ctx = SslContext::builder(method).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { + match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } @@ -240,7 +240,7 @@ run_test!(verify_trusted_callback_override_ok, |method, stream| { let mut ctx = SslContext::builder(method).unwrap(); ctx.set_verify_callback(SSL_VERIFY_PEER, |_, _| true); - match ctx.set_CA_file(&Path::new("test/cert.pem")) { + match ctx.set_ca_file(&Path::new("test/cert.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } @@ -254,7 +254,7 @@ run_test!(verify_trusted_callback_override_bad, |method, stream| { let mut ctx = SslContext::builder(method).unwrap(); ctx.set_verify_callback(SSL_VERIFY_PEER, |_, _| false); - match ctx.set_CA_file(&Path::new("test/cert.pem")) { + match ctx.set_ca_file(&Path::new("test/cert.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } @@ -278,7 +278,7 @@ run_test!(verify_trusted_get_error_ok, |method, stream| { true }); - match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { + match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } @@ -497,7 +497,7 @@ fn test_connect_with_unilateral_alpn() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); - match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { + match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } @@ -518,7 +518,7 @@ fn test_connect_with_unilateral_npn() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); - match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { + match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } @@ -540,7 +540,7 @@ fn test_connect_with_alpn_successful_multiple_matching() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"spdy/3.1", b"http/1.1"]).unwrap(); - match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { + match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } @@ -562,7 +562,7 @@ fn test_connect_with_npn_successful_multiple_matching() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"spdy/3.1", b"http/1.1"]).unwrap(); - match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { + match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } @@ -585,7 +585,7 @@ fn test_connect_with_alpn_successful_single_match() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"spdy/3.1"]).unwrap(); - match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { + match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } @@ -609,7 +609,7 @@ fn test_connect_with_npn_successful_single_match() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"spdy/3.1"]).unwrap(); - match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { + match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } @@ -648,7 +648,7 @@ fn test_npn_server_advertise_multiple() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"spdy/3.1"]).unwrap(); - match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { + match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } @@ -689,7 +689,7 @@ fn test_alpn_server_advertise_multiple() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"spdy/3.1"]).unwrap(); - match ctx.set_CA_file(&Path::new("test/root-ca.pem")) { + match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { Ok(_) => {} Err(err) => panic!("Unexpected error {:?}", err), } @@ -730,7 +730,7 @@ fn test_alpn_server_select_none() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/2"]).unwrap(); - ctx.set_CA_file(&Path::new("test/root-ca.pem")).unwrap(); + ctx.set_ca_file(&Path::new("test/root-ca.pem")).unwrap(); // Now connect to the socket and make sure the protocol negotiation works... let stream = TcpStream::connect(localhost).unwrap(); let stream = Ssl::new(&ctx.build()).unwrap().connect(stream).unwrap(); @@ -765,7 +765,7 @@ fn test_alpn_server_select_none() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/2"]).unwrap(); - ctx.set_CA_file(&Path::new("test/root-ca.pem")).unwrap(); + ctx.set_ca_file(&Path::new("test/root-ca.pem")).unwrap(); // Now connect to the socket and make sure the protocol negotiation works... let stream = TcpStream::connect(localhost).unwrap(); assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_err()); @@ -1128,7 +1128,7 @@ fn connector_client_server_mozilla_intermediate() { }); let mut connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap(); - connector.context_mut().set_CA_file("test/root-ca.pem").unwrap(); + connector.context_mut().set_ca_file("test/root-ca.pem").unwrap(); let connector = connector.build(); let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); @@ -1160,7 +1160,7 @@ fn connector_client_server_mozilla_modern() { }); let mut connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap(); - connector.context_mut().set_CA_file("test/root-ca.pem").unwrap(); + connector.context_mut().set_ca_file("test/root-ca.pem").unwrap(); let connector = connector.build(); let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); From 558124b7555539e09292b61be057d9ba24e64bf5 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 22:02:26 -0700 Subject: [PATCH 131/186] Expose SSL_MODEs --- openssl-sys/src/lib.rs | 10 ++++++-- openssl/src/dh.rs | 5 +--- openssl/src/hash.rs | 4 +-- openssl/src/ssl/connector.rs | 46 ++++++++++++++++++--------------- openssl/src/ssl/mod.rs | 49 ++++++++++++++++++++++-------------- openssl/src/ssl/tests/mod.rs | 14 +++++------ 6 files changed, 72 insertions(+), 56 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 8fd287f7..755277e4 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1051,8 +1051,14 @@ pub const SSL_CTRL_SET_TLSEXT_SERVERNAME_CB: c_int = 53; pub const SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG: c_int = 54; pub const SSL_CTRL_SET_TLSEXT_HOSTNAME: c_int = 55; -pub const SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER: c_long = 2; -pub const SSL_MODE_AUTO_RETRY: c_long = 4; +pub const SSL_MODE_ENABLE_PARTIAL_WRITE: c_long = 0x1; +pub const SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER: c_long = 0x2; +pub const SSL_MODE_AUTO_RETRY: c_long = 0x4; +pub const SSL_MODE_NO_AUTO_CHAIN: c_long = 0x8; +pub const SSL_MODE_RELEASE_BUFFERS: c_long = 0x10; +pub const SSL_MODE_SEND_CLIENTHELLO_TIME: c_long = 0x20; +pub const SSL_MODE_SEND_SERVERHELLO_TIME: c_long = 0x40; +pub const SSL_MODE_SEND_FALLBACK_SCSV: c_long = 0x80; pub const SSL_ERROR_NONE: c_int = 0; pub const SSL_ERROR_SSL: c_int = 1; diff --git a/openssl/src/dh.rs b/openssl/src/dh.rs index f2659eb3..5c5ea05e 100644 --- a/openssl/src/dh.rs +++ b/openssl/src/dh.rs @@ -27,10 +27,7 @@ impl Dh { pub fn from_params(p: BigNum, g: BigNum, q: BigNum) -> Result { unsafe { let dh = Dh(try!(cvt_p(ffi::DH_new()))); - try!(cvt(compat::DH_set0_pqg(dh.0, - p.as_ptr(), - q.as_ptr(), - g.as_ptr()))); + try!(cvt(compat::DH_set0_pqg(dh.0, p.as_ptr(), q.as_ptr(), g.as_ptr()))); mem::forget((p, g, q)); Ok(dh) } diff --git a/openssl/src/hash.rs b/openssl/src/hash.rs index c91976bf..6a13371d 100644 --- a/openssl/src/hash.rs +++ b/openssl/src/hash.rs @@ -135,9 +135,7 @@ impl Hasher { try!(self.init()); } unsafe { - try!(cvt(ffi::EVP_DigestUpdate(self.ctx, - data.as_ptr() as *mut _, - data.len()))); + try!(cvt(ffi::EVP_DigestUpdate(self.ctx, data.as_ptr() as *mut _, data.len()))); } self.state = Updated; Ok(()) diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index dd7656dd..c7bfb209 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -39,6 +39,10 @@ fn ctx(method: SslMethod) -> Result { opts |= ssl::SSL_OP_CIPHER_SERVER_PREFERENCE; ctx.set_options(opts); + let mode = ssl::SSL_MODE_AUTO_RETRY | ssl::SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | + ssl::SSL_MODE_ENABLE_PARTIAL_WRITE; + ctx.set_mode(mode); + Ok(ctx) } @@ -53,9 +57,9 @@ impl SslConnectorBuilder { let mut ctx = try!(ctx(method)); try!(ctx.set_default_verify_paths()); // From https://github.com/python/cpython/blob/c30098c8c6014f3340a369a31df9c74bdbacc269/Lib/ssl.py#L191 - try!(ctx.set_cipher_list( - "ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:ECDH+AES128:\ - DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:!aNULL:!eNULL:!MD5:!3DES")); + try!(ctx.set_cipher_list("ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:\ + DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:\ + RSA+AES:RSA+HIGH:!aNULL:!eNULL:!MD5:!3DES")); Ok(SslConnectorBuilder(ctx)) } @@ -123,17 +127,20 @@ impl SslAcceptorBuilder { let dh = try!(Dh::from_pem(DHPARAM_PEM.as_bytes())); try!(ctx.set_tmp_dh(&dh)); try!(setup_curves(&mut ctx)); - try!(ctx.set_cipher_list( - "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:\ - ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:\ - ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:\ - DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:\ - ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:\ - ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:\ - ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:\ - DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:\ - EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:\ - AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS")); + try!(ctx.set_cipher_list("ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:\ + ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:\ + ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:\ + DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:\ + ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:\ + ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:\ + ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:\ + ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:\ + DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:\ + DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:\ + ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:\ + EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:\ + AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:\ + DES-CBC3-SHA:!DSS")); SslAcceptorBuilder::finish_setup(ctx, private_key, certificate, chain) } @@ -153,12 +160,11 @@ impl SslAcceptorBuilder { { let mut ctx = try!(ctx(method)); try!(setup_curves(&mut ctx)); - try!(ctx.set_cipher_list( - "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:\ - ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:\ - ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:\ - ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:\ - ECDHE-RSA-AES128-SHA256")); + try!(ctx.set_cipher_list("ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:\ + ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:\ + ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:\ + ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:\ + ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256")); SslAcceptorBuilder::finish_setup(ctx, private_key, certificate, chain) } diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 2aea5af4..3aa509f4 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -108,12 +108,11 @@ mod tests; use self::bio::BioMethod; -pub use ssl::connector::{SslConnectorBuilder, SslConnector, SslAcceptorBuilder, - SslAcceptor}; +pub use ssl::connector::{SslConnectorBuilder, SslConnector, SslAcceptorBuilder, SslAcceptor}; pub use ssl::error::{Error, HandshakeError}; bitflags! { - pub flags SslOptions: c_ulong { + pub flags SslOption: c_ulong { const SSL_OP_MICROSOFT_SESS_ID_BUG = ffi::SSL_OP_MICROSOFT_SESS_ID_BUG, const SSL_OP_NETSCAPE_CHALLENGE_BUG = ffi::SSL_OP_NETSCAPE_CHALLENGE_BUG, const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = @@ -154,6 +153,19 @@ bitflags! { } } +bitflags! { + pub flags SslMode: c_long { + const SSL_MODE_ENABLE_PARTIAL_WRITE = ffi::SSL_MODE_ENABLE_PARTIAL_WRITE, + const SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER = ffi::SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER, + const SSL_MODE_AUTO_RETRY = ffi::SSL_MODE_AUTO_RETRY, + const SSL_MODE_NO_AUTO_CHAIN = ffi::SSL_MODE_NO_AUTO_CHAIN, + const SSL_MODE_RELEASE_BUFFERS = ffi::SSL_MODE_RELEASE_BUFFERS, + const SSL_MODE_SEND_CLIENTHELLO_TIME = ffi::SSL_MODE_SEND_CLIENTHELLO_TIME, + const SSL_MODE_SEND_SERVERHELLO_TIME = ffi::SSL_MODE_SEND_SERVERHELLO_TIME, + const SSL_MODE_SEND_FALLBACK_SCSV = ffi::SSL_MODE_SEND_FALLBACK_SCSV, + } +} + #[derive(Copy, Clone)] pub struct SslMethod(*const ffi::SSL_METHOD); @@ -426,16 +438,12 @@ impl Drop for SslContextBuilder { impl SslContextBuilder { pub fn new(method: SslMethod) -> Result { - init(); - - let mut ctx = unsafe { + unsafe { + init(); let ctx = try!(cvt_p(ffi::SSL_CTX_new(method.as_ptr()))); - SslContextBuilder::from_ptr(ctx) - }; - try!(ctx.set_mode(ffi::SSL_MODE_AUTO_RETRY | ffi::SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)); - - Ok(ctx) + Ok(SslContextBuilder::from_ptr(ctx)) + } } pub unsafe fn from_ptr(ctx: *mut ffi::SSL_CTX) -> SslContextBuilder { @@ -498,8 +506,11 @@ impl SslContextBuilder { } } - fn set_mode(&mut self, mode: c_long) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::SSL_CTX_set_mode(self.as_ptr(), mode) as c_int).map(|_| ()) } + pub fn set_mode(&mut self, mode: SslMode) -> SslMode { + unsafe { + let mode = ffi::SSL_CTX_set_mode(self.as_ptr(), mode.bits()); + SslMode::from_bits(mode).unwrap() + } } pub fn set_tmp_dh(&mut self, dh: &DhRef) -> Result<(), ErrorStack> { @@ -630,19 +641,19 @@ impl SslContextBuilder { unsafe { cvt(ffi::SSL_CTX_set_ecdh_auto(self.as_ptr(), onoff as c_int)).map(|_| ()) } } - pub fn set_options(&mut self, option: SslOptions) -> SslOptions { + pub fn set_options(&mut self, option: SslOption) -> SslOption { let ret = unsafe { compat::SSL_CTX_set_options(self.as_ptr(), option.bits()) }; - SslOptions::from_bits(ret).unwrap() + SslOption::from_bits(ret).unwrap() } - pub fn options(&self) -> SslOptions { + pub fn options(&self) -> SslOption { let ret = unsafe { compat::SSL_CTX_get_options(self.as_ptr()) }; - SslOptions::from_bits(ret).unwrap() + SslOption::from_bits(ret).unwrap() } - pub fn clear_options(&mut self, option: SslOptions) -> SslOptions { + pub fn clear_options(&mut self, option: SslOption) -> SslOption { let ret = unsafe { compat::SSL_CTX_clear_options(self.as_ptr(), option.bits()) }; - SslOptions::from_bits(ret).unwrap() + SslOption::from_bits(ret).unwrap() } /// Set the protocols to be used during Next Protocol Negotiation (the protocols diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 61eac063..a874fe3b 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -18,8 +18,8 @@ use hash::MessageDigest; use ssl; use ssl::SSL_VERIFY_PEER; use ssl::{SslMethod, HandshakeError}; -use ssl::{SslContext, SslStream, Ssl, ShutdownResult, SslConnectorBuilder, - SslAcceptorBuilder, Error}; +use ssl::{SslContext, SslStream, Ssl, ShutdownResult, SslConnectorBuilder, SslAcceptorBuilder, + Error}; use x509::X509StoreContextRef; use x509::X509FileType; use x509::X509; @@ -1115,12 +1115,10 @@ fn connector_client_server_mozilla_intermediate() { let t = thread::spawn(move || { let key = PKey::private_key_from_pem(KEY).unwrap(); let cert = X509::from_pem(CERT).unwrap(); - let connector = SslAcceptorBuilder::mozilla_intermediate(SslMethod::tls(), - &key, - &cert, - None::) - .unwrap() - .build(); + let connector = + SslAcceptorBuilder::mozilla_intermediate(SslMethod::tls(), &key, &cert, None::) + .unwrap() + .build(); let stream = listener.accept().unwrap().0; let mut stream = connector.accept(stream).unwrap(); From 006da592857b9a3d3cdc5bc35056101bb61954a4 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 30 Oct 2016 22:42:32 -0700 Subject: [PATCH 132/186] Return an SslRef --- openssl/src/ssl/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 3aa509f4..5466f26e 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -1255,7 +1255,7 @@ impl MidHandshakeSslStream { } /// Returns a shared reference to the `Ssl` of the stream. - pub fn ssl(&self) -> &Ssl { + pub fn ssl(&self) -> &SslRef { self.stream.ssl() } @@ -1437,7 +1437,7 @@ impl SslStream { } /// Returns the OpenSSL `Ssl` object associated with this stream. - pub fn ssl(&self) -> &Ssl { + pub fn ssl(&self) -> &SslRef { &self.ssl } } From f22955315839a2aa03fcfc1f0c3e00da4844915b Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 31 Oct 2016 19:58:04 -0700 Subject: [PATCH 133/186] Mention 0.7 README --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 54f208b4..cb154412 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,12 @@ [Documentation](https://sfackler.github.io/rust-openssl/doc/v0.8.3/openssl). +## Warning + +This README does not correspond to rust-openssl 0.7.x. See +[here](https://github.com/sfackler/rust-openssl/blob/b8fb29db5c246175a096260eacca38180cd77dd0/README.md) +for that README. + ## Building rust-openssl depends on the OpenSSL runtime libraries version 1.0.1 or above. From 927c3e924cd894cb4b32efff666f949a294ab7c7 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 31 Oct 2016 19:37:21 -0700 Subject: [PATCH 134/186] Add a generic Ref type --- openssl/src/bn.rs | 15 +-------------- openssl/src/lib.rs | 39 +++++++++++++++++++++++++++++++++++++++ openssl/src/types.rs | 27 +++++++++++++++++++++++++++ 3 files changed, 67 insertions(+), 14 deletions(-) create mode 100644 openssl/src/types.rs diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs index 78684d0a..ab5f7769 100644 --- a/openssl/src/bn.rs +++ b/openssl/src/bn.rs @@ -23,16 +23,7 @@ pub enum RNGProperty { TwoMsbOne = 1, } -/// A context object for `BigNum` operations. -pub struct BnCtx(*mut ffi::BN_CTX); - -impl Drop for BnCtx { - fn drop(&mut self) { - unsafe { - ffi::BN_CTX_free(self.0); - } - } -} +type_!(BnCtx, ffi::BN_CTX, ffi::BN_CTX_free); impl BnCtx { /// Returns a new `BnCtx`. @@ -40,10 +31,6 @@ impl BnCtx { unsafe { cvt_p(ffi::BN_CTX_new()).map(BnCtx) } } - pub fn as_ptr(&self) -> *mut ffi::BN_CTX { - self.0 - } - /// Places the result of `a * b` in `r`. pub fn mul(&mut self, r: &mut BigNumRef, diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index f335c097..8fa53f3b 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -20,6 +20,44 @@ use libc::c_int; use error::ErrorStack; +macro_rules! type_ { + ($n:ident, $c:path, $d:path) => { + pub struct $n(*mut $c); + + unsafe impl ::types::OpenSslType for $n { + type CType = $c; + + unsafe fn from_ptr(ptr: *mut $c) -> $n { + $n(ptr) + } + + fn as_ptr(&self) -> *mut $c { + self.0 + } + } + + impl Drop for $n { + fn drop(&mut self) { + unsafe { $d(self.0) } + } + } + + impl ::std::ops::Deref for $n { + type Target = ::types::Ref<$n>; + + fn deref(&self) -> &::types::Ref<$n> { + unsafe { ::types::Ref::from_ptr(self.0) } + } + } + + impl ::std::ops::DerefMut for $n { + fn deref_mut(&mut self) -> &mut ::types::Ref<$n> { + unsafe { ::types::Ref::from_ptr_mut(self.0) } + } + } + } +} + mod bio; mod opaque; mod util; @@ -37,6 +75,7 @@ pub mod pkcs12; pub mod pkcs5; pub mod pkey; pub mod rand; +pub mod types; pub mod rsa; pub mod sign; pub mod ssl; diff --git a/openssl/src/types.rs b/openssl/src/types.rs new file mode 100644 index 00000000..16829ea4 --- /dev/null +++ b/openssl/src/types.rs @@ -0,0 +1,27 @@ +use std::marker::PhantomData; + +use opaque::Opaque; + +pub unsafe trait OpenSslType { + type CType; + + unsafe fn from_ptr(ptr: *mut Self::CType) -> Self; + + fn as_ptr(&self) -> *mut Self::CType; +} + +pub struct Ref(Opaque, PhantomData); + +impl Ref { + pub unsafe fn from_ptr<'a>(ptr: *mut T::CType) -> &'a Ref { + &*(ptr as *mut _) + } + + pub unsafe fn from_ptr_mut<'a>(ptr: *mut T::CType) -> &'a mut Ref { + &mut *(ptr as *mut _) + } + + pub fn as_ptr(&self) -> *mut T::CType { + self as *const _ as *mut _ + } +} From 3363046c34ca3f968ce8b34e885d25aebac2b1f4 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 31 Oct 2016 19:45:52 -0700 Subject: [PATCH 135/186] Update bignum --- openssl/src/bn.rs | 231 ++++++++++++++++++--------------------------- openssl/src/dsa.rs | 19 ++-- openssl/src/rsa.rs | 23 ++--- 3 files changed, 114 insertions(+), 159 deletions(-) diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs index ab5f7769..7542b25a 100644 --- a/openssl/src/bn.rs +++ b/openssl/src/bn.rs @@ -3,12 +3,12 @@ use libc::c_int; use std::cmp::Ordering; use std::ffi::CString; use std::{fmt, ptr}; -use std::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub, Deref, DerefMut}; +use std::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub, Deref}; use {cvt, cvt_p, cvt_n}; use crypto::CryptoString; use error::ErrorStack; -use opaque::Opaque; +use types::{Ref, OpenSslType}; /// Specifies the desired properties of a randomly generated `BigNum`. #[derive(Copy, Clone)] @@ -33,19 +33,19 @@ impl BnCtx { /// Places the result of `a * b` in `r`. pub fn mul(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - b: &BigNumRef) + r: &mut Ref, + a: &Ref, + b: &Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_mul(r.as_ptr(), a.as_ptr(), b.as_ptr(), self.as_ptr())).map(|_| ()) } } /// Places the result of `a / b` in `dv` and `a mod b` in `rem`. pub fn div(&mut self, - dv: Option<&mut BigNumRef>, - rem: Option<&mut BigNumRef>, - a: &BigNumRef, - b: &BigNumRef) + dv: Option<&mut Ref>, + rem: Option<&mut Ref>, + a: &Ref, + b: &Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_div(dv.map(|b| b.as_ptr()).unwrap_or(ptr::null_mut()), @@ -58,25 +58,25 @@ impl BnCtx { } /// Places the result of `a²` in `r`. - pub fn sqr(&mut self, r: &mut BigNumRef, a: &BigNumRef) -> Result<(), ErrorStack> { + pub fn sqr(&mut self, r: &mut Ref, a: &Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_sqr(r.as_ptr(), a.as_ptr(), self.as_ptr())).map(|_| ()) } } /// Places the result of `a mod m` in `r`. pub fn nnmod(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - m: &BigNumRef) + r: &mut Ref, + a: &Ref, + m: &Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_nnmod(r.as_ptr(), a.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) } } /// Places the result of `(a + b) mod m` in `r`. pub fn mod_add(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - b: &BigNumRef, - m: &BigNumRef) + r: &mut Ref, + a: &Ref, + b: &Ref, + m: &Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_mod_add(r.as_ptr(), a.as_ptr(), b.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) @@ -85,10 +85,10 @@ impl BnCtx { /// Places the result of `(a - b) mod m` in `r`. pub fn mod_sub(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - b: &BigNumRef, - m: &BigNumRef) + r: &mut Ref, + a: &Ref, + b: &Ref, + m: &Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_mod_sub(r.as_ptr(), a.as_ptr(), b.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) @@ -97,10 +97,10 @@ impl BnCtx { /// Places the result of `(a * b) mod m` in `r`. pub fn mod_mul(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - b: &BigNumRef, - m: &BigNumRef) + r: &mut Ref, + a: &Ref, + b: &Ref, + m: &Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_mod_mul(r.as_ptr(), a.as_ptr(), b.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) @@ -109,28 +109,28 @@ impl BnCtx { /// Places the result of `a² mod m` in `r`. pub fn mod_sqr(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - m: &BigNumRef) + r: &mut Ref, + a: &Ref, + m: &Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_mod_sqr(r.as_ptr(), a.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) } } /// Places the result of `a^p` in `r`. pub fn exp(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - p: &BigNumRef) + r: &mut Ref, + a: &Ref, + p: &Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_exp(r.as_ptr(), a.as_ptr(), p.as_ptr(), self.0)).map(|_| ()) } } /// Places the result of `a^p mod m` in `r`. pub fn mod_exp(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - p: &BigNumRef, - m: &BigNumRef) + r: &mut Ref, + a: &Ref, + p: &Ref, + m: &Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_mod_exp(r.as_ptr(), a.as_ptr(), p.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) @@ -139,9 +139,9 @@ impl BnCtx { /// Places the inverse of `a` modulo `n` in `r`. pub fn mod_inverse(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - n: &BigNumRef) + r: &mut Ref, + a: &Ref, + n: &Ref) -> Result<(), ErrorStack> { unsafe { cvt_p(ffi::BN_mod_inverse(r.as_ptr(), a.as_ptr(), n.as_ptr(), self.as_ptr())) @@ -151,9 +151,9 @@ impl BnCtx { /// Places the greatest common denominator of `a` and `b` in `r`. pub fn gcd(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - b: &BigNumRef) + r: &mut Ref, + a: &Ref, + b: &Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_gcd(r.as_ptr(), a.as_ptr(), b.as_ptr(), self.as_ptr())).map(|_| ()) } } @@ -163,7 +163,7 @@ impl BnCtx { /// Performs a Miller-Rabin probabilistic primality test with `checks` iterations. /// /// Returns `true` if `p` is prime with an error probability of less than `0.25 ^ checks`. - pub fn is_prime(&mut self, p: &BigNumRef, checks: i32) -> Result { + pub fn is_prime(&mut self, p: &Ref, checks: i32) -> Result { unsafe { cvt_n(ffi::BN_is_prime_ex(p.as_ptr(), checks.into(), self.as_ptr(), ptr::null_mut())) .map(|r| r != 0) @@ -180,7 +180,7 @@ impl BnCtx { /// /// Returns `true` if `p` is prime with an error probability of less than `0.25 ^ checks`. pub fn is_prime_fasttest(&mut self, - p: &BigNumRef, + p: &Ref, checks: i32, do_trial_division: bool) -> Result { @@ -201,7 +201,7 @@ impl BnCtx { /// * `bits`: Length of the number in bits. /// * `prop`: The desired properties of the number. /// * `odd`: If `true`, the generated number will be odd. - pub fn rand(r: &mut BigNumRef, + pub fn rand(r: &mut Ref, bits: i32, prop: RNGProperty, odd: bool) @@ -212,7 +212,7 @@ impl BnCtx { } /// The cryptographically weak counterpart to `checked_new_random`. - pub fn pseudo_rand(r: &mut BigNumRef, + pub fn pseudo_rand(r: &mut Ref, bits: i32, prop: RNGProperty, odd: bool) @@ -224,22 +224,7 @@ impl BnCtx { } } -/// A borrowed, signed, arbitrary-precision integer. -pub struct BigNumRef(Opaque); - -impl BigNumRef { - pub unsafe fn from_ptr<'a>(handle: *mut ffi::BIGNUM) -> &'a BigNumRef { - &*(handle as *mut _) - } - - pub unsafe fn from_ptr_mut<'a>(handle: *mut ffi::BIGNUM) -> &'a mut BigNumRef { - &mut *(handle as *mut _) - } - - pub fn as_ptr(&self) -> *mut ffi::BIGNUM { - self as *const _ as *mut _ - } - +impl Ref { /// Adds a `u32` to `self`. pub fn add_word(&mut self, w: u32) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_add_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) } @@ -281,12 +266,12 @@ impl BigNumRef { /// Places a cryptographically-secure pseudo-random number nonnegative /// number less than `self` in `rnd`. - pub fn rand_in_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { + pub fn rand_in_range(&self, rnd: &mut Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_rand_range(self.as_ptr(), rnd.as_ptr())).map(|_| ()) } } /// The cryptographically weak counterpart to `rand_in_range`. - pub fn pseudo_rand_in_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { + pub fn pseudo_rand_in_range(&self, rnd: &mut Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_pseudo_rand_range(self.as_ptr(), rnd.as_ptr())).map(|_| ()) } } @@ -317,32 +302,32 @@ impl BigNumRef { } /// Places `self << 1` in `r`. - pub fn lshift1(&self, r: &mut BigNumRef) -> Result<(), ErrorStack> { + pub fn lshift1(&self, r: &mut Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_lshift1(r.as_ptr(), self.as_ptr())).map(|_| ()) } } /// Places `self >> 1` in `r`. - pub fn rshift1(&self, r: &mut BigNumRef) -> Result<(), ErrorStack> { + pub fn rshift1(&self, r: &mut Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_rshift1(r.as_ptr(), self.as_ptr())).map(|_| ()) } } /// Places `self + b` in `r`. - pub fn add(&self, r: &mut BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { + pub fn add(&self, r: &mut Ref, b: &Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_add(r.as_ptr(), self.as_ptr(), b.as_ptr())).map(|_| ()) } } /// Places `self - b` in `r`. - pub fn sub(&self, r: &mut BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { + pub fn sub(&self, r: &mut Ref, b: &Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_sub(r.as_ptr(), self.as_ptr(), b.as_ptr())).map(|_| ()) } } /// Places `self << n` in `r`. - pub fn lshift(&self, r: &mut BigNumRef, b: i32) -> Result<(), ErrorStack> { + pub fn lshift(&self, r: &mut Ref, b: i32) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_lshift(r.as_ptr(), self.as_ptr(), b.into())).map(|_| ()) } } /// Places `self >> n` in `r`. - pub fn rshift(&self, r: &mut BigNumRef, n: i32) -> Result<(), ErrorStack> { + pub fn rshift(&self, r: &mut Ref, n: i32) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_rshift(r.as_ptr(), self.as_ptr(), n.into())).map(|_| ()) } } @@ -365,7 +350,7 @@ impl BigNumRef { /// /// assert_eq!(s.ucmp(&o), Ordering::Equal); /// ``` - pub fn ucmp(&self, oth: &BigNumRef) -> Ordering { + pub fn ucmp(&self, oth: &Ref) -> Ordering { unsafe { ffi::BN_ucmp(self.as_ptr(), oth.as_ptr()).cmp(&0) } } @@ -446,13 +431,7 @@ impl BigNumRef { } } -/// An owned, signed, arbitrary-precision integer. -/// -/// `BigNum` provides wrappers around OpenSSL's checked arithmetic functions. -/// Additionally, it implements the standard operators (`std::ops`), which -/// perform unchecked arithmetic, unwrapping the returned `Result` of the -/// checked operations. -pub struct BigNum(*mut ffi::BIGNUM); +type_!(BigNum, ffi::BIGNUM, ffi::BN_clear_free); impl BigNum { /// Creates a new `BigNum` with the value 0. @@ -491,10 +470,6 @@ impl BigNum { } } - pub unsafe fn from_ptr(handle: *mut ffi::BIGNUM) -> BigNum { - BigNum(handle) - } - /// Creates a new `BigNum` from an unsigned, big-endian encoded number of arbitrary length. /// /// ``` @@ -519,11 +494,11 @@ impl BigNum { /// * `safe`: If true, returns a "safe" prime `p` so that `(p-1)/2` is also prime. /// * `add`/`rem`: If `add` is set to `Some(add)`, `p % add == rem` will hold, where `p` is the /// generated prime and `rem` is `1` if not specified (`None`). - pub fn generate_prime(r: &mut BigNumRef, + pub fn generate_prime(r: &mut Ref, bits: i32, safe: bool, - add: Option<&BigNumRef>, - rem: Option<&BigNumRef>) + add: Option<&Ref>, + rem: Option<&Ref>) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_generate_prime_ex(r.as_ptr(), @@ -537,35 +512,13 @@ impl BigNum { } } -impl Drop for BigNum { - fn drop(&mut self) { - unsafe { - ffi::BN_clear_free(self.as_ptr()); - } - } -} - -impl Deref for BigNum { - type Target = BigNumRef; - - fn deref(&self) -> &BigNumRef { - unsafe { BigNumRef::from_ptr(self.0) } - } -} - -impl DerefMut for BigNum { - fn deref_mut(&mut self) -> &mut BigNumRef { - unsafe { BigNumRef::from_ptr_mut(self.0) } - } -} - -impl AsRef for BigNum { - fn as_ref(&self) -> &BigNumRef { +impl AsRef> for BigNum { + fn as_ref(&self) -> &Ref { self.deref() } } -impl fmt::Debug for BigNumRef { +impl fmt::Debug for Ref { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.to_dec_str() { Ok(s) => f.write_str(&s), @@ -583,7 +536,7 @@ impl fmt::Debug for BigNum { } } -impl fmt::Display for BigNumRef { +impl fmt::Display for Ref { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.to_dec_str() { Ok(s) => f.write_str(&s), @@ -601,19 +554,19 @@ impl fmt::Display for BigNum { } } -impl PartialEq for BigNumRef { - fn eq(&self, oth: &BigNumRef) -> bool { +impl PartialEq> for Ref { + fn eq(&self, oth: &Ref) -> bool { self.cmp(oth) == Ordering::Equal } } -impl PartialEq for BigNumRef { +impl PartialEq for Ref { fn eq(&self, oth: &BigNum) -> bool { self.eq(oth.deref()) } } -impl Eq for BigNumRef {} +impl Eq for Ref {} impl PartialEq for BigNum { fn eq(&self, oth: &BigNum) -> bool { @@ -621,28 +574,28 @@ impl PartialEq for BigNum { } } -impl PartialEq for BigNum { - fn eq(&self, oth: &BigNumRef) -> bool { +impl PartialEq> for BigNum { + fn eq(&self, oth: &Ref) -> bool { self.deref().eq(oth) } } impl Eq for BigNum {} -impl PartialOrd for BigNumRef { - fn partial_cmp(&self, oth: &BigNumRef) -> Option { +impl PartialOrd> for Ref { + fn partial_cmp(&self, oth: &Ref) -> Option { Some(self.cmp(oth)) } } -impl PartialOrd for BigNumRef { +impl PartialOrd for Ref { fn partial_cmp(&self, oth: &BigNum) -> Option { Some(self.cmp(oth.deref())) } } -impl Ord for BigNumRef { - fn cmp(&self, oth: &BigNumRef) -> Ordering { +impl Ord for Ref { + fn cmp(&self, oth: &Ref) -> Ordering { unsafe { ffi::BN_cmp(self.as_ptr(), oth.as_ptr()).cmp(&0) } } } @@ -653,8 +606,8 @@ impl PartialOrd for BigNum { } } -impl PartialOrd for BigNum { - fn partial_cmp(&self, oth: &BigNumRef) -> Option { +impl PartialOrd> for BigNum { + fn partial_cmp(&self, oth: &Ref) -> Option { self.deref().partial_cmp(oth) } } @@ -667,7 +620,7 @@ impl Ord for BigNum { macro_rules! delegate { ($t:ident, $m:ident) => { - impl<'a, 'b> $t<&'b BigNum> for &'a BigNumRef { + impl<'a, 'b> $t<&'b BigNum> for &'a Ref { type Output = BigNum; fn $m(self, oth: &BigNum) -> BigNum { @@ -675,10 +628,10 @@ macro_rules! delegate { } } - impl<'a, 'b> $t<&'b BigNumRef> for &'a BigNum { + impl<'a, 'b> $t<&'b Ref> for &'a BigNum { type Output = BigNum; - fn $m(self, oth: &BigNumRef) -> BigNum { + fn $m(self, oth: &Ref) -> BigNum { $t::$m(self.deref(), oth) } } @@ -693,10 +646,10 @@ macro_rules! delegate { } } -impl<'a, 'b> Add<&'b BigNumRef> for &'a BigNumRef { +impl<'a, 'b> Add<&'b Ref> for &'a Ref { type Output = BigNum; - fn add(self, oth: &BigNumRef) -> BigNum { + fn add(self, oth: &Ref) -> BigNum { let mut r = BigNum::new().unwrap(); self.add(&mut r, oth).unwrap(); r @@ -705,10 +658,10 @@ impl<'a, 'b> Add<&'b BigNumRef> for &'a BigNumRef { delegate!(Add, add); -impl<'a, 'b> Sub<&'b BigNumRef> for &'a BigNumRef { +impl<'a, 'b> Sub<&'b Ref> for &'a Ref { type Output = BigNum; - fn sub(self, oth: &BigNumRef) -> BigNum { + fn sub(self, oth: &Ref) -> BigNum { let mut r = BigNum::new().unwrap(); self.sub(&mut r, oth).unwrap(); r @@ -717,10 +670,10 @@ impl<'a, 'b> Sub<&'b BigNumRef> for &'a BigNumRef { delegate!(Sub, sub); -impl<'a, 'b> Mul<&'b BigNumRef> for &'a BigNumRef { +impl<'a, 'b> Mul<&'b Ref> for &'a Ref { type Output = BigNum; - fn mul(self, oth: &BigNumRef) -> BigNum { + fn mul(self, oth: &Ref) -> BigNum { let mut ctx = BnCtx::new().unwrap(); let mut r = BigNum::new().unwrap(); ctx.mul(&mut r, self, oth).unwrap(); @@ -730,10 +683,10 @@ impl<'a, 'b> Mul<&'b BigNumRef> for &'a BigNumRef { delegate!(Mul, mul); -impl<'a, 'b> Div<&'b BigNumRef> for &'a BigNumRef { +impl<'a, 'b> Div<&'b Ref> for &'a Ref { type Output = BigNum; - fn div(self, oth: &'b BigNumRef) -> BigNum { + fn div(self, oth: &'b Ref) -> BigNum { let mut ctx = BnCtx::new().unwrap(); let mut dv = BigNum::new().unwrap(); ctx.div(Some(&mut dv), None, self, oth).unwrap(); @@ -743,10 +696,10 @@ impl<'a, 'b> Div<&'b BigNumRef> for &'a BigNumRef { delegate!(Div, div); -impl<'a, 'b> Rem<&'b BigNumRef> for &'a BigNumRef { +impl<'a, 'b> Rem<&'b Ref> for &'a Ref { type Output = BigNum; - fn rem(self, oth: &'b BigNumRef) -> BigNum { + fn rem(self, oth: &'b Ref) -> BigNum { let mut ctx = BnCtx::new().unwrap(); let mut rem = BigNum::new().unwrap(); ctx.div(None, Some(&mut rem), self, oth).unwrap(); @@ -756,7 +709,7 @@ impl<'a, 'b> Rem<&'b BigNumRef> for &'a BigNumRef { delegate!(Rem, rem); -impl<'a> Shl for &'a BigNumRef { +impl<'a> Shl for &'a Ref { type Output = BigNum; fn shl(self, n: i32) -> BigNum { @@ -774,7 +727,7 @@ impl<'a> Shl for &'a BigNum { } } -impl<'a> Shr for &'a BigNumRef { +impl<'a> Shr for &'a Ref { type Output = BigNum; fn shr(self, n: i32) -> BigNum { @@ -792,7 +745,7 @@ impl<'a> Shr for &'a BigNum { } } -impl<'a> Neg for &'a BigNumRef { +impl<'a> Neg for &'a Ref { type Output = BigNum; fn neg(self) -> BigNum { diff --git a/openssl/src/dsa.rs b/openssl/src/dsa.rs index e92b8ca3..c98d9c35 100644 --- a/openssl/src/dsa.rs +++ b/openssl/src/dsa.rs @@ -5,11 +5,12 @@ use std::fmt; use std::ops::Deref; use std::ptr; -use {cvt, cvt_p}; -use bn::BigNumRef; use bio::{MemBio, MemBioSlice}; -use util::{CallbackState, invoke_passwd_cb}; +use bn::BigNum; +use {cvt, cvt_p}; use opaque::Opaque; +use types::Ref; +use util::{CallbackState, invoke_passwd_cb}; pub struct DsaRef(Opaque); @@ -53,35 +54,35 @@ impl DsaRef { } } - pub fn p(&self) -> Option<&BigNumRef> { + pub fn p(&self) -> Option<&Ref> { unsafe { let p = compat::pqg(self.as_ptr())[0]; if p.is_null() { None } else { - Some(BigNumRef::from_ptr(p as *mut _)) + Some(Ref::::from_ptr(p as *mut _)) } } } - pub fn q(&self) -> Option<&BigNumRef> { + pub fn q(&self) -> Option<&Ref> { unsafe { let q = compat::pqg(self.as_ptr())[1]; if q.is_null() { None } else { - Some(BigNumRef::from_ptr(q as *mut _)) + Some(Ref::::from_ptr(q as *mut _)) } } } - pub fn g(&self) -> Option<&BigNumRef> { + pub fn g(&self) -> Option<&Ref> { unsafe { let g = compat::pqg(self.as_ptr())[2]; if g.is_null() { None } else { - Some(BigNumRef::from_ptr(g as *mut _)) + Some(Ref::::from_ptr(g as *mut _)) } } } diff --git a/openssl/src/rsa.rs b/openssl/src/rsa.rs index c6c96223..a12dc4d1 100644 --- a/openssl/src/rsa.rs +++ b/openssl/src/rsa.rs @@ -6,10 +6,11 @@ use std::ops::Deref; use libc::{c_int, c_void, c_char}; use {cvt, cvt_p, cvt_n}; -use bn::{BigNum, BigNumRef}; +use bn::BigNum; use bio::{MemBio, MemBioSlice}; use error::ErrorStack; use util::{CallbackState, invoke_passwd_cb}; +use types::{OpenSslType, Ref}; use opaque::Opaque; /// Type of encryption padding to use. @@ -162,57 +163,57 @@ impl RsaRef { } } - pub fn n(&self) -> Option<&BigNumRef> { + pub fn n(&self) -> Option<&Ref> { unsafe { let n = compat::key(self.as_ptr())[0]; if n.is_null() { None } else { - Some(BigNumRef::from_ptr(n as *mut _)) + Some(Ref::::from_ptr(n as *mut _)) } } } - pub fn d(&self) -> Option<&BigNumRef> { + pub fn d(&self) -> Option<&Ref> { unsafe { let d = compat::key(self.as_ptr())[2]; if d.is_null() { None } else { - Some(BigNumRef::from_ptr(d as *mut _)) + Some(Ref::::from_ptr(d as *mut _)) } } } - pub fn e(&self) -> Option<&BigNumRef> { + pub fn e(&self) -> Option<&Ref> { unsafe { let e = compat::key(self.as_ptr())[1]; if e.is_null() { None } else { - Some(BigNumRef::from_ptr(e as *mut _)) + Some(Ref::::from_ptr(e as *mut _)) } } } - pub fn p(&self) -> Option<&BigNumRef> { + pub fn p(&self) -> Option<&Ref> { unsafe { let p = compat::factors(self.as_ptr())[0]; if p.is_null() { None } else { - Some(BigNumRef::from_ptr(p as *mut _)) + Some(Ref::::from_ptr(p as *mut _)) } } } - pub fn q(&self) -> Option<&BigNumRef> { + pub fn q(&self) -> Option<&Ref> { unsafe { let q = compat::factors(self.as_ptr())[1]; if q.is_null() { None } else { - Some(BigNumRef::from_ptr(q as *mut _)) + Some(Ref::::from_ptr(q as *mut _)) } } } From 849fca4a7b285368ea3fc6f484350d6fa59c29e8 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 31 Oct 2016 19:49:37 -0700 Subject: [PATCH 136/186] Convert Asn1Time --- openssl/src/asn1.rs | 44 +++-------------------------------------- openssl/src/x509/mod.rs | 10 +++++----- 2 files changed, 8 insertions(+), 46 deletions(-) diff --git a/openssl/src/asn1.rs b/openssl/src/asn1.rs index 9a83a5da..a089b41b 100644 --- a/openssl/src/asn1.rs +++ b/openssl/src/asn1.rs @@ -1,30 +1,15 @@ use libc::c_long; use std::{ptr, fmt}; -use std::ops::Deref; - use ffi; -use opaque::Opaque; use {cvt, cvt_p}; use bio::MemBio; use error::ErrorStack; +use types::{OpenSslType, Ref}; -/// A borrowed Asn1Time -pub struct Asn1TimeRef(Opaque); +type_!(Asn1Time, ffi::ASN1_TIME, ffi::ASN1_TIME_free); -impl Asn1TimeRef { - /// Creates a new `Asn1TimeRef` wrapping the provided handle. - pub unsafe fn from_ptr<'a>(handle: *mut ffi::ASN1_TIME) -> &'a Asn1TimeRef { - &*(handle as *mut _) - } - - /// Returns the raw handle - pub fn as_ptr(&self) -> *mut ffi::ASN1_TIME { - self as *const _ as *mut _ - } -} - -impl fmt::Display for Asn1TimeRef { +impl fmt::Display for Ref { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mem_bio = try!(MemBio::new()); let as_str = unsafe { @@ -35,16 +20,7 @@ impl fmt::Display for Asn1TimeRef { } } - -/// Corresponds to the ASN.1 structure Time defined in RFC5280 -pub struct Asn1Time(*mut ffi::ASN1_TIME); - impl Asn1Time { - /// Wraps existing ASN1_TIME and takes ownership - pub unsafe fn from_ptr(handle: *mut ffi::ASN1_TIME) -> Asn1Time { - Asn1Time(handle) - } - fn from_period(period: c_long) -> Result { ffi::init(); @@ -59,17 +35,3 @@ impl Asn1Time { Asn1Time::from_period(days as c_long * 60 * 60 * 24) } } - -impl Deref for Asn1Time { - type Target = Asn1TimeRef; - - fn deref(&self) -> &Asn1TimeRef { - unsafe { Asn1TimeRef::from_ptr(self.0) } - } -} - -impl Drop for Asn1Time { - fn drop(&mut self) { - unsafe { ffi::ASN1_TIME_free(self.as_ptr()) }; - } -} diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index b49a9848..8a4941ea 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -14,7 +14,6 @@ use std::str; use {cvt, cvt_p}; use asn1::Asn1Time; -use asn1::Asn1TimeRef; use bio::{MemBio, MemBioSlice}; use crypto::CryptoString; use hash::MessageDigest; @@ -24,6 +23,7 @@ use error::ErrorStack; use ffi; use nid::Nid; use opaque::Opaque; +use types::Ref; #[cfg(ossl10x)] use ffi::{X509_set_notBefore, X509_set_notAfter, ASN1_STRING_data}; @@ -401,20 +401,20 @@ impl X509Ref { } /// Returns certificate Not After validity period. - pub fn not_after<'a>(&'a self) -> &'a Asn1TimeRef { + pub fn not_after<'a>(&'a self) -> &'a Ref { unsafe { let date = compat::X509_get_notAfter(self.as_ptr()); assert!(!date.is_null()); - Asn1TimeRef::from_ptr(date) + Ref::from_ptr(date) } } /// Returns certificate Not Before validity period. - pub fn not_before<'a>(&'a self) -> &'a Asn1TimeRef { + pub fn not_before<'a>(&'a self) -> &'a Ref { unsafe { let date = compat::X509_get_notBefore(self.as_ptr()); assert!(!date.is_null()); - Asn1TimeRef::from_ptr(date) + Ref::from_ptr(date) } } From 28f375974a21342f3ae4c39f0a4df17570d89e69 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 31 Oct 2016 19:56:03 -0700 Subject: [PATCH 137/186] Convert Dh --- openssl/src/dh.rs | 31 ++----------------------------- openssl/src/ssl/mod.rs | 5 +++-- 2 files changed, 5 insertions(+), 31 deletions(-) diff --git a/openssl/src/dh.rs b/openssl/src/dh.rs index 5c5ea05e..4ae145d6 100644 --- a/openssl/src/dh.rs +++ b/openssl/src/dh.rs @@ -3,25 +3,12 @@ use error::ErrorStack; use bio::MemBioSlice; use std::ptr; use std::mem; -use std::ops::Deref; use {cvt, cvt_p}; use bn::BigNum; -use opaque::Opaque; +use types::OpenSslType; -pub struct DhRef(Opaque); - -impl DhRef { - pub unsafe fn from_ptr<'a>(ptr: *mut ffi::DH) -> &'a DhRef { - &*(ptr as *mut _) - } - - pub fn as_ptr(&self) -> *mut ffi::DH { - self as *const _ as *mut _ - } -} - -pub struct Dh(*mut ffi::DH); +type_!(Dh, ffi::DH, ffi::DH_free); impl Dh { pub fn from_params(p: BigNum, g: BigNum, q: BigNum) -> Result { @@ -63,20 +50,6 @@ impl Dh { } } -impl Drop for Dh { - fn drop(&mut self) { - unsafe { ffi::DH_free(self.0) } - } -} - -impl Deref for Dh { - type Target = DhRef; - - fn deref(&self) -> &DhRef { - unsafe { DhRef::from_ptr(self.0) } - } -} - #[cfg(ossl110)] mod compat { pub use ffi::DH_set0_pqg; diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 5466f26e..695b2382 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -91,7 +91,7 @@ use std::marker::PhantomData; use ffi; use {init, cvt, cvt_p}; -use dh::DhRef; +use dh::Dh; use ec_key::EcKeyRef; use x509::{X509StoreContextRef, X509FileType, X509, X509Ref, X509VerifyError}; #[cfg(any(ossl102, ossl110))] @@ -99,6 +99,7 @@ use verify::X509VerifyParamRef; use pkey::PKeyRef; use error::ErrorStack; use opaque::Opaque; +use types::Ref; mod error; mod connector; @@ -513,7 +514,7 @@ impl SslContextBuilder { } } - pub fn set_tmp_dh(&mut self, dh: &DhRef) -> Result<(), ErrorStack> { + pub fn set_tmp_dh(&mut self, dh: &Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::SSL_CTX_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as c_int).map(|_| ()) } } From fe5fb75d45c69a2cfca87982e57ea14876d1b795 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 31 Oct 2016 20:04:55 -0700 Subject: [PATCH 138/186] Update Dsa --- openssl/src/dsa.rs | 44 ++++++-------------------------------------- 1 file changed, 6 insertions(+), 38 deletions(-) diff --git a/openssl/src/dsa.rs b/openssl/src/dsa.rs index c98d9c35..6efa7050 100644 --- a/openssl/src/dsa.rs +++ b/openssl/src/dsa.rs @@ -2,27 +2,17 @@ use error::ErrorStack; use ffi; use libc::{c_int, c_char, c_void}; use std::fmt; -use std::ops::Deref; use std::ptr; use bio::{MemBio, MemBioSlice}; use bn::BigNum; use {cvt, cvt_p}; -use opaque::Opaque; use types::Ref; use util::{CallbackState, invoke_passwd_cb}; -pub struct DsaRef(Opaque); - -impl DsaRef { - pub unsafe fn from_ptr<'a>(ptr: *mut ffi::DSA) -> &'a DsaRef { - &*(ptr as *mut _) - } - - pub fn as_ptr(&self) -> *mut ffi::DSA { - self as *const _ as *mut _ - } +type_!(Dsa, ffi::DSA, ffi::DSA_free); +impl Ref { /// Writes an DSA private key as unencrypted PEM formatted data pub fn private_key_to_pem(&self) -> Result, ErrorStack> { assert!(self.has_private_key()); @@ -96,21 +86,7 @@ impl DsaRef { } } -pub struct Dsa(*mut ffi::DSA); - -impl Drop for Dsa { - fn drop(&mut self) { - unsafe { - ffi::DSA_free(self.0); - } - } -} - impl Dsa { - pub unsafe fn from_ptr(dsa: *mut ffi::DSA) -> Dsa { - Dsa(dsa) - } - /// Generate a DSA key pair. pub fn generate(bits: u32) -> Result { unsafe { @@ -122,7 +98,7 @@ impl Dsa { ptr::null_mut(), ptr::null_mut(), ptr::null_mut()))); - try!(cvt(ffi::DSA_generate_key(dsa .0))); + try!(cvt(ffi::DSA_generate_key(dsa.0))); Ok(dsa) } } @@ -178,11 +154,9 @@ impl Dsa { } } -impl Deref for Dsa { - type Target = DsaRef; - - fn deref(&self) -> &DsaRef { - unsafe { DsaRef::from_ptr(self.0) } +impl fmt::Debug for Dsa { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "DSA") } } @@ -217,12 +191,6 @@ mod compat { } } -impl fmt::Debug for Dsa { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "DSA") - } -} - #[cfg(test)] mod test { use libc::c_char; From d6579ab058a22b8e7e2d82cd0d707fb3e670d5ec Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 31 Oct 2016 20:06:06 -0700 Subject: [PATCH 139/186] Update EcKey --- openssl/src/ec_key.rs | 36 +----------------------------------- openssl/src/ssl/mod.rs | 4 ++-- 2 files changed, 3 insertions(+), 37 deletions(-) diff --git a/openssl/src/ec_key.rs b/openssl/src/ec_key.rs index 81b790aa..95175eaa 100644 --- a/openssl/src/ec_key.rs +++ b/openssl/src/ec_key.rs @@ -1,49 +1,15 @@ use ffi; -use std::ops::Deref; use cvt_p; use error::ErrorStack; use nid::Nid; -use opaque::Opaque; -pub struct EcKeyRef(Opaque); - -impl EcKeyRef { - pub unsafe fn from_ptr<'a>(ptr: *mut ffi::EC_KEY) -> &'a EcKeyRef { - &*(ptr as *mut _) - } - - pub fn as_ptr(&self) -> *mut ffi::EC_KEY { - self as *const _ as *mut _ - } -} - -pub struct EcKey(*mut ffi::EC_KEY); - -impl Drop for EcKey { - fn drop(&mut self) { - unsafe { - ffi::EC_KEY_free(self.0); - } - } -} +type_!(EcKey, ffi::EC_KEY, ffi::EC_KEY_free); impl EcKey { pub fn new_by_curve_name(nid: Nid) -> Result { unsafe { cvt_p(ffi::EC_KEY_new_by_curve_name(nid.as_raw())).map(EcKey) } } - - pub unsafe fn from_ptr(ptr: *mut ffi::EC_KEY) -> EcKey { - EcKey(ptr) - } -} - -impl Deref for EcKey { - type Target = EcKeyRef; - - fn deref(&self) -> &EcKeyRef { - unsafe { EcKeyRef::from_ptr(self.0) } - } } #[cfg(test)] diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 695b2382..97b0fe6e 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -92,7 +92,7 @@ use ffi; use {init, cvt, cvt_p}; use dh::Dh; -use ec_key::EcKeyRef; +use ec_key::EcKey; use x509::{X509StoreContextRef, X509FileType, X509, X509Ref, X509VerifyError}; #[cfg(any(ossl102, ossl110))] use verify::X509VerifyParamRef; @@ -518,7 +518,7 @@ impl SslContextBuilder { unsafe { cvt(ffi::SSL_CTX_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as c_int).map(|_| ()) } } - pub fn set_tmp_ecdh(&mut self, key: &EcKeyRef) -> Result<(), ErrorStack> { + pub fn set_tmp_ecdh(&mut self, key: &Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::SSL_CTX_set_tmp_ecdh(self.as_ptr(), key.as_ptr()) as c_int).map(|_| ()) } } From f640613863f0b66bc004f9d9d89f73a31701d396 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 31 Oct 2016 20:12:55 -0700 Subject: [PATCH 140/186] Update PKey --- openssl/src/pkcs12.rs | 1 + openssl/src/pkey.rs | 41 ++++-------------------------------- openssl/src/ssl/connector.rs | 9 ++++---- openssl/src/ssl/mod.rs | 4 ++-- openssl/src/x509/mod.rs | 8 +++---- 5 files changed, 16 insertions(+), 47 deletions(-) diff --git a/openssl/src/pkcs12.rs b/openssl/src/pkcs12.rs index ab0934a8..1318f7f7 100644 --- a/openssl/src/pkcs12.rs +++ b/openssl/src/pkcs12.rs @@ -10,6 +10,7 @@ use {cvt, cvt_p}; use pkey::PKey; use error::ErrorStack; use x509::X509; +use types::OpenSslType; /// A PKCS #12 archive. pub struct Pkcs12(*mut ffi::PKCS12); diff --git a/openssl/src/pkey.rs b/openssl/src/pkey.rs index 8e4041b1..2561ab29 100644 --- a/openssl/src/pkey.rs +++ b/openssl/src/pkey.rs @@ -1,7 +1,6 @@ use libc::{c_void, c_char, c_int}; use std::ptr; use std::mem; -use std::ops::Deref; use ffi; use {cvt, cvt_p}; @@ -10,20 +9,11 @@ use dsa::Dsa; use rsa::{Rsa, RsaRef}; use error::ErrorStack; use util::{CallbackState, invoke_passwd_cb}; -use opaque::Opaque; +use types::{OpenSslType, Ref}; -/// A borrowed `PKey`. -pub struct PKeyRef(Opaque); - -impl PKeyRef { - pub unsafe fn from_ptr<'a>(ptr: *mut ffi::EVP_PKEY) -> &'a PKeyRef { - &*(ptr as *mut _) - } - - pub fn as_ptr(&self) -> *mut ffi::EVP_PKEY { - self as *const _ as *mut _ - } +type_!(PKey, ffi::EVP_PKEY, ffi::EVP_PKEY_free); +impl Ref { /// Get a reference to the interal RSA key for direct access to the key components pub fn rsa(&self) -> Result { unsafe { @@ -59,14 +49,11 @@ impl PKeyRef { Ok(mem_bio.get_buf().to_owned()) } - pub fn public_eq(&self, other: &PKeyRef) -> bool { + pub fn public_eq(&self, other: &Ref) -> bool { unsafe { ffi::EVP_PKEY_cmp(self.as_ptr(), other.as_ptr()) == 1 } } } -/// Represents a public key, optionally with a private key attached. -pub struct PKey(*mut ffi::EVP_PKEY); - unsafe impl Send for PKey {} unsafe impl Sync for PKey {} @@ -105,10 +92,6 @@ impl PKey { } } - pub unsafe fn from_ptr(handle: *mut ffi::EVP_PKEY) -> PKey { - PKey(handle) - } - /// Reads private key from PEM, takes ownership of handle pub fn private_key_from_pem(buf: &[u8]) -> Result { ffi::init(); @@ -166,22 +149,6 @@ impl PKey { } } -impl Drop for PKey { - fn drop(&mut self) { - unsafe { - ffi::EVP_PKEY_free(self.0); - } - } -} - -impl Deref for PKey { - type Target = PKeyRef; - - fn deref(&self) -> &PKeyRef { - unsafe { PKeyRef::from_ptr(self.0) } - } -} - #[cfg(test)] mod tests { #[test] diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index c7bfb209..752126e0 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -4,8 +4,9 @@ use dh::Dh; use error::ErrorStack; use ssl::{self, SslMethod, SslContextBuilder, SslContext, Ssl, SSL_VERIFY_PEER, SslStream, HandshakeError}; -use pkey::PKeyRef; +use pkey::PKey; use x509::X509Ref; +use types::Ref; // apps/dh2048.pem const DHPARAM_PEM: &'static str = r#" @@ -116,7 +117,7 @@ impl SslAcceptorBuilder { /// /// [docs]: https://wiki.mozilla.org/Security/Server_Side_TLS pub fn mozilla_intermediate(method: SslMethod, - private_key: &PKeyRef, + private_key: &Ref, certificate: &X509Ref, chain: I) -> Result @@ -151,7 +152,7 @@ impl SslAcceptorBuilder { /// /// [docs]: https://wiki.mozilla.org/Security/Server_Side_TLS pub fn mozilla_modern(method: SslMethod, - private_key: &PKeyRef, + private_key: &Ref, certificate: &X509Ref, chain: I) -> Result @@ -169,7 +170,7 @@ impl SslAcceptorBuilder { } fn finish_setup(mut ctx: SslContextBuilder, - private_key: &PKeyRef, + private_key: &Ref, certificate: &X509Ref, chain: I) -> Result diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 97b0fe6e..6a6916fc 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -96,7 +96,7 @@ use ec_key::EcKey; use x509::{X509StoreContextRef, X509FileType, X509, X509Ref, X509VerifyError}; #[cfg(any(ossl102, ossl110))] use verify::X509VerifyParamRef; -use pkey::PKeyRef; +use pkey::PKey; use error::ErrorStack; use opaque::Opaque; use types::Ref; @@ -615,7 +615,7 @@ impl SslContextBuilder { } /// Specifies the private key - pub fn set_private_key(&mut self, key: &PKeyRef) -> Result<(), ErrorStack> { + pub fn set_private_key(&mut self, key: &Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::SSL_CTX_use_PrivateKey(self.as_ptr(), key.as_ptr())).map(|_| ()) } } diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 8a4941ea..d3f7fbc0 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -17,13 +17,13 @@ use asn1::Asn1Time; use bio::{MemBio, MemBioSlice}; use crypto::CryptoString; use hash::MessageDigest; -use pkey::{PKey, PKeyRef}; +use pkey::PKey; use rand::rand_bytes; use error::ErrorStack; use ffi; use nid::Nid; use opaque::Opaque; -use types::Ref; +use types::{OpenSslType, Ref}; #[cfg(ossl10x)] use ffi::{X509_set_notBefore, X509_set_notAfter, ASN1_STRING_data}; @@ -269,7 +269,7 @@ impl X509Generator { } /// Sets the certificate public-key, then self-sign and return it - pub fn sign(&self, p_key: &PKeyRef) -> Result { + pub fn sign(&self, p_key: &Ref) -> Result { ffi::init(); unsafe { @@ -321,7 +321,7 @@ impl X509Generator { } /// Obtain a certificate signing request (CSR) - pub fn request(&self, p_key: &PKeyRef) -> Result { + pub fn request(&self, p_key: &Ref) -> Result { let cert = match self.sign(p_key) { Ok(c) => c, Err(x) => return Err(x), From e9d78181c334bb0398f65b30f6165ec1b54fe623 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 31 Oct 2016 20:15:12 -0700 Subject: [PATCH 141/186] Update Rsa --- openssl/src/pkey.rs | 4 ++-- openssl/src/rsa.rs | 36 ++---------------------------------- 2 files changed, 4 insertions(+), 36 deletions(-) diff --git a/openssl/src/pkey.rs b/openssl/src/pkey.rs index 2561ab29..6236b642 100644 --- a/openssl/src/pkey.rs +++ b/openssl/src/pkey.rs @@ -6,7 +6,7 @@ use ffi; use {cvt, cvt_p}; use bio::{MemBio, MemBioSlice}; use dsa::Dsa; -use rsa::{Rsa, RsaRef}; +use rsa::Rsa; use error::ErrorStack; use util::{CallbackState, invoke_passwd_cb}; use types::{OpenSslType, Ref}; @@ -139,7 +139,7 @@ impl PKey { } /// Assign an RSA key to this pkey. - pub fn set_rsa(&mut self, rsa: &RsaRef) -> Result<(), ErrorStack> { + pub fn set_rsa(&mut self, rsa: &Ref) -> Result<(), ErrorStack> { unsafe { // this needs to be a reference as the set1_RSA ups the reference count let rsa_ptr = rsa.as_ptr(); diff --git a/openssl/src/rsa.rs b/openssl/src/rsa.rs index a12dc4d1..57a07bd1 100644 --- a/openssl/src/rsa.rs +++ b/openssl/src/rsa.rs @@ -2,7 +2,6 @@ use ffi; use std::fmt; use std::ptr; use std::mem; -use std::ops::Deref; use libc::{c_int, c_void, c_char}; use {cvt, cvt_p, cvt_n}; @@ -11,7 +10,6 @@ use bio::{MemBio, MemBioSlice}; use error::ErrorStack; use util::{CallbackState, invoke_passwd_cb}; use types::{OpenSslType, Ref}; -use opaque::Opaque; /// Type of encryption padding to use. #[derive(Copy, Clone)] @@ -21,17 +19,9 @@ pub const NO_PADDING: Padding = Padding(ffi::RSA_NO_PADDING); pub const PKCS1_PADDING: Padding = Padding(ffi::RSA_PKCS1_PADDING); pub const PKCS1_OAEP_PADDING: Padding = Padding(ffi::RSA_PKCS1_OAEP_PADDING); -pub struct RsaRef(Opaque); - -impl RsaRef { - pub unsafe fn from_ptr<'a>(ptr: *mut ffi::RSA) -> &'a RsaRef { - &*(ptr as *mut _) - } - - pub fn as_ptr(&self) -> *mut ffi::RSA { - self as *const _ as *mut _ - } +type_!(Rsa, ffi::RSA, ffi::RSA_free); +impl Ref { /// Writes an RSA private key as unencrypted PEM formatted data pub fn private_key_to_pem(&self) -> Result, ErrorStack> { let mem_bio = try!(MemBio::new()); @@ -219,16 +209,6 @@ impl RsaRef { } } -pub struct Rsa(*mut ffi::RSA); - -impl Drop for Rsa { - fn drop(&mut self) { - unsafe { - ffi::RSA_free(self.0); - } - } -} - impl Rsa { /// only useful for associating the key material directly with the key, it's safer to use /// the supplied load and save methods for DER formatted keys. @@ -266,10 +246,6 @@ impl Rsa { } } - pub unsafe fn from_ptr(rsa: *mut ffi::RSA) -> Rsa { - Rsa(rsa) - } - /// Generates a public/private key pair with the specified size. /// /// The public exponent will be 65537. @@ -330,14 +306,6 @@ impl fmt::Debug for Rsa { } } -impl Deref for Rsa { - type Target = RsaRef; - - fn deref(&self) -> &RsaRef { - unsafe { RsaRef::from_ptr(self.0) } - } -} - #[cfg(ossl110)] mod compat { use std::ptr; From 16e398e005803e0796f7033497179d689b3df265 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 31 Oct 2016 20:19:59 -0700 Subject: [PATCH 142/186] Update verify --- openssl-sys/src/lib.rs | 2 ++ openssl/src/sign.rs | 9 +++++---- openssl/src/ssl/mod.rs | 8 ++++---- openssl/src/verify.rs | 14 +++----------- 4 files changed, 14 insertions(+), 19 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 755277e4..7f92f3a3 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1675,6 +1675,8 @@ extern { 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; + #[cfg(not(ossl101))] + pub fn X509_VERIFY_PARAM_free(param: *mut X509_VERIFY_PARAM); #[cfg(not(ossl101))] pub fn X509_VERIFY_PARAM_set_hostflags(param: *mut X509_VERIFY_PARAM, flags: c_uint); #[cfg(not(ossl101))] diff --git a/openssl/src/sign.rs b/openssl/src/sign.rs index eeee5cc7..aebfcca7 100644 --- a/openssl/src/sign.rs +++ b/openssl/src/sign.rs @@ -63,13 +63,14 @@ use {cvt, cvt_p}; use hash::MessageDigest; use pkey::PKey; use error::ErrorStack; +use types::Ref; #[cfg(ossl110)] use ffi::{EVP_MD_CTX_new, EVP_MD_CTX_free}; #[cfg(any(ossl101, ossl102))] use ffi::{EVP_MD_CTX_create as EVP_MD_CTX_new, EVP_MD_CTX_destroy as EVP_MD_CTX_free}; -pub struct Signer<'a>(*mut ffi::EVP_MD_CTX, PhantomData<&'a PKey>); +pub struct Signer<'a>(*mut ffi::EVP_MD_CTX, PhantomData<&'a Ref>); impl<'a> Drop for Signer<'a> { fn drop(&mut self) { @@ -80,7 +81,7 @@ impl<'a> Drop for Signer<'a> { } impl<'a> Signer<'a> { - pub fn new(type_: MessageDigest, pkey: &'a PKey) -> Result, ErrorStack> { + pub fn new(type_: MessageDigest, pkey: &'a Ref) -> Result, ErrorStack> { unsafe { ffi::init(); @@ -128,7 +129,7 @@ impl<'a> Write for Signer<'a> { } } -pub struct Verifier<'a>(*mut ffi::EVP_MD_CTX, PhantomData<&'a PKey>); +pub struct Verifier<'a>(*mut ffi::EVP_MD_CTX, PhantomData<&'a Ref>); impl<'a> Drop for Verifier<'a> { fn drop(&mut self) { @@ -139,7 +140,7 @@ impl<'a> Drop for Verifier<'a> { } impl<'a> Verifier<'a> { - pub fn new(type_: MessageDigest, pkey: &'a PKey) -> Result, ErrorStack> { + pub fn new(type_: MessageDigest, pkey: &'a Ref) -> Result, ErrorStack> { unsafe { ffi::init(); diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 6a6916fc..8101ad01 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -95,7 +95,7 @@ use dh::Dh; use ec_key::EcKey; use x509::{X509StoreContextRef, X509FileType, X509, X509Ref, X509VerifyError}; #[cfg(any(ossl102, ossl110))] -use verify::X509VerifyParamRef; +use verify::X509VerifyParam; use pkey::PKey; use error::ErrorStack; use opaque::Opaque; @@ -1109,13 +1109,13 @@ impl SslRef { /// /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or 1.1.0. #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - pub fn param_mut(&mut self) -> &mut X509VerifyParamRef { + pub fn param_mut(&mut self) -> &mut Ref { self._param_mut() } #[cfg(any(ossl102, ossl110))] - fn _param_mut(&mut self) -> &mut X509VerifyParamRef { - unsafe { X509VerifyParamRef::from_ptr_mut(ffi::SSL_get0_param(self.as_ptr())) } + fn _param_mut(&mut self) -> &mut Ref { + unsafe { Ref::from_ptr_mut(ffi::SSL_get0_param(self.as_ptr())) } } /// Returns the result of X509 certificate verification. diff --git a/openssl/src/verify.rs b/openssl/src/verify.rs index ceb3a6c8..c067e08e 100644 --- a/openssl/src/verify.rs +++ b/openssl/src/verify.rs @@ -3,7 +3,7 @@ use ffi; use cvt; use error::ErrorStack; -use opaque::Opaque; +use types::Ref; bitflags! { pub flags X509CheckFlags: c_uint { @@ -19,17 +19,9 @@ bitflags! { } } -pub struct X509VerifyParamRef(Opaque); - -impl X509VerifyParamRef { - pub unsafe fn from_ptr_mut<'a>(ptr: *mut ffi::X509_VERIFY_PARAM) -> &'a mut X509VerifyParamRef { - &mut *(ptr as *mut _) - } - - pub fn as_ptr(&self) -> *mut ffi::X509_VERIFY_PARAM { - self as *const _ as *mut _ - } +type_!(X509VerifyParam, ffi::X509_VERIFY_PARAM, ffi::X509_VERIFY_PARAM_free); +impl Ref { pub fn set_hostflags(&mut self, hostflags: X509CheckFlags) { unsafe { ffi::X509_VERIFY_PARAM_set_hostflags(self.as_ptr(), hostflags.bits); From ff12d37aefd597d41af9fa478570a4e3e588b67e Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 31 Oct 2016 20:32:55 -0700 Subject: [PATCH 143/186] Update ssl --- openssl/src/ssl/mod.rs | 145 ++++++++--------------------------------- 1 file changed, 27 insertions(+), 118 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 8101ad01..42c38980 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -80,7 +80,6 @@ use std::fmt; use std::io; use std::io::prelude::*; use std::mem; -use std::ops::{Deref, DerefMut}; use std::path::Path; use std::ptr; use std::str; @@ -98,8 +97,7 @@ use x509::{X509StoreContextRef, X509FileType, X509, X509Ref, X509VerifyError}; use verify::X509VerifyParam; use pkey::PKey; use error::ErrorStack; -use opaque::Opaque; -use types::Ref; +use types::{OpenSslType, Ref}; mod error; mod connector; @@ -295,13 +293,13 @@ extern "C" fn ssl_raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_ST } extern "C" fn raw_sni(ssl: *mut ffi::SSL, al: *mut c_int, _arg: *mut c_void) -> c_int - where F: Fn(&mut SslRef) -> Result<(), SniError> + Any + 'static + Sync + Send + where F: Fn(&mut Ref) -> Result<(), SniError> + Any + 'static + Sync + Send { unsafe { let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_verify_data_idx::()); let callback: &F = &*(callback as *mut F); - let ssl = SslRef::from_ptr_mut(ssl); + let ssl = Ref::from_ptr_mut(ssl); match callback(ssl) { Ok(()) => ffi::SSL_TLSEXT_ERR_OK, @@ -481,7 +479,7 @@ impl SslContextBuilder { /// Obtain the server name with `servername` then set the corresponding context /// with `set_ssl_context` pub fn set_servername_callback(&mut self, callback: F) - where F: Fn(&mut SslRef) -> Result<(), SniError> + Any + 'static + Sync + Send + where F: Fn(&mut Ref) -> Result<(), SniError> + Any + 'static + Sync + Send { unsafe { let callback = Box::new(callback); @@ -735,25 +733,7 @@ impl SslContextBuilder { } } -/// A borrowed SSL context object. -pub struct SslContextRef(Opaque); - -impl SslContextRef { - pub unsafe fn from_ptr<'a>(ctx: *mut ffi::SSL_CTX) -> &'a SslContextRef { - &*(ctx as *mut _) - } - - pub unsafe fn from_ptr_mut<'a>(ctx: *mut ffi::SSL_CTX) -> &'a mut SslContextRef { - &mut *(ctx as *mut _) - } - - pub fn as_ptr(&self) -> *mut ffi::SSL_CTX { - self as *const _ as *mut _ - } -} - -/// An owned SSL context object. -pub struct SslContext(*mut ffi::SSL_CTX); +type_!(SslContext, ffi::SSL_CTX, ffi::SSL_CTX_free); unsafe impl Send for SslContext {} unsafe impl Sync for SslContext {} @@ -774,38 +754,10 @@ impl fmt::Debug for SslContext { } } -impl Drop for SslContext { - fn drop(&mut self) { - unsafe { ffi::SSL_CTX_free(self.as_ptr()) } - } -} - -impl Deref for SslContext { - type Target = SslContextRef; - - fn deref(&self) -> &SslContextRef { - unsafe { SslContextRef::from_ptr(self.0) } - } -} - -impl DerefMut for SslContext { - fn deref_mut(&mut self) -> &mut SslContextRef { - unsafe { SslContextRef::from_ptr_mut(self.0) } - } -} - impl SslContext { pub fn builder(method: SslMethod) -> Result { SslContextBuilder::new(method) } - - pub unsafe fn from_ptr(ctx: *mut ffi::SSL_CTX) -> SslContext { - SslContext(ctx) - } - - pub fn as_ptr(&self) -> *mut ffi::SSL_CTX { - self.0 - } } @@ -817,17 +769,21 @@ pub struct CipherBits { pub algorithm: i32, } -pub struct SslCipherRef(Opaque); +pub struct SslCipher(*mut ffi::SSL_CIPHER); -impl SslCipherRef { - pub unsafe fn from_ptr<'a>(ptr: *const ffi::SSL_CIPHER) -> &'a SslCipherRef { - &*(ptr as *const _) +unsafe impl OpenSslType for SslCipher { + type CType = ffi::SSL_CIPHER; + + unsafe fn from_ptr(ptr: *mut ffi::SSL_CIPHER) -> SslCipher { + SslCipher(ptr) } - pub fn as_ptr(&self) -> *const ffi::SSL_CIPHER { - self as *const _ as *const _ + fn as_ptr(&self) -> *mut ffi::SSL_CIPHER { + self.0 } +} +impl Ref { /// Returns the name of cipher. pub fn name(&self) -> &'static str { let name = unsafe { @@ -871,15 +827,11 @@ impl SslCipherRef { } } -/// A reference to an `Ssl`. -pub struct SslRef(Opaque); +type_!(Ssl, ffi::SSL, ffi::SSL_free); -unsafe impl Send for SslRef {} -unsafe impl Sync for SslRef {} - -impl fmt::Debug for SslRef { +impl fmt::Debug for Ref { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - let mut builder = fmt.debug_struct("SslRef"); + let mut builder = fmt.debug_struct("Ssl"); builder.field("state", &self.state_string_long()); if let Some(err) = self.verify_result() { builder.field("verify_result", &err); @@ -888,19 +840,7 @@ impl fmt::Debug for SslRef { } } -impl SslRef { - pub unsafe fn from_ptr<'a>(ssl: *mut ffi::SSL) -> &'a SslRef { - &*(ssl as *mut _) - } - - pub unsafe fn from_ptr_mut<'a>(ssl: *mut ffi::SSL) -> &'a mut SslRef { - &mut *(ssl as *mut _) - } - - pub fn as_ptr(&self) -> *mut ffi::SSL { - self as *const _ as *mut _ - } - +impl Ref { fn get_raw_rbio(&self) -> *mut ffi::BIO { unsafe { ffi::SSL_get_rbio(self.as_ptr()) } } @@ -945,14 +885,14 @@ impl SslRef { } } - pub fn current_cipher(&self) -> Option<&SslCipherRef> { + pub fn current_cipher(&self) -> Option<&Ref> { unsafe { let ptr = ffi::SSL_get_current_cipher(self.as_ptr()); if ptr.is_null() { None } else { - Some(SslCipherRef::from_ptr(ptr)) + Some(Ref::from_ptr(ptr as *mut _)) } } } @@ -1093,15 +1033,15 @@ impl SslRef { } /// Changes the context corresponding to the current connection. - pub fn set_ssl_context(&mut self, ctx: &SslContextRef) -> Result<(), ErrorStack> { + pub fn set_ssl_context(&mut self, ctx: &Ref) -> Result<(), ErrorStack> { unsafe { cvt_p(ffi::SSL_set_SSL_CTX(self.as_ptr(), ctx.as_ptr())).map(|_| ()) } } /// Returns the context corresponding to the current connection - pub fn ssl_context(&self) -> &SslContextRef { + pub fn ssl_context(&self) -> &Ref { unsafe { let ssl_ctx = ffi::SSL_get_SSL_CTX(self.as_ptr()); - SslContextRef::from_ptr(ssl_ctx) + Ref::from_ptr(ssl_ctx) } } @@ -1124,39 +1064,12 @@ impl SslRef { } } -pub struct Ssl(*mut ffi::SSL); - unsafe impl Sync for Ssl {} unsafe impl Send for Ssl {} impl fmt::Debug for Ssl { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - let mut builder = fmt.debug_struct("Ssl"); - builder.field("state", &self.state_string_long()); - if let Some(err) = self.verify_result() { - builder.field("verify_result", &err); - } - builder.finish() - } -} - -impl Drop for Ssl { - fn drop(&mut self) { - unsafe { ffi::SSL_free(self.as_ptr()) } - } -} - -impl Deref for Ssl { - type Target = SslRef; - - fn deref(&self) -> &SslRef { - unsafe { SslRef::from_ptr(self.0) } - } -} - -impl DerefMut for Ssl { - fn deref_mut(&mut self) -> &mut SslRef { - unsafe { SslRef::from_ptr_mut(self.0) } + fmt::Debug::fmt(&**self, fmt) } } @@ -1168,10 +1081,6 @@ impl Ssl { } } - pub unsafe fn from_ptr(ssl: *mut ffi::SSL) -> Ssl { - Ssl(ssl) - } - /// Creates an SSL/TLS client operating over the provided stream. /// /// # Warning @@ -1256,7 +1165,7 @@ impl MidHandshakeSslStream { } /// Returns a shared reference to the `Ssl` of the stream. - pub fn ssl(&self) -> &SslRef { + pub fn ssl(&self) -> &Ref { self.stream.ssl() } @@ -1438,7 +1347,7 @@ impl SslStream { } /// Returns the OpenSSL `Ssl` object associated with this stream. - pub fn ssl(&self) -> &SslRef { + pub fn ssl(&self) -> &Ref { &self.ssl } } From cd7fa9fca29296adebe37dfc20d3cebc96010534 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 31 Oct 2016 20:54:34 -0700 Subject: [PATCH 144/186] Update x509 --- openssl-sys/src/lib.rs | 4 +- openssl/src/ssl/connector.rs | 23 +++--- openssl/src/ssl/mod.rs | 16 ++--- openssl/src/ssl/tests/mod.rs | 23 +----- openssl/src/x509/mod.rs | 135 ++++++++++------------------------- 5 files changed, 62 insertions(+), 139 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 7f92f3a3..ae423099 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1658,12 +1658,14 @@ extern { pub fn X509_EXTENSION_free(ext: *mut X509_EXTENSION); + 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; pub fn ASN1_STRING_length(x: *const ASN1_STRING) -> c_int; - pub fn X509_STORE_CTX_get_current_cert(ct: *mut X509_STORE_CTX) -> *mut X509; + pub fn X509_STORE_CTX_free(ctx: *mut X509_STORE_CTX); + pub fn X509_STORE_CTX_get_current_cert(ctx: *mut X509_STORE_CTX) -> *mut X509; pub fn X509_STORE_CTX_get_error(ctx: *mut X509_STORE_CTX) -> c_int; pub fn X509_STORE_CTX_get_ex_data(ctx: *mut X509_STORE_CTX, idx: c_int) -> *mut c_void; pub fn X509_STORE_CTX_get_error_depth(ctx: *mut X509_STORE_CTX) -> c_int; diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index 752126e0..a1bcfa77 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -5,7 +5,7 @@ use error::ErrorStack; use ssl::{self, SslMethod, SslContextBuilder, SslContext, Ssl, SSL_VERIFY_PEER, SslStream, HandshakeError}; use pkey::PKey; -use x509::X509Ref; +use x509::X509; use types::Ref; // apps/dh2048.pem @@ -118,11 +118,11 @@ impl SslAcceptorBuilder { /// [docs]: https://wiki.mozilla.org/Security/Server_Side_TLS pub fn mozilla_intermediate(method: SslMethod, private_key: &Ref, - certificate: &X509Ref, + certificate: &Ref, chain: I) -> Result where I: IntoIterator, - I::Item: AsRef + I::Item: AsRef> { let mut ctx = try!(ctx(method)); let dh = try!(Dh::from_pem(DHPARAM_PEM.as_bytes())); @@ -153,11 +153,11 @@ impl SslAcceptorBuilder { /// [docs]: https://wiki.mozilla.org/Security/Server_Side_TLS pub fn mozilla_modern(method: SslMethod, private_key: &Ref, - certificate: &X509Ref, + certificate: &Ref, chain: I) -> Result where I: IntoIterator, - I::Item: AsRef + I::Item: AsRef> { let mut ctx = try!(ctx(method)); try!(setup_curves(&mut ctx)); @@ -171,11 +171,11 @@ impl SslAcceptorBuilder { fn finish_setup(mut ctx: SslContextBuilder, private_key: &Ref, - certificate: &X509Ref, + certificate: &Ref, chain: I) -> Result where I: IntoIterator, - I::Item: AsRef + I::Item: AsRef> { try!(ctx.set_private_key(private_key)); try!(ctx.set_certificate(certificate)); @@ -255,11 +255,12 @@ mod verify { use std::net::IpAddr; use nid; - use x509::{X509StoreContextRef, X509Ref, GeneralNames, X509NameRef}; + use x509::{X509StoreContext, X509, GeneralNames, X509Name}; + use types::Ref; pub fn verify_callback(domain: &str, preverify_ok: bool, - x509_ctx: &X509StoreContextRef) + x509_ctx: &Ref) -> bool { if !preverify_ok || x509_ctx.error_depth() != 0 { return preverify_ok; @@ -271,7 +272,7 @@ mod verify { } } - fn verify_hostname(domain: &str, cert: &X509Ref) -> bool { + fn verify_hostname(domain: &str, cert: &Ref) -> bool { match cert.subject_alt_names() { Some(names) => verify_subject_alt_names(domain, &names), None => verify_subject_name(domain, &cert.subject_name()), @@ -303,7 +304,7 @@ mod verify { false } - fn verify_subject_name(domain: &str, subject_name: &X509NameRef) -> bool { + fn verify_subject_name(domain: &str, subject_name: &Ref) -> bool { if let Some(pattern) = subject_name.text_by_nid(nid::COMMONNAME) { // Unlike with SANs, IP addresses in the subject name don't have a // different encoding. We need to pass this down to matches_dns to diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 42c38980..68d411c7 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -92,7 +92,7 @@ use ffi; use {init, cvt, cvt_p}; use dh::Dh; use ec_key::EcKey; -use x509::{X509StoreContextRef, X509FileType, X509, X509Ref, X509VerifyError}; +use x509::{X509StoreContext, X509FileType, X509, X509VerifyError}; #[cfg(any(ossl102, ossl110))] use verify::X509VerifyParam; use pkey::PKey; @@ -262,7 +262,7 @@ fn get_new_ssl_idx() -> c_int { } extern "C" fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int - where F: Fn(bool, &X509StoreContextRef) -> bool + Any + 'static + Sync + Send + where F: Fn(bool, &Ref) -> bool + Any + 'static + Sync + Send { unsafe { let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx(); @@ -271,14 +271,14 @@ extern "C" fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_ let verify = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_verify_data_idx::()); let verify: &F = &*(verify as *mut F); - let ctx = X509StoreContextRef::from_ptr(x509_ctx); + let ctx = Ref::from_ptr(x509_ctx); verify(preverify_ok != 0, ctx) as c_int } } extern "C" fn ssl_raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int - where F: Fn(bool, &X509StoreContextRef) -> bool + Any + 'static + Sync + Send + where F: Fn(bool, &Ref) -> bool + Any + 'static + Sync + Send { unsafe { let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx(); @@ -286,7 +286,7 @@ extern "C" fn ssl_raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_ST let verify = ffi::SSL_get_ex_data(ssl as *const _, get_ssl_verify_data_idx::()); let verify: &F = &*(verify as *mut F); - let ctx = X509StoreContextRef::from_ptr(x509_ctx); + let ctx = Ref::from_ptr(x509_ctx); verify(preverify_ok != 0, ctx) as c_int } @@ -463,7 +463,7 @@ impl SslContextBuilder { /// Configures the certificate verification method for new connections and /// registers a verification callback. pub fn set_verify_callback(&mut self, mode: SslVerifyMode, verify: F) - where F: Fn(bool, &X509StoreContextRef) -> bool + Any + 'static + Sync + Send + where F: Fn(bool, &Ref) -> bool + Any + 'static + Sync + Send { unsafe { let verify = Box::new(verify); @@ -584,7 +584,7 @@ impl SslContextBuilder { } /// Specifies the certificate - pub fn set_certificate(&mut self, cert: &X509Ref) -> Result<(), ErrorStack> { + pub fn set_certificate(&mut self, cert: &Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::SSL_CTX_use_certificate(self.as_ptr(), cert.as_ptr())).map(|_| ()) } } @@ -874,7 +874,7 @@ impl Ref { /// to the certificate chain. It should return `true` if the certificate /// chain is valid and `false` otherwise. pub fn set_verify_callback(&mut self, mode: SslVerifyMode, verify: F) - where F: Fn(bool, &X509StoreContextRef) -> bool + Any + 'static + Sync + Send + where F: Fn(bool, &Ref) -> bool + Any + 'static + Sync + Send { unsafe { let verify = Box::new(verify); diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index a874fe3b..13b3a8a7 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -20,7 +20,7 @@ use ssl::SSL_VERIFY_PEER; use ssl::{SslMethod, HandshakeError}; use ssl::{SslContext, SslStream, Ssl, ShutdownResult, SslConnectorBuilder, SslAcceptorBuilder, Error}; -use x509::X509StoreContextRef; +use x509::X509StoreContext; use x509::X509FileType; use x509::X509; #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] @@ -171,8 +171,9 @@ macro_rules! run_test( use ssl::{SslContext, Ssl, SslStream}; use ssl::SSL_VERIFY_PEER; use hash::MessageDigest; - use x509::X509StoreContextRef; + use x509::X509StoreContext; use serialize::hex::FromHex; + use types::Ref; use super::Server; #[test] @@ -771,24 +772,6 @@ fn test_alpn_server_select_none() { assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_err()); } -#[cfg(test)] -mod dtlsv1 { - use serialize::hex::FromHex; - use std::net::TcpStream; - use std::thread; - - use hash::MessageDigest; - use ssl::SslMethod; - use ssl::{SslContext, SslStream}; - use ssl::SSL_VERIFY_PEER; - use x509::X509StoreContextRef; - - #[test] - fn test_new_ctx() { - SslContext::builder(SslMethod::dtls()).unwrap(); - } -} - #[test] #[cfg_attr(any(windows, target_arch = "arm"), ignore)] // FIXME(#467) fn test_read_dtlsv1() { diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index d3f7fbc0..bb2c7544 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -7,7 +7,6 @@ use std::ffi::{CStr, CString}; use std::fmt; use std::marker::PhantomData; use std::mem; -use std::ops::Deref; use std::ptr; use std::slice; use std::str; @@ -22,7 +21,6 @@ use rand::rand_bytes; use error::ErrorStack; use ffi; use nid::Nid; -use opaque::Opaque; use types::{OpenSslType, Ref}; #[cfg(ossl10x)] @@ -49,28 +47,20 @@ pub enum X509FileType { Default = ffi::X509_FILETYPE_DEFAULT, } -pub struct X509StoreContextRef(Opaque); - -impl X509StoreContextRef { - pub unsafe fn from_ptr<'a>(ctx: *mut ffi::X509_STORE_CTX) -> &'a X509StoreContextRef { - &*(ctx as *mut _) - } - - pub fn as_ptr(&self) -> *mut ffi::X509_STORE_CTX { - self as *const _ as *mut _ - } +type_!(X509StoreContext, ffi::X509_STORE_CTX, ffi::X509_STORE_CTX_free); +impl Ref { pub fn error(&self) -> Option { unsafe { X509VerifyError::from_raw(ffi::X509_STORE_CTX_get_error(self.as_ptr()) as c_long) } } - pub fn current_cert(&self) -> Option<&X509Ref> { + pub fn current_cert(&self) -> Option<&Ref> { unsafe { let ptr = ffi::X509_STORE_CTX_get_current_cert(self.as_ptr()); if ptr.is_null() { None } else { - Some(X509Ref::from_ptr(ptr)) + Some(Ref::from_ptr(ptr)) } } } @@ -346,23 +336,13 @@ impl X509Generator { } } -/// A borrowed public key certificate. -pub struct X509Ref(Opaque); +type_!(X509, ffi::X509, ffi::X509_free); -impl X509Ref { - /// Creates a new `X509Ref` wrapping the provided handle. - pub unsafe fn from_ptr<'a>(x509: *mut ffi::X509) -> &'a X509Ref { - &*(x509 as *mut _) - } - - pub fn as_ptr(&self) -> *mut ffi::X509 { - self as *const _ as *mut _ - } - - pub fn subject_name(&self) -> &X509NameRef { +impl Ref { + pub fn subject_name(&self) -> &Ref { unsafe { let name = ffi::X509_get_subject_name(self.as_ptr()); - X509NameRef::from_ptr(name) + Ref::from_ptr(name) } } @@ -437,7 +417,7 @@ impl X509Ref { } } -impl ToOwned for X509Ref { +impl ToOwned for Ref { type Owned = X509; fn to_owned(&self) -> X509 { @@ -448,15 +428,7 @@ impl ToOwned for X509Ref { } } -/// An owned public key certificate. -pub struct X509(*mut ffi::X509); - impl X509 { - /// Returns a new `X509`, taking ownership of the handle. - pub unsafe fn from_ptr(x509: *mut ffi::X509) -> X509 { - X509(x509) - } - /// Reads a certificate from DER. pub fn from_der(buf: &[u8]) -> Result { unsafe { @@ -480,49 +452,27 @@ impl X509 { } } -impl Deref for X509 { - type Target = X509Ref; - - fn deref(&self) -> &X509Ref { - unsafe { X509Ref::from_ptr(self.0) } - } -} - impl Clone for X509 { fn clone(&self) -> X509 { self.to_owned() } } -impl Drop for X509 { - fn drop(&mut self) { - unsafe { ffi::X509_free(self.as_ptr()) }; - } -} - -impl AsRef for X509 { - fn as_ref(&self) -> &X509Ref { +impl AsRef> for X509 { + fn as_ref(&self) -> &Ref { &*self } } -impl Borrow for X509 { - fn borrow(&self) -> &X509Ref { +impl Borrow> for X509 { + fn borrow(&self) -> &Ref { &*self } } -pub struct X509NameRef(Opaque); - -impl X509NameRef { - pub unsafe fn from_ptr<'a>(ptr: *mut ffi::X509_NAME) -> &'a X509NameRef { - &*(ptr as *mut _) - } - - pub fn as_ptr(&self) -> *mut ffi::X509_NAME { - self as *const _ as *mut _ - } +type_!(X509Name, ffi::X509_NAME, ffi::X509_NAME_free); +impl Ref { pub fn text_by_nid(&self, nid: Nid) -> Option { unsafe { let loc = ffi::X509_NAME_get_index_by_NID(self.as_ptr(), nid.as_raw(), -1); @@ -554,18 +504,29 @@ impl X509NameRef { } } -/// A certificate signing request -pub struct X509Req(*mut ffi::X509_REQ); +type_!(X509Req, ffi::X509_REQ, ffi::X509_REQ_free); + +impl Ref { + /// 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()) + } +} impl X509Req { - pub unsafe fn from_ptr(handle: *mut ffi::X509_REQ) -> X509Req { - X509Req(handle) - } - - pub fn as_ptr(&self) -> *mut ffi::X509_REQ { - self.0 - } - /// Reads CSR from PEM pub fn from_pem(buf: &[u8]) -> Result { let mem_bio = try!(MemBioSlice::new(buf)); @@ -577,30 +538,6 @@ impl X509Req { Ok(X509Req::from_ptr(handle)) } } - - /// 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.0) } != 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.0); - } - Ok(mem_bio.get_buf().to_owned()) - } -} - -impl Drop for X509Req { - fn drop(&mut self) { - unsafe { ffi::X509_REQ_free(self.0) }; - } } /// A collection of X.509 extensions. From 96a77cf5a8388cea89e61e5d610f78bae1842d3a Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 31 Oct 2016 20:56:51 -0700 Subject: [PATCH 145/186] Remove Opaque --- openssl/src/lib.rs | 1 - openssl/src/opaque.rs | 6 ------ openssl/src/types.rs | 5 ++--- 3 files changed, 2 insertions(+), 10 deletions(-) delete mode 100644 openssl/src/opaque.rs diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index 8fa53f3b..d053606f 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -59,7 +59,6 @@ macro_rules! type_ { } mod bio; -mod opaque; mod util; pub mod asn1; pub mod bn; diff --git a/openssl/src/opaque.rs b/openssl/src/opaque.rs deleted file mode 100644 index 9545471c..00000000 --- a/openssl/src/opaque.rs +++ /dev/null @@ -1,6 +0,0 @@ -use std::cell::UnsafeCell; - -/// This is intended to be used as the inner type for types designed to be pointed to by references -/// converted from raw C pointers. It has an `UnsafeCell` internally to inform the compiler about -/// aliasability and doesn't implement `Copy`, so it can't be dereferenced. -pub struct Opaque(UnsafeCell<()>); diff --git a/openssl/src/types.rs b/openssl/src/types.rs index 16829ea4..7302bca9 100644 --- a/openssl/src/types.rs +++ b/openssl/src/types.rs @@ -1,7 +1,6 @@ +use std::cell::UnsafeCell; use std::marker::PhantomData; -use opaque::Opaque; - pub unsafe trait OpenSslType { type CType; @@ -10,7 +9,7 @@ pub unsafe trait OpenSslType { fn as_ptr(&self) -> *mut Self::CType; } -pub struct Ref(Opaque, PhantomData); +pub struct Ref(UnsafeCell<()>, PhantomData); impl Ref { pub unsafe fn from_ptr<'a>(ptr: *mut T::CType) -> &'a Ref { From ab30ad0ce76ee6fd8cc14ecff2186171c7f610e3 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 31 Oct 2016 20:59:38 -0700 Subject: [PATCH 146/186] Documentation --- openssl/src/types.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/openssl/src/types.rs b/openssl/src/types.rs index 7302bca9..40831ee8 100644 --- a/openssl/src/types.rs +++ b/openssl/src/types.rs @@ -1,25 +1,38 @@ +//! Items used by other types. + use std::cell::UnsafeCell; use std::marker::PhantomData; +/// A type implemented by wrappers over OpenSSL types. +/// +/// This should not be implemented by anything outside of this crate; new methods may be added at +/// any time. pub unsafe trait OpenSslType { + /// The raw C type. type CType; + /// Constructs an instance of this type from its raw type. unsafe fn from_ptr(ptr: *mut Self::CType) -> Self; + /// Returns a pointer to its raw type. fn as_ptr(&self) -> *mut Self::CType; } +/// A reference to an OpenSSL type. pub struct Ref(UnsafeCell<()>, PhantomData); impl Ref { + /// Constructs a shared reference to this type from its raw type. pub unsafe fn from_ptr<'a>(ptr: *mut T::CType) -> &'a Ref { &*(ptr as *mut _) } + /// Constructs a mutable reference to this type from its raw type. pub unsafe fn from_ptr_mut<'a>(ptr: *mut T::CType) -> &'a mut Ref { &mut *(ptr as *mut _) } + /// Returns a pointer to its raw type. pub fn as_ptr(&self) -> *mut T::CType { self as *const _ as *mut _ } From dc4098bdd83e23703b2490741ee7461caea83375 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 31 Oct 2016 22:43:05 -0700 Subject: [PATCH 147/186] Clean up x509 name entries --- openssl-sys/src/lib.rs | 5 ++- openssl/src/asn1.rs | 28 +++++++++++++++++ openssl/src/ssl/connector.rs | 8 ++++- openssl/src/x509/mod.rs | 59 ++++++++++++++++++++++-------------- openssl/src/x509/tests.rs | 44 +++++++++------------------ 5 files changed, 90 insertions(+), 54 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index ae423099..f556b19f 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1660,8 +1660,11 @@ extern { 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; + pub fn X509_NAME_get_index_by_NID(n: *mut X509_NAME, nid: c_int, last_pos: c_int) -> c_int; + pub fn X509_NAME_ENTRY_free(x: *mut X509_NAME_ENTRY); + + pub fn ASN1_STRING_free(x: *mut ASN1_STRING); pub fn ASN1_STRING_length(x: *const ASN1_STRING) -> c_int; pub fn X509_STORE_CTX_free(ctx: *mut X509_STORE_CTX); diff --git a/openssl/src/asn1.rs b/openssl/src/asn1.rs index a089b41b..d0704693 100644 --- a/openssl/src/asn1.rs +++ b/openssl/src/asn1.rs @@ -1,9 +1,11 @@ use libc::c_long; use std::{ptr, fmt}; +use std::slice; use ffi; use {cvt, cvt_p}; use bio::MemBio; +use crypto::CryptoString; use error::ErrorStack; use types::{OpenSslType, Ref}; @@ -35,3 +37,29 @@ impl Asn1Time { Asn1Time::from_period(days as c_long * 60 * 60 * 24) } } + +type_!(Asn1String, ffi::ASN1_STRING, ffi::ASN1_STRING_free); + +impl Ref { + pub fn as_utf8(&self) -> Result { + unsafe { + let mut ptr = ptr::null_mut(); + let len = ffi::ASN1_STRING_to_UTF8(&mut ptr, self.as_ptr()); + if len < 0 { + return Err(ErrorStack::get()); + } + + Ok(CryptoString::from_raw_parts(ptr, len as usize)) + } + } + + pub fn as_slice(&self) -> &[u8] { + unsafe { slice::from_raw_parts(ffi::ASN1_STRING_data(self.as_ptr()), self.len()) } + } + + pub fn len(&self) -> usize { + unsafe { + ffi::ASN1_STRING_length(self.as_ptr()) as usize + } + } +} diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index a1bcfa77..5520e578 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -253,6 +253,7 @@ fn setup_verify(ssl: &mut Ssl, domain: &str) -> Result<(), ErrorStack> { #[cfg(not(any(ossl102, ossl110)))] mod verify { use std::net::IpAddr; + use std::str; use nid; use x509::{X509StoreContext, X509, GeneralNames, X509Name}; @@ -305,7 +306,12 @@ mod verify { } fn verify_subject_name(domain: &str, subject_name: &Ref) -> bool { - if let Some(pattern) = subject_name.text_by_nid(nid::COMMONNAME) { + if let Some(pattern) = subject_name.entries_by_nid(nid::COMMONNAME).next() { + let pattern = match str::from_utf8(pattern.data().as_slice()) { + Ok(pattern) => pattern, + Err(_) => return false, + }; + // Unlike with SANs, IP addresses in the subject name don't have a // different encoding. We need to pass this down to matches_dns to // disallow wildcard matches with bogus patterns like *.0.0.1 diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index bb2c7544..28f2542f 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -12,9 +12,8 @@ use std::slice; use std::str; use {cvt, cvt_p}; -use asn1::Asn1Time; +use asn1::{Asn1String, Asn1Time}; use bio::{MemBio, MemBioSlice}; -use crypto::CryptoString; use hash::MessageDigest; use pkey::PKey; use rand::rand_bytes; @@ -473,33 +472,49 @@ impl Borrow> for X509 { type_!(X509Name, ffi::X509_NAME, ffi::X509_NAME_free); impl Ref { - pub fn text_by_nid(&self, nid: Nid) -> Option { + pub fn entries_by_nid<'a>(&'a self, nid: Nid) -> X509NameEntries<'a> { + X509NameEntries { + name: self, + nid: nid, + loc: -1, + } + } +} + +pub struct X509NameEntries<'a> { + name: &'a Ref, + nid: Nid, + loc: c_int, +} + +impl<'a> Iterator for X509NameEntries<'a> { + type Item = &'a Ref; + + fn next(&mut self) -> Option<&'a Ref> { unsafe { - let loc = ffi::X509_NAME_get_index_by_NID(self.as_ptr(), nid.as_raw(), -1); - if loc == -1 { + self.loc = ffi::X509_NAME_get_index_by_NID(self.name.as_ptr(), + self.nid.as_raw(), + self.loc); + + if self.loc == -1 { return None; } - let ne = ffi::X509_NAME_get_entry(self.as_ptr(), loc); - if ne.is_null() { - return None; - } + let entry = ffi::X509_NAME_get_entry(self.name.as_ptr(), self.loc); + assert!(!entry.is_null()); - let asn1_str = ffi::X509_NAME_ENTRY_get_data(ne); - if asn1_str.is_null() { - return None; - } + Some(Ref::from_ptr(entry)) + } + } +} - let mut str_from_asn1: *mut u8 = ptr::null_mut(); - let len = ffi::ASN1_STRING_to_UTF8(&mut str_from_asn1, asn1_str); +type_!(X509NameEntry, ffi::X509_NAME_ENTRY, ffi::X509_NAME_ENTRY_free); - if len < 0 { - return None; - } - - assert!(!str_from_asn1.is_null()); - - Some(CryptoString::from_raw_parts(str_from_asn1, len as usize)) +impl Ref { + pub fn data(&self) -> &Ref { + unsafe { + let data = ffi::X509_NAME_ENTRY_get_data(self.as_ptr()); + Ref::from_ptr(data) } } } diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index 1c248ba2..db93c3a8 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -113,58 +113,42 @@ fn test_save_der() { #[test] fn test_subject_read_cn() { let cert = include_bytes!("../../test/cert.pem"); - let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); + let cert = X509::from_pem(cert).unwrap(); let subject = cert.subject_name(); - let cn = match subject.text_by_nid(nid::COMMONNAME) { - Some(x) => x, - None => panic!("Failed to read CN from cert"), - }; - - assert_eq!(&cn as &str, "foobar.com") + let cn = subject.entries_by_nid(nid::COMMONNAME).next().unwrap(); + assert_eq!(cn.data().as_slice(), b"foobar.com") } #[test] fn test_nid_values() { let cert = include_bytes!("../../test/nid_test_cert.pem"); - let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); + let cert = X509::from_pem(cert).unwrap(); let subject = cert.subject_name(); - let cn = match subject.text_by_nid(nid::COMMONNAME) { - Some(x) => x, - None => panic!("Failed to read CN from cert"), - }; - assert_eq!(&cn as &str, "example.com"); + let cn = subject.entries_by_nid(nid::COMMONNAME).next().unwrap(); + assert_eq!(cn.data().as_slice(), b"example.com"); - let email = match subject.text_by_nid(nid::PKCS9_EMAILADDRESS) { - Some(x) => x, - None => panic!("Failed to read subject email address from cert"), - }; - assert_eq!(&email as &str, "test@example.com"); + let email = subject.entries_by_nid(nid::PKCS9_EMAILADDRESS).next().unwrap(); + assert_eq!(email.data().as_slice(), b"test@example.com"); - let friendly = match subject.text_by_nid(nid::FRIENDLYNAME) { - Some(x) => x, - None => panic!("Failed to read subject friendly name from cert"), - }; - assert_eq!(&friendly as &str, "Example"); + let friendly = subject.entries_by_nid(nid::FRIENDLYNAME).next().unwrap(); + assert_eq!(&*friendly.data().as_utf8().unwrap(), "Example"); } #[test] fn test_nid_uid_value() { let cert = include_bytes!("../../test/nid_uid_test_cert.pem"); - let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); + let cert = X509::from_pem(cert).unwrap(); let subject = cert.subject_name(); - let cn = match subject.text_by_nid(nid::USERID) { - Some(x) => x, - None => panic!("Failed to read UID from cert"), - }; - assert_eq!(&cn as &str, "this is the userId"); + let cn = subject.entries_by_nid(nid::USERID).next().unwrap(); + assert_eq!(cn.data().as_slice(), b"this is the userId"); } #[test] fn test_subject_alt_name() { let cert = include_bytes!("../../test/alt_name_cert.pem"); - let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); + let cert = X509::from_pem(cert).unwrap(); let subject_alt_names = cert.subject_alt_names().unwrap(); assert_eq!(3, subject_alt_names.len()); From f71395c600a2605bf4a22c63e2c7ba8ae58e12c7 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 31 Oct 2016 22:45:51 -0700 Subject: [PATCH 148/186] Little cfg cleanup --- openssl/src/ssl/connector.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index 5520e578..b2e00a81 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -242,7 +242,7 @@ fn setup_verify(ssl: &mut Ssl, domain: &str) -> Result<(), ErrorStack> { param.set_host(domain) } -#[cfg(not(any(ossl102, ossl110)))] +#[cfg(ossl101)] fn setup_verify(ssl: &mut Ssl, domain: &str) -> Result<(), ErrorStack> { let domain = domain.to_owned(); ssl.set_verify_callback(SSL_VERIFY_PEER, @@ -250,7 +250,7 @@ fn setup_verify(ssl: &mut Ssl, domain: &str) -> Result<(), ErrorStack> { Ok(()) } -#[cfg(not(any(ossl102, ossl110)))] +#[cfg(ossl101)] mod verify { use std::net::IpAddr; use std::str; From dd4836cdf61842512338fa63eaabad80d3f12bde Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 31 Oct 2016 23:06:27 -0700 Subject: [PATCH 149/186] Fix 1.1.0 build --- openssl/src/asn1.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/openssl/src/asn1.rs b/openssl/src/asn1.rs index d0704693..78c66d4b 100644 --- a/openssl/src/asn1.rs +++ b/openssl/src/asn1.rs @@ -54,7 +54,7 @@ impl Ref { } pub fn as_slice(&self) -> &[u8] { - unsafe { slice::from_raw_parts(ffi::ASN1_STRING_data(self.as_ptr()), self.len()) } + unsafe { slice::from_raw_parts(ASN1_STRING_data(self.as_ptr()), self.len()) } } pub fn len(&self) -> usize { @@ -63,3 +63,12 @@ impl Ref { } } } + +#[cfg(any(ossl101, ossl102))] +use ffi::ASN1_STRING_data; + +#[cfg(ossl110)] +#[allow(bad_style)] +unsafe fn ASN1_STRING_data(s: *mut ffi::ASN1_STRING) -> *mut ::libc::c_uchar { + ffi::ASN1_STRING_get0_data(s) as *mut _ +} From 43911db26cd6044cb990b51898ce824d221bbb76 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 31 Oct 2016 23:09:07 -0700 Subject: [PATCH 150/186] Avoid extra allocations in Asn1Time Display impl --- openssl/src/asn1.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/openssl/src/asn1.rs b/openssl/src/asn1.rs index 78c66d4b..e1d94d09 100644 --- a/openssl/src/asn1.rs +++ b/openssl/src/asn1.rs @@ -1,7 +1,9 @@ -use libc::c_long; -use std::{ptr, fmt}; -use std::slice; use ffi; +use libc::c_long; +use std::fmt; +use std::ptr; +use std::slice; +use std::str; use {cvt, cvt_p}; use bio::MemBio; @@ -13,12 +15,11 @@ type_!(Asn1Time, ffi::ASN1_TIME, ffi::ASN1_TIME_free); impl fmt::Display for Ref { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mem_bio = try!(MemBio::new()); - let as_str = unsafe { + unsafe { + let mem_bio = try!(MemBio::new()); try!(cvt(ffi::ASN1_TIME_print(mem_bio.as_ptr(), self.as_ptr()))); - String::from_utf8_unchecked(mem_bio.get_buf().to_owned()) - }; - write!(f, "{}", as_str) + write!(f, "{}", str::from_utf8_unchecked(mem_bio.get_buf())) + } } } From 9ea27c12b9b5d2d723d8686f5bde4de0223cb160 Mon Sep 17 00:00:00 2001 From: Lionel Flandrin Date: Tue, 1 Nov 2016 11:55:02 +0100 Subject: [PATCH 151/186] Add method to encode a public key as a DER blob --- openssl-sys/src/lib.rs | 2 ++ openssl/src/pkey.rs | 11 ++++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index f556b19f..1a9a2ac1 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1693,6 +1693,8 @@ extern { pub fn i2d_X509_bio(b: *mut BIO, x: *mut X509) -> c_int; pub fn i2d_X509_REQ_bio(b: *mut BIO, x: *mut X509_REQ) -> c_int; + pub fn i2d_PUBKEY_bio(b: *mut BIO, x: *mut EVP_PKEY) -> c_int; + pub fn i2d_RSA_PUBKEY(k: *mut RSA, buf: *mut *mut u8) -> c_int; pub fn d2i_RSA_PUBKEY(k: *mut *mut RSA, buf: *mut *const u8, len: c_long) -> *mut RSA; pub fn i2d_RSAPrivateKey(k: *const RSA, buf: *mut *mut u8) -> c_int; diff --git a/openssl/src/pkey.rs b/openssl/src/pkey.rs index 6236b642..4885ad3c 100644 --- a/openssl/src/pkey.rs +++ b/openssl/src/pkey.rs @@ -40,7 +40,7 @@ impl Ref { Ok(mem_bio.get_buf().to_owned()) } - /// Stores public key as a PEM + /// Encode public key in PEM format pub fn public_key_to_pem(&self) -> Result, ErrorStack> { let mem_bio = try!(MemBio::new()); unsafe { @@ -49,6 +49,15 @@ impl Ref { Ok(mem_bio.get_buf().to_owned()) } + /// Encode public key in DER format + pub fn public_key_to_der(&self) -> Result, ErrorStack> { + let mem_bio = try!(MemBio::new()); + unsafe { + try!(cvt(ffi::i2d_PUBKEY_bio(mem_bio.as_ptr(), self.as_ptr()))); + } + Ok(mem_bio.get_buf().to_owned()) + } + pub fn public_eq(&self, other: &Ref) -> bool { unsafe { ffi::EVP_PKEY_cmp(self.as_ptr(), other.as_ptr()) == 1 } } From 3bdefa987a0d36bbf77687f2376f4b29f0a20814 Mon Sep 17 00:00:00 2001 From: Lionel Flandrin Date: Mon, 31 Oct 2016 23:49:38 +0100 Subject: [PATCH 152/186] Implement a generic Stack API to deal with OpenSSL stacks --- openssl-sys/src/ossl110.rs | 7 +- openssl/src/lib.rs | 1 + openssl/src/stack.rs | 319 +++++++++++++++++++++++++++++++++++++ 3 files changed, 323 insertions(+), 4 deletions(-) create mode 100644 openssl/src/stack.rs diff --git a/openssl-sys/src/ossl110.rs b/openssl-sys/src/ossl110.rs index 1a7c9e00..7d31b687 100644 --- a/openssl-sys/src/ossl110.rs +++ b/openssl-sys/src/ossl110.rs @@ -13,7 +13,6 @@ pub enum HMAC_CTX {} pub enum OPENSSL_STACK {} pub enum RSA {} pub enum SSL_CTX {} -pub enum _STACK {} pub enum stack_st_ASN1_OBJECT {} pub enum stack_st_GENERAL_NAME {} pub enum stack_st_OPENSSL_STRING {} @@ -147,7 +146,7 @@ extern { pub fn OpenSSL_version_num() -> c_ulong; pub fn OpenSSL_version(key: c_int) -> *const c_char; - pub fn OPENSSL_sk_free(st: *mut _STACK); - pub fn OPENSSL_sk_pop_free(st: *mut _STACK, free: Option); - pub fn OPENSSL_sk_pop(st: *mut _STACK) -> *mut c_void; + 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_pop(st: *mut ::OPENSSL_STACK) -> *mut c_void; } diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index d053606f..03f702b5 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -81,6 +81,7 @@ pub mod ssl; pub mod symm; pub mod version; pub mod x509; +pub mod stack; #[cfg(any(ossl102, ossl110))] mod verify; diff --git a/openssl/src/stack.rs b/openssl/src/stack.rs new file mode 100644 index 00000000..2cc53b5f --- /dev/null +++ b/openssl/src/stack.rs @@ -0,0 +1,319 @@ +use std::ops::{Deref, DerefMut, Index, IndexMut}; +use std::iter; +use std::borrow::Borrow; +use std::convert::AsRef; + +#[cfg(ossl110)] +use libc::c_int; + +use ffi; +use types::{OpenSslType, Ref}; + +/// Trait implemented by stackable types. This must *only* be +/// implemented on opaque types that can be directly casted into their +/// `CType`. +pub trait Stackable: OpenSslType { + /// C stack type for this element. Generally called + /// `stack_st_{ELEMENT_TYPE}`, normally hidden by the + /// `STACK_OF(ELEMENT_TYPE)` macro in the OpenSSL API. + type StackType; +} + +/// An owned stack of `T`. +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) + } +} + +impl Drop for Stack { + #[cfg(ossl10x)] + fn drop(&mut self) { + unsafe { + loop { + let ptr = ffi::sk_pop(self.as_stack()); + + if ptr.is_null() { + break; + } + + // Build the owned version of the object just to run + // its `drop` implementation and delete the item. + T::from_ptr(ptr as *mut _); + } + + ffi::sk_free(self.0 as *mut _); + } + } + + #[cfg(ossl110)] + fn drop(&mut self) { + unsafe { + loop { + let ptr = ffi::OPENSSL_sk_pop(self.as_stack()); + + if ptr.is_null() { + break; + } + + // Build the owned version of the object just to run + // its `drop` implementation and delete the item. + T::from_ptr(ptr as *mut _); + } + + ffi::OPENSSL_sk_free(self.0 as *mut _); + } + } +} + +impl AsRef>> for Stack { + fn as_ref(&self) -> &Ref> { + &*self + } +} + +impl Borrow>> for Stack { + fn borrow(&self) -> &Ref> { + &*self + } +} + +unsafe impl OpenSslType for Stack { + type CType = T::StackType; + + unsafe fn from_ptr(ptr: *mut T::StackType) -> Stack { + Stack(ptr) + } + + fn as_ptr(&self) -> *mut T::StackType { + self.0 + } +} + +impl Deref for Stack { + type Target = Ref>; + + fn deref(&self) -> &Ref> { + unsafe { Ref::from_ptr(self.0) } + } +} + +impl DerefMut for Stack { + fn deref_mut(&mut self) -> &mut ::types::Ref> { + unsafe { Ref::from_ptr_mut(self.0) } + } +} + +impl Ref> { + /// OpenSSL stack types are just a (kinda) typesafe wrapper around + /// a `_STACK` object. We can therefore safely cast it and access + /// the `_STACK` members without having to worry about the real + /// layout of `T::StackType`. + /// + /// If that sounds unsafe then keep in mind that's exactly how the + /// OpenSSL 1.1.0 new C stack code works. + #[cfg(ossl10x)] + fn as_stack(&self) -> *mut ffi::_STACK { + self.as_ptr() as *mut _ + } + + /// OpenSSL 1.1.0 replaced the stack macros with a functions and + /// only exposes an opaque OPENSSL_STACK struct + /// publicly. + #[cfg(ossl110)] + fn as_stack(&self) -> *mut ffi::OPENSSL_STACK { + self.as_ptr() as *mut _ + } + + /// Returns the number of items in the stack + pub fn len(&self) -> usize { + self._len() + } + + #[cfg(ossl10x)] + fn _len(&self) -> usize { + unsafe { (*self.as_stack()).num as usize } + } + + #[cfg(ossl110)] + fn _len(&self) -> usize { + unsafe { ffi::OPENSSL_sk_num(self.as_stack()) as usize } + } + + pub fn iter(&self) -> Iter { + // Unfortunately we can't simply convert the stack into a + // slice and use that because OpenSSL 1.1.0 doesn't directly + // expose the stack data (we have to use `OPENSSL_sk_value` + // instead). We have to rewrite the entire iteration framework + // instead. + + Iter { + stack: self, + pos: 0, + } + } + + pub fn iter_mut(&mut self) -> IterMut { + IterMut { + stack: self, + pos: 0, + } + } + + /// Returns a reference to the element at the given index in the + /// stack or `None` if the index is out of bounds + pub fn get(&self, idx: usize) -> Option<&Ref> { + if idx >= self.len() { + return None; + } + + unsafe { + let r = Ref::from_ptr(self._get(idx)); + + Some(r) + } + } + + /// Returns a mutable reference to the element at the given index in the + /// stack or `None` if the index is out of bounds + pub fn get_mut(&mut self, idx: usize) -> Option<&mut Ref> { + if idx >= self.len() { + return None; + } + + unsafe { + Some(Ref::from_ptr_mut(self._get(idx))) + } + } + + #[cfg(ossl10x)] + unsafe fn _get(&self, idx: usize) -> *mut T::CType { + *(*self.as_stack()).data.offset(idx as isize) as *mut _ + } + + #[cfg(ossl110)] + unsafe fn _get(&self, idx: usize) -> *mut T::CType { + ffi::OPENSSL_sk_value(self.as_stack(), idx as c_int) as *mut _ + } +} + +impl Index for Ref> { + type Output = Ref; + + fn index(&self, index: usize) -> &Ref { + self.get(index).unwrap() + } +} + +impl IndexMut for Ref> { + fn index_mut(&mut self, index: usize) -> &mut Ref { + self.get_mut(index).unwrap() + } +} + +impl<'a, T: Stackable> iter::IntoIterator for &'a Ref> { + type Item = &'a Ref; + type IntoIter = Iter<'a, T>; + + fn into_iter(self) -> Iter<'a, T> { + self.iter() + } +} + +impl<'a, T: Stackable> iter::IntoIterator for &'a mut Ref> { + type Item = &'a mut Ref; + type IntoIter = IterMut<'a, T>; + + fn into_iter(self) -> IterMut<'a, T> { + self.iter_mut() + } +} + +impl<'a, T: Stackable> iter::IntoIterator for &'a Stack { + type Item = &'a Ref; + type IntoIter = Iter<'a, T>; + + fn into_iter(self) -> Iter<'a, T> { + self.iter() + } +} + +impl<'a, T: Stackable> iter::IntoIterator for &'a mut Stack { + type Item = &'a mut Ref; + type IntoIter = IterMut<'a, T>; + + fn into_iter(self) -> IterMut<'a, T> { + self.iter_mut() + } +} + +/// An iterator over the stack's contents. +pub struct Iter<'a, T: Stackable> + where T: 'a { + stack: &'a Ref>, + pos: usize, +} + +impl<'a, T: Stackable> iter::Iterator for Iter<'a, T> { + type Item = &'a Ref; + + fn next(&mut self) -> Option<&'a Ref> { + let n = self.stack.get(self.pos); + + if n.is_some() { + self.pos += 1; + } + + n + } + + fn size_hint(&self) -> (usize, Option) { + let rem = self.stack.len() - self.pos; + + (rem, Some(rem)) + } +} + +impl<'a, T: Stackable> iter::ExactSizeIterator for Iter<'a, T> { +} + +/// A mutable iterator over the stack's contents. +pub struct IterMut<'a, T: Stackable + 'a> { + stack: &'a mut Ref>, + pos: usize, +} + +impl<'a, T: Stackable> iter::Iterator for IterMut<'a, T> { + type Item = &'a mut Ref; + + fn next(&mut self) -> Option<&'a mut Ref> { + if self.pos >= self.stack.len() { + None + } else { + // Rust won't allow us to get a mutable reference into + // `stack` in this situation since it can't statically + // guarantee that we won't return several references to + // the same object, so we have to use unsafe code for + // mutable iterators. + let n = unsafe { + Some(Ref::from_ptr_mut(self.stack._get(self.pos))) + }; + + self.pos += 1; + + n + } + } + + fn size_hint(&self) -> (usize, Option) { + let rem = self.stack.len() - self.pos; + + (rem, Some(rem)) + } +} + +impl<'a, T: Stackable> iter::ExactSizeIterator for IterMut<'a, T> { +} From 36bf0bb38750412e5c2700273a850f16398cc427 Mon Sep 17 00:00:00 2001 From: Lionel Flandrin Date: Mon, 31 Oct 2016 23:53:28 +0100 Subject: [PATCH 153/186] Replace GeneralNames by the new Stack API --- openssl/src/ssl/connector.rs | 10 ++- openssl/src/x509/mod.rs | 145 ++++------------------------------- openssl/src/x509/tests.rs | 6 +- 3 files changed, 25 insertions(+), 136 deletions(-) diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index b2e00a81..c95b0fa1 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -256,7 +256,8 @@ mod verify { use std::str; use nid; - use x509::{X509StoreContext, X509, GeneralNames, X509Name}; + use x509::{X509StoreContext, X509, X509Name, GeneralName}; + use stack::Stack; use types::Ref; pub fn verify_callback(domain: &str, @@ -275,15 +276,16 @@ mod verify { fn verify_hostname(domain: &str, cert: &Ref) -> bool { match cert.subject_alt_names() { - Some(names) => verify_subject_alt_names(domain, &names), + Some(names) => verify_subject_alt_names(domain, names), None => verify_subject_name(domain, &cert.subject_name()), } } - fn verify_subject_alt_names(domain: &str, names: &GeneralNames) -> bool { + fn verify_subject_alt_names(domain: &str, + names: Stack) -> bool { let ip = domain.parse(); - for name in names { + for name in &names { match ip { Ok(ip) => { if let Some(actual) = name.ipaddress() { diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 28f2542f..dcda5913 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -1,11 +1,10 @@ -use libc::{c_char, c_int, c_long, c_ulong, c_void}; +use libc::{c_char, c_int, c_long, c_ulong}; use std::borrow::Borrow; use std::cmp; 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::ptr; use std::slice; @@ -21,6 +20,7 @@ use error::ErrorStack; use ffi; use nid::Nid; use types::{OpenSslType, Ref}; +use stack::{Stack, Stackable}; #[cfg(ossl10x)] use ffi::{X509_set_notBefore, X509_set_notAfter, ASN1_STRING_data}; @@ -346,7 +346,7 @@ impl Ref { } /// Returns this certificate's SAN entries, if they exist. - pub fn subject_alt_names(&self) -> Option { + pub fn subject_alt_names(&self) -> Option> { unsafe { let stack = ffi::X509_get_ext_d2i(self.as_ptr(), ffi::NID_subject_alt_name, @@ -356,7 +356,7 @@ impl Ref { return None; } - Some(GeneralNames { stack: stack as *mut _ }) + Some(Stack::from_ptr(stack as *mut _)) } } @@ -678,135 +678,18 @@ impl X509VerifyError { } } -/// A collection of OpenSSL `GENERAL_NAME`s. -pub struct GeneralNames { - stack: *mut ffi::stack_st_GENERAL_NAME, -} +type_!(GeneralName, ffi::GENERAL_NAME, ffi::GENERAL_NAME_free); -impl Drop for GeneralNames { - #[cfg(ossl10x)] - fn drop(&mut self) { - unsafe { - // This transmute is dubious but it's what openssl itself does... - let free: unsafe extern "C" fn(*mut ffi::GENERAL_NAME) = ffi::GENERAL_NAME_free; - let free: unsafe extern "C" fn(*mut c_void) = mem::transmute(free); - ffi::sk_pop_free(&mut (*self.stack).stack, Some(free)); - } - } - - #[cfg(ossl110)] - fn drop(&mut self) { - unsafe { - // This transmute is dubious but it's what openssl itself does... - let free: unsafe extern "C" fn(*mut ffi::GENERAL_NAME) = ffi::GENERAL_NAME_free; - let free: unsafe extern "C" fn(*mut c_void) = mem::transmute(free); - ffi::OPENSSL_sk_pop_free(self.stack as *mut _, Some(free)); - } - } -} - -impl GeneralNames { - /// Returns the number of `GeneralName`s in this structure. - pub fn len(&self) -> usize { - self._len() - } - - #[cfg(ossl10x)] - fn _len(&self) -> usize { - unsafe { (*self.stack).stack.num as usize } - } - - #[cfg(ossl110)] - fn _len(&self) -> usize { - unsafe { ffi::OPENSSL_sk_num(self.stack as *const _) as usize } - } - - /// Returns the specified `GeneralName`. - /// - /// # Panics - /// - /// Panics if `idx` is not less than `len()`. - pub fn get<'a>(&'a self, idx: usize) -> GeneralName<'a> { - unsafe { - assert!(idx < self.len()); - GeneralName { - name: self._get(idx), - m: PhantomData, - } - } - } - - #[cfg(ossl10x)] - unsafe fn _get(&self, idx: usize) -> *const ffi::GENERAL_NAME { - *(*self.stack).stack.data.offset(idx as isize) as *const ffi::GENERAL_NAME - } - - #[cfg(ossl110)] - unsafe fn _get(&self, idx: usize) -> *const ffi::GENERAL_NAME { - ffi::OPENSSL_sk_value(self.stack as *const _, idx as c_int) as *mut _ - } - - /// Returns an iterator over the `GeneralName`s in this structure. - pub fn iter(&self) -> GeneralNamesIter { - GeneralNamesIter { - names: self, - idx: 0, - } - } -} - -impl<'a> IntoIterator for &'a GeneralNames { - type Item = GeneralName<'a>; - type IntoIter = GeneralNamesIter<'a>; - - fn into_iter(self) -> GeneralNamesIter<'a> { - self.iter() - } -} - -/// An iterator over OpenSSL `GENERAL_NAME`s. -pub struct GeneralNamesIter<'a> { - names: &'a GeneralNames, - idx: usize, -} - -impl<'a> Iterator for GeneralNamesIter<'a> { - type Item = GeneralName<'a>; - - fn next(&mut self) -> Option { - if self.idx < self.names.len() { - let name = self.names.get(self.idx); - self.idx += 1; - Some(name) - } else { - None - } - } - - fn size_hint(&self) -> (usize, Option) { - let size = self.names.len() - self.idx; - (size, Some(size)) - } -} - -impl<'a> ExactSizeIterator for GeneralNamesIter<'a> {} - -/// An OpenSSL `GENERAL_NAME`. -pub struct GeneralName<'a> { - name: *const ffi::GENERAL_NAME, - m: PhantomData<&'a ()>, -} - -impl<'a> GeneralName<'a> { +impl Ref { /// Returns the contents of this `GeneralName` if it is a `dNSName`. pub fn dnsname(&self) -> Option<&str> { unsafe { - if (*self.name).type_ != ffi::GEN_DNS { + if (*self.as_ptr()).type_ != ffi::GEN_DNS { return None; } - let ptr = ASN1_STRING_data((*self.name).d as *mut _); - let len = ffi::ASN1_STRING_length((*self.name).d as *mut _); + let ptr = ASN1_STRING_data((*self.as_ptr()).d as *mut _); + let len = ffi::ASN1_STRING_length((*self.as_ptr()).d as *mut _); let slice = slice::from_raw_parts(ptr as *const u8, len as usize); // dNSNames are stated to be ASCII (specifically IA5). Hopefully @@ -819,18 +702,22 @@ impl<'a> GeneralName<'a> { /// Returns the contents of this `GeneralName` if it is an `iPAddress`. pub fn ipaddress(&self) -> Option<&[u8]> { unsafe { - if (*self.name).type_ != ffi::GEN_IPADD { + if (*self.as_ptr()).type_ != ffi::GEN_IPADD { return None; } - let ptr = ASN1_STRING_data((*self.name).d as *mut _); - let len = ffi::ASN1_STRING_length((*self.name).d as *mut _); + let ptr = ASN1_STRING_data((*self.as_ptr()).d as *mut _); + let len = ffi::ASN1_STRING_length((*self.as_ptr()).d as *mut _); Some(slice::from_raw_parts(ptr as *const u8, len as usize)) } } } +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 diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index db93c3a8..2527d538 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -152,10 +152,10 @@ fn test_subject_alt_name() { let subject_alt_names = cert.subject_alt_names().unwrap(); assert_eq!(3, subject_alt_names.len()); - assert_eq!(Some("foobar.com"), subject_alt_names.get(0).dnsname()); - assert_eq!(subject_alt_names.get(1).ipaddress(), + assert_eq!(Some("foobar.com"), subject_alt_names[0].dnsname()); + assert_eq!(subject_alt_names[1].ipaddress(), Some(&[127, 0, 0, 1][..])); - assert_eq!(subject_alt_names.get(2).ipaddress(), + assert_eq!(subject_alt_names[2].ipaddress(), Some(&b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01"[..])); } From 8d0090faecea5dbcbf87a0446beb2e60828378bc Mon Sep 17 00:00:00 2001 From: Lionel Flandrin Date: Mon, 31 Oct 2016 23:55:00 +0100 Subject: [PATCH 154/186] Implement X509StoreContextRef::get_chain --- openssl-sys/src/ossl10x.rs | 1 + openssl-sys/src/ossl110.rs | 1 + openssl/src/x509/mod.rs | 26 ++++++++++++++++++++++++++ 3 files changed, 28 insertions(+) diff --git a/openssl-sys/src/ossl10x.rs b/openssl-sys/src/ossl10x.rs index 241dc782..07fa7d46 100644 --- a/openssl-sys/src/ossl10x.rs +++ b/openssl-sys/src/ossl10x.rs @@ -583,6 +583,7 @@ extern { 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_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; pub fn ASN1_STRING_to_UTF8(out: *mut *mut c_uchar, s: *mut ::ASN1_STRING) -> c_int; pub fn ASN1_STRING_data(x: *mut ::ASN1_STRING) -> *mut c_uchar; pub fn CRYPTO_add_lock(pointer: *mut c_int, diff --git a/openssl-sys/src/ossl110.rs b/openssl-sys/src/ossl110.rs index 7d31b687..1b0d9f34 100644 --- a/openssl-sys/src/ossl110.rs +++ b/openssl-sys/src/ossl110.rs @@ -141,6 +141,7 @@ extern { pub fn X509_up_ref(x: *mut X509) -> c_int; pub fn SSL_CTX_up_ref(x: *mut SSL_CTX) -> c_int; pub fn X509_get0_extensions(req: *const ::X509) -> *const stack_st_X509_EXTENSION; + pub fn X509_STORE_CTX_get0_chain(ctx: *mut ::X509_STORE_CTX) -> *mut stack_st_X509; pub fn EVP_MD_CTX_new() -> *mut EVP_MD_CTX; pub fn EVP_MD_CTX_free(ctx: *mut EVP_MD_CTX); diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index dcda5913..e27b03d1 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -67,6 +67,28 @@ impl Ref { pub fn error_depth(&self) -> u32 { unsafe { ffi::X509_STORE_CTX_get_error_depth(self.as_ptr()) as u32 } } + + pub fn get_chain(&self) -> Option<&Ref>> { + unsafe { + let chain = self._get_chain(); + + if chain.is_null() { + return None; + } + + Some(Ref::from_ptr(chain)) + } + } + + #[cfg(ossl110)] + unsafe fn _get_chain(&self) -> *mut ffi::stack_st_X509 { + ffi::X509_STORE_CTX_get0_chain(self.as_ptr()) + } + + #[cfg(ossl10x)] + unsafe fn _get_chain(&self) -> *mut ffi::stack_st_X509 { + ffi::X509_STORE_CTX_get_chain(self.as_ptr()) + } } #[allow(non_snake_case)] @@ -468,6 +490,10 @@ impl Borrow> for X509 { &*self } } + +impl Stackable for X509 { + type StackType = ffi::stack_st_X509; +} type_!(X509Name, ffi::X509_NAME, ffi::X509_NAME_free); From 79c51d5e517ffe40e01c34577667c0a242a5f6ba Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 1 Nov 2016 19:12:38 -0700 Subject: [PATCH 155/186] Clean up stack destructor --- openssl/src/stack.rs | 41 ++++++++++++++--------------------------- 1 file changed, 14 insertions(+), 27 deletions(-) diff --git a/openssl/src/stack.rs b/openssl/src/stack.rs index 2cc53b5f..bb1ddfda 100644 --- a/openssl/src/stack.rs +++ b/openssl/src/stack.rs @@ -9,12 +9,19 @@ use libc::c_int; use ffi; use types::{OpenSslType, Ref}; -/// Trait implemented by stackable types. This must *only* be -/// implemented on opaque types that can be directly casted into their -/// `CType`. +#[cfg(ossl10x)] +use ffi::{sk_pop as OPENSSL_sk_pop, sk_free as OPENSSL_sk_free}; +#[cfg(ossl110)] +use ffi::{OPENSSL_sk_pop, OPENSSL_sk_free}; + +/// Trait implemented by types which can be placed in a stack. +/// +/// Like `OpenSslType`, it should not be implemented for any type outside +/// of this crate. pub trait Stackable: OpenSslType { - /// C stack type for this element. Generally called - /// `stack_st_{ELEMENT_TYPE}`, normally hidden by the + /// The C stack type for this element. + /// + /// Generally called `stack_st_{ELEMENT_TYPE}`, normally hidden by the /// `STACK_OF(ELEMENT_TYPE)` macro in the OpenSSL API. type StackType; } @@ -30,11 +37,10 @@ impl Stack { } impl Drop for Stack { - #[cfg(ossl10x)] fn drop(&mut self) { unsafe { loop { - let ptr = ffi::sk_pop(self.as_stack()); + let ptr = OPENSSL_sk_pop(self.as_stack()); if ptr.is_null() { break; @@ -45,26 +51,7 @@ impl Drop for Stack { T::from_ptr(ptr as *mut _); } - ffi::sk_free(self.0 as *mut _); - } - } - - #[cfg(ossl110)] - fn drop(&mut self) { - unsafe { - loop { - let ptr = ffi::OPENSSL_sk_pop(self.as_stack()); - - if ptr.is_null() { - break; - } - - // Build the owned version of the object just to run - // its `drop` implementation and delete the item. - T::from_ptr(ptr as *mut _); - } - - ffi::OPENSSL_sk_free(self.0 as *mut _); + OPENSSL_sk_free(self.0 as *mut _); } } } From c776534ad4c89a23870aafb83709a25bc558fad0 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 1 Nov 2016 19:25:40 -0700 Subject: [PATCH 156/186] Clean up stack --- openssl-sys/src/ossl10x.rs | 2 ++ openssl/src/stack.rs | 28 ++++++---------------------- 2 files changed, 8 insertions(+), 22 deletions(-) diff --git a/openssl-sys/src/ossl10x.rs b/openssl-sys/src/ossl10x.rs index 07fa7d46..461ee9b5 100644 --- a/openssl-sys/src/ossl10x.rs +++ b/openssl-sys/src/ossl10x.rs @@ -594,6 +594,8 @@ 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_num(st: *mut _STACK) -> c_int; + pub fn sk_value(st: *mut _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_pop(st: *mut _STACK) -> *mut c_void; diff --git a/openssl/src/stack.rs b/openssl/src/stack.rs index bb1ddfda..e48ebe77 100644 --- a/openssl/src/stack.rs +++ b/openssl/src/stack.rs @@ -2,17 +2,16 @@ use std::ops::{Deref, DerefMut, Index, IndexMut}; use std::iter; use std::borrow::Borrow; use std::convert::AsRef; - -#[cfg(ossl110)] use libc::c_int; use ffi; use types::{OpenSslType, Ref}; #[cfg(ossl10x)] -use ffi::{sk_pop as OPENSSL_sk_pop, sk_free as OPENSSL_sk_free}; +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}; #[cfg(ossl110)] -use ffi::{OPENSSL_sk_pop, OPENSSL_sk_free}; +use ffi::{OPENSSL_sk_pop, OPENSSL_sk_free, OPENSSL_sk_num, OPENSSL_sk_value}; /// Trait implemented by types which can be placed in a stack. /// @@ -117,17 +116,7 @@ impl Ref> { /// Returns the number of items in the stack pub fn len(&self) -> usize { - self._len() - } - - #[cfg(ossl10x)] - fn _len(&self) -> usize { - unsafe { (*self.as_stack()).num as usize } - } - - #[cfg(ossl110)] - fn _len(&self) -> usize { - unsafe { ffi::OPENSSL_sk_num(self.as_stack()) as usize } + unsafe { OPENSSL_sk_num(self.as_stack()) as usize } } pub fn iter(&self) -> Iter { @@ -176,14 +165,9 @@ impl Ref> { } } - #[cfg(ossl10x)] unsafe fn _get(&self, idx: usize) -> *mut T::CType { - *(*self.as_stack()).data.offset(idx as isize) as *mut _ - } - - #[cfg(ossl110)] - unsafe fn _get(&self, idx: usize) -> *mut T::CType { - ffi::OPENSSL_sk_value(self.as_stack(), idx as c_int) as *mut _ + assert!(idx <= c_int::max_value() as usize); + OPENSSL_sk_value(self.as_stack(), idx as c_int) as *mut _ } } From d5a9a239f688f3820db6d61ed77467152dfe72cf Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 1 Nov 2016 19:36:08 -0700 Subject: [PATCH 157/186] More minor cleanup --- openssl/src/stack.rs | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/openssl/src/stack.rs b/openssl/src/stack.rs index e48ebe77..368b6e07 100644 --- a/openssl/src/stack.rs +++ b/openssl/src/stack.rs @@ -142,31 +142,28 @@ impl Ref> { /// Returns a reference to the element at the given index in the /// stack or `None` if the index is out of bounds pub fn get(&self, idx: usize) -> Option<&Ref> { - if idx >= self.len() { - return None; - } - unsafe { - let r = Ref::from_ptr(self._get(idx)); + if idx >= self.len() { + return None; + } - Some(r) + Some(Ref::from_ptr(self._get(idx))) } } /// Returns a mutable reference to the element at the given index in the /// stack or `None` if the index is out of bounds pub fn get_mut(&mut self, idx: usize) -> Option<&mut Ref> { - if idx >= self.len() { - return None; - } - unsafe { + if idx >= self.len() { + return None; + } + Some(Ref::from_ptr_mut(self._get(idx))) } } unsafe fn _get(&self, idx: usize) -> *mut T::CType { - assert!(idx <= c_int::max_value() as usize); OPENSSL_sk_value(self.as_stack(), idx as c_int) as *mut _ } } From e67733cc4e16d4d060dd022765a577cbe7fa2dfe Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 1 Nov 2016 19:45:38 -0700 Subject: [PATCH 158/186] Cleanup X509StoreContext::chain --- openssl/src/x509/mod.rs | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index e27b03d1..67760b86 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -23,10 +23,11 @@ use types::{OpenSslType, Ref}; use stack::{Stack, Stackable}; #[cfg(ossl10x)] -use ffi::{X509_set_notBefore, X509_set_notAfter, ASN1_STRING_data}; +use ffi::{X509_set_notBefore, X509_set_notAfter, ASN1_STRING_data, X509_STORE_CTX_get_chain}; #[cfg(ossl110)] use ffi::{X509_set1_notBefore as X509_set_notBefore, X509_set1_notAfter as X509_set_notAfter, - ASN1_STRING_get0_data as ASN1_STRING_data}; + ASN1_STRING_get0_data as ASN1_STRING_data, + X509_STORE_CTX_get0_chain as X509_STORE_CTX_get_chain}; #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] pub mod verify; @@ -68,9 +69,9 @@ impl Ref { unsafe { ffi::X509_STORE_CTX_get_error_depth(self.as_ptr()) as u32 } } - pub fn get_chain(&self) -> Option<&Ref>> { + pub fn chain(&self) -> Option<&Ref>> { unsafe { - let chain = self._get_chain(); + let chain = X509_STORE_CTX_get_chain(self.as_ptr()); if chain.is_null() { return None; @@ -79,16 +80,6 @@ impl Ref { Some(Ref::from_ptr(chain)) } } - - #[cfg(ossl110)] - unsafe fn _get_chain(&self) -> *mut ffi::stack_st_X509 { - ffi::X509_STORE_CTX_get0_chain(self.as_ptr()) - } - - #[cfg(ossl10x)] - unsafe fn _get_chain(&self) -> *mut ffi::stack_st_X509 { - ffi::X509_STORE_CTX_get_chain(self.as_ptr()) - } } #[allow(non_snake_case)] @@ -490,7 +481,7 @@ impl Borrow> for X509 { &*self } } - + impl Stackable for X509 { type StackType = ffi::stack_st_X509; } From 343ce159ec2a2fe584bcbdba6d26015d8a556bbd Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 1 Nov 2016 19:51:55 -0700 Subject: [PATCH 159/186] Fix stack signatures --- openssl-sys/src/ossl10x.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openssl-sys/src/ossl10x.rs b/openssl-sys/src/ossl10x.rs index 461ee9b5..a3f775d0 100644 --- a/openssl-sys/src/ossl10x.rs +++ b/openssl-sys/src/ossl10x.rs @@ -594,8 +594,8 @@ 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_num(st: *mut _STACK) -> c_int; - pub fn sk_value(st: *mut _STACK, n: c_int) -> *mut c_void; + 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_pop(st: *mut _STACK) -> *mut c_void; From 888b8b696c4adb36c30e5dc2551d6a4d6f79af47 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 1 Nov 2016 21:42:39 -0700 Subject: [PATCH 160/186] Fix docs --- openssl/src/bn.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs index 7542b25a..7bc8b2c9 100644 --- a/openssl/src/bn.rs +++ b/openssl/src/bn.rs @@ -211,7 +211,7 @@ impl BnCtx { } } - /// The cryptographically weak counterpart to `checked_new_random`. + /// The cryptographically weak counterpart to `rand`. pub fn pseudo_rand(r: &mut Ref, bits: i32, prop: RNGProperty, From 176348630a07f53808b33dae05c61b6dd0d8ef7f Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 1 Nov 2016 21:59:07 -0700 Subject: [PATCH 161/186] Don't clear BigNums in destructor Instead add a clear method. --- openssl-sys/src/lib.rs | 2 ++ openssl/src/bn.rs | 9 ++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 1a9a2ac1..f30d9f03 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1274,6 +1274,8 @@ extern { 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; diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs index 7bc8b2c9..989f65e0 100644 --- a/openssl/src/bn.rs +++ b/openssl/src/bn.rs @@ -225,6 +225,13 @@ impl BnCtx { } impl Ref { + /// Erases the memory used by this `BigNum`, resetting its value to 0. + /// + /// This can be used to destroy sensitive data such as keys when they are no longer needed. + pub fn clear(&mut self) { + unsafe { ffi::BN_clear(self.as_ptr()) } + } + /// Adds a `u32` to `self`. pub fn add_word(&mut self, w: u32) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_add_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) } @@ -431,7 +438,7 @@ impl Ref { } } -type_!(BigNum, ffi::BIGNUM, ffi::BN_clear_free); +type_!(BigNum, ffi::BIGNUM, ffi::BN_free); impl BigNum { /// Creates a new `BigNum` with the value 0. From aa0040125b4006bd7520220cb8330b5b3d24ffb4 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Tue, 1 Nov 2016 22:50:22 -0700 Subject: [PATCH 162/186] Use built in DH parameters when available Fall back to a hardcoded PEM blob on 1.0.1, but serialized from DH_get_2048_256. --- openssl-sys/src/lib.rs | 4 +-- openssl/src/dh.rs | 16 ++++++++- openssl/src/ssl/connector.rs | 64 +++++++++++++++++++++++++++--------- 3 files changed, 66 insertions(+), 18 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index f30d9f03..f5de44b6 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1346,8 +1346,8 @@ extern { pub fn CRYPTO_memcmp(a: *const c_void, b: *const c_void, len: size_t) -> c_int; + pub fn DH_new() -> *mut DH; pub fn DH_free(dh: *mut DH); - #[cfg(not(ossl101))] pub fn DH_get_1024_160() -> *mut DH; #[cfg(not(ossl101))] @@ -1471,6 +1471,7 @@ extern { pub fn PEM_read_bio_RSAPrivateKey(bio: *mut BIO, rsa: *mut *mut RSA, callback: Option, user_data: *mut c_void) -> *mut RSA; pub fn PEM_read_bio_RSA_PUBKEY(bio: *mut BIO, rsa: *mut *mut RSA, callback: Option, user_data: *mut c_void) -> *mut RSA; + pub fn PEM_write_bio_DHparams(bio: *mut BIO, x: *mut DH) -> c_int; pub fn PEM_write_bio_PrivateKey(bio: *mut BIO, pkey: *mut EVP_PKEY, cipher: *const EVP_CIPHER, kstr: *mut c_uchar, klen: c_int, callback: Option, @@ -1724,5 +1725,4 @@ extern { pub fn HMAC_Final(ctx: *mut HMAC_CTX, md: *mut c_uchar, len: *mut c_uint) -> c_int; - pub fn DH_new() -> *mut DH; } diff --git a/openssl/src/dh.rs b/openssl/src/dh.rs index 4ae145d6..4dfe26cb 100644 --- a/openssl/src/dh.rs +++ b/openssl/src/dh.rs @@ -5,11 +5,25 @@ use std::ptr; use std::mem; use {cvt, cvt_p}; +use bio::MemBio; use bn::BigNum; -use types::OpenSslType; +use types::{OpenSslType, Ref}; type_!(Dh, ffi::DH, ffi::DH_free); +impl Ref { + /// Encodes the parameters to PEM. + pub fn to_pem(&self) -> Result, ErrorStack> { + let mem_bio = try!(MemBio::new()); + + unsafe { + try!(cvt(ffi::PEM_write_bio_DHparams(mem_bio.as_ptr(), self.as_ptr()))); + } + + Ok(mem_bio.get_buf().to_owned()) + } +} + impl Dh { pub fn from_params(p: BigNum, g: BigNum, q: BigNum) -> Result { unsafe { diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index c95b0fa1..75a1a03c 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -8,22 +8,23 @@ use pkey::PKey; use x509::X509; use types::Ref; -// apps/dh2048.pem +// Serialized form of DH_get_2048_256 +#[cfg(any(ossl101, all(test, any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))))] const DHPARAM_PEM: &'static str = r#" -----BEGIN DH PARAMETERS----- -MIIBCAKCAQEA///////////JD9qiIWjCNMTGYouA3BzRKQJOCIpnzHQCC76mOxOb -IlFKCHmONATd75UZs806QxswKwpt8l8UN0/hNW1tUcJF5IW1dmJefsb0TELppjft -awv/XLb0Brft7jhr+1qJn6WunyQRfEsf5kkoZlHs5Fs9wgB8uKFjvwWY2kg2HFXT -mmkWP6j9JM9fg2VdI9yjrZYcYvNWIIVSu57VKQdwlpZtZww1Tkq8mATxdGwIyhgh -fDKQXkYuNs474553LBgOhgObJ4Oi7Aeij7XFXfBvTFLJ3ivL9pVYFxg5lUl86pVq -5RXSJhiY+gUQFXKOWoqsqmj//////////wIBAg== +MIICCQKCAQEAh6jmHbS2Zjz/u9GcZRlZmYzu9ghmDdDyXSzu1ENeOwDgDfjx1hlX +1Pr330VhsqowFsPZETQJb6o79Cltgw6afCCeDGSXUXq9WoqdMGvPZ+2R+eZyW0dY +wCLgse9Cdb97bFv8EdRfkIi5QfVOseWbuLw5oL8SMH9cT9twxYGyP3a2Osrhyqa3 +kC1SUmc1SIoO8TxtmlG/pKs62DR3llJNjvahZ7WkGCXZZ+FE5RQFZCUcysuD5rSG +9rPKP3lxUGAmwLhX9omWKFbe1AEKvQvmIcOjlgpU5xDDdfJjddcBQQOktUMwwZiv +EmEW0iduEXFfaTh3+tfvCcrbCUrpHhoVlwKCAQA/syybcxNNCy53UGZg7b1ITKex +jyHvIFQH9Hk6GguhJRDbwVB3vkY//0/tSqwLtVW+OmwbDGtHsbw3c79+jG9ikBIo ++MKMuxilWuMTQQAKZQGW+THHelfy3fRj5ensFEt3feYqqrioYorDdtKC1u04ZOZ5 +gkKOvIMdFDSPby+Rk7UEWvJ2cWTh38lnwfs/LlWkvRv/6DucgNBSuYXRguoK2yo7 +cxPT/hTISEseBSWIubfSu9LfAWGZ7NBuFVfNCRWzNTu7ZODsN3/QKDcN+StSx4kU +KM3GfrYYS1I9HbJGwy9jB4SQ8A741kfRSNR5VFFeIyfP75jFgmZLTA9sxBZZ -----END DH PARAMETERS----- - -These are the 2048-bit DH parameters from "More Modular Exponential -(MODP) Diffie-Hellman groups for Internet Key Exchange (IKE)": -https://tools.ietf.org/html/rfc3526 - -See https://tools.ietf.org/html/rfc2412 for how they were generated."#; +"#; fn ctx(method: SslMethod) -> Result { let mut ctx = try!(SslContextBuilder::new(method)); @@ -125,7 +126,7 @@ impl SslAcceptorBuilder { I::Item: AsRef> { let mut ctx = try!(ctx(method)); - let dh = try!(Dh::from_pem(DHPARAM_PEM.as_bytes())); + let dh = try!(get_dh()); try!(ctx.set_tmp_dh(&dh)); try!(setup_curves(&mut ctx)); try!(ctx.set_cipher_list("ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:\ @@ -202,9 +203,30 @@ impl SslAcceptorBuilder { } } +#[cfg(ossl101)] +fn get_dh() -> Result { + Dh::from_pem(DHPARAM_PEM.as_bytes()) +} + +#[cfg(not(ossl101))] +fn get_dh() -> Result { + use ffi; + + use cvt_p; + use types::OpenSslType; + + // manually call into ffi to avoid forcing the features + unsafe { + cvt_p(ffi::DH_get_2048_256()).map(|p| Dh::from_ptr(p)) + } +} + #[cfg(ossl101)] fn setup_curves(ctx: &mut SslContextBuilder) -> Result<(), ErrorStack> { - let curve = try!(::ec_key::EcKey::new_by_curve_name(::nid::X9_62_PRIME256V1)); + use ec_key::EcKey; + use nid; + + let curve = try!(EcKey::new_by_curve_name(nid::X9_62_PRIME256V1)); ctx.set_tmp_ecdh(&curve) } @@ -420,3 +442,15 @@ mod verify { } } } + +#[cfg(test)] +mod test { + #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] + #[test] + fn check_dhparam() { + use dh::Dh; + + let expected = String::from_utf8(Dh::get_2048_256().unwrap().to_pem().unwrap()).unwrap(); + assert_eq!(expected.trim(), super::DHPARAM_PEM.trim()); + } +} From 7f308aa5e1c440712217bc8b4310000372856459 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Wed, 2 Nov 2016 08:26:18 -0700 Subject: [PATCH 163/186] Fix signature --- openssl-sys/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index f5de44b6..ca1148d4 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1471,7 +1471,7 @@ extern { pub fn PEM_read_bio_RSAPrivateKey(bio: *mut BIO, rsa: *mut *mut RSA, callback: Option, user_data: *mut c_void) -> *mut RSA; pub fn PEM_read_bio_RSA_PUBKEY(bio: *mut BIO, rsa: *mut *mut RSA, callback: Option, user_data: *mut c_void) -> *mut RSA; - pub fn PEM_write_bio_DHparams(bio: *mut BIO, x: *mut DH) -> c_int; + pub fn PEM_write_bio_DHparams(bio: *mut BIO, x: *const DH) -> c_int; pub fn PEM_write_bio_PrivateKey(bio: *mut BIO, pkey: *mut EVP_PKEY, cipher: *const EVP_CIPHER, kstr: *mut c_uchar, klen: c_int, callback: Option, From 62a9f89fceca595c1868320974eb74c6a8f33307 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 3 Nov 2016 20:38:51 -0700 Subject: [PATCH 164/186] Avoid lhash weirdness --- openssl-sys/src/lib.rs | 3 +-- openssl-sys/src/ossl10x.rs | 2 ++ openssl-sys/src/ossl110.rs | 2 ++ openssl/src/x509/mod.rs | 16 ++++++++-------- systest/build.rs | 2 -- 5 files changed, 13 insertions(+), 12 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index ca1148d4..5266b5bc 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -23,6 +23,7 @@ pub enum ASN1_TIME {} pub enum ASN1_TYPE {} pub enum BN_CTX {} pub enum BN_GENCB {} +pub enum CONF {} pub enum COMP_METHOD {} pub enum EC_KEY {} pub enum ENGINE {} @@ -1676,8 +1677,6 @@ extern { pub fn X509_STORE_CTX_get_ex_data(ctx: *mut X509_STORE_CTX, idx: c_int) -> *mut c_void; pub fn X509_STORE_CTX_get_error_depth(ctx: *mut X509_STORE_CTX) -> c_int; - pub fn X509V3_EXT_conf_nid(conf: *mut c_void, ctx: *mut X509V3_CTX, ext_nid: c_int, value: *mut c_char) -> *mut X509_EXTENSION; - pub fn X509V3_EXT_conf(conf: *mut c_void, ctx: *mut X509V3_CTX, name: *mut c_char, value: *mut c_char) -> *mut X509_EXTENSION; 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 X509_REQ_add_extensions(req: *mut X509_REQ, exts: *mut stack_st_X509_EXTENSION) -> c_int; diff --git a/openssl-sys/src/ossl10x.rs b/openssl-sys/src/ossl10x.rs index a3f775d0..2b066446 100644 --- a/openssl-sys/src/ossl10x.rs +++ b/openssl-sys/src/ossl10x.rs @@ -584,6 +584,8 @@ extern { 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; + pub fn X509V3_EXT_nconf_nid(conf: *mut ::CONF, ctx: *mut ::X509V3_CTX, ext_nid: c_int, value: *mut c_char) -> *mut ::X509_EXTENSION; + pub fn X509V3_EXT_nconf(conf: *mut ::CONF, ctx: *mut ::X509V3_CTX, name: *mut c_char, value: *mut c_char) -> *mut ::X509_EXTENSION; pub fn ASN1_STRING_to_UTF8(out: *mut *mut c_uchar, s: *mut ::ASN1_STRING) -> c_int; pub fn ASN1_STRING_data(x: *mut ::ASN1_STRING) -> *mut c_uchar; pub fn CRYPTO_add_lock(pointer: *mut c_int, diff --git a/openssl-sys/src/ossl110.rs b/openssl-sys/src/ossl110.rs index 1b0d9f34..a2259fc6 100644 --- a/openssl-sys/src/ossl110.rs +++ b/openssl-sys/src/ossl110.rs @@ -63,6 +63,8 @@ extern { 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_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; + pub fn X509V3_EXT_nconf(conf: *mut ::CONF, ctx: *mut ::X509V3_CTX, name: *const c_char, value: *const c_char) -> *mut ::X509_EXTENSION; pub fn ASN1_STRING_to_UTF8(out: *mut *mut c_uchar, s: *const ::ASN1_STRING) -> c_int; pub fn BN_is_negative(b: *const ::BIGNUM) -> c_int; pub fn EVP_CIPHER_key_length(cipher: *const EVP_CIPHER) -> c_int; diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 67760b86..02bdcb01 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -213,17 +213,17 @@ impl X509Generator { let value = CString::new(value.as_bytes()).unwrap(); let ext = match exttype.get_nid() { Some(nid) => { - try!(cvt_p(ffi::X509V3_EXT_conf_nid(ptr::null_mut(), - mem::transmute(&ctx), - nid.as_raw(), - value.as_ptr() as *mut c_char))) + 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_conf(ptr::null_mut(), - mem::transmute(&ctx), - name.as_ptr() as *mut c_char, - value.as_ptr() as *mut c_char))) + 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 { diff --git a/systest/build.rs b/systest/build.rs index 8fac5536..38d43995 100644 --- a/systest/build.rs +++ b/systest/build.rs @@ -78,8 +78,6 @@ fn main() { }); cfg.skip_fn(move |s| { s == "CRYPTO_memcmp" || // uses volatile - s == "X509V3_EXT_conf_nid" || // weird lhash first param - s == "X509V3_EXT_conf" || // weird lhash first param // Skip some functions with function pointers on windows, not entirely // sure how to get them to work out... From e87b75fa03ab6ec78903087a069fd868cf02903e Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 3 Nov 2016 20:54:08 -0700 Subject: [PATCH 165/186] Rename BnCtx --- openssl/src/bn.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs index 989f65e0..a64d18bf 100644 --- a/openssl/src/bn.rs +++ b/openssl/src/bn.rs @@ -23,12 +23,12 @@ pub enum RNGProperty { TwoMsbOne = 1, } -type_!(BnCtx, ffi::BN_CTX, ffi::BN_CTX_free); +type_!(BigNumContext, ffi::BN_CTX, ffi::BN_CTX_free); -impl BnCtx { - /// Returns a new `BnCtx`. - pub fn new() -> Result { - unsafe { cvt_p(ffi::BN_CTX_new()).map(BnCtx) } +impl BigNumContext { + /// Returns a new `BigNumContext`. + pub fn new() -> Result { + unsafe { cvt_p(ffi::BN_CTX_new()).map(BigNumContext) } } /// Places the result of `a * b` in `r`. @@ -681,7 +681,7 @@ impl<'a, 'b> Mul<&'b Ref> for &'a Ref { type Output = BigNum; fn mul(self, oth: &Ref) -> BigNum { - let mut ctx = BnCtx::new().unwrap(); + let mut ctx = BigNumContext::new().unwrap(); let mut r = BigNum::new().unwrap(); ctx.mul(&mut r, self, oth).unwrap(); r @@ -694,7 +694,7 @@ impl<'a, 'b> Div<&'b Ref> for &'a Ref { type Output = BigNum; fn div(self, oth: &'b Ref) -> BigNum { - let mut ctx = BnCtx::new().unwrap(); + let mut ctx = BigNumContext::new().unwrap(); let mut dv = BigNum::new().unwrap(); ctx.div(Some(&mut dv), None, self, oth).unwrap(); dv @@ -707,7 +707,7 @@ impl<'a, 'b> Rem<&'b Ref> for &'a Ref { type Output = BigNum; fn rem(self, oth: &'b Ref) -> BigNum { - let mut ctx = BnCtx::new().unwrap(); + let mut ctx = BigNumContext::new().unwrap(); let mut rem = BigNum::new().unwrap(); ctx.div(None, Some(&mut rem), self, oth).unwrap(); rem @@ -780,7 +780,7 @@ impl Neg for BigNum { #[cfg(test)] mod tests { - use bn::{BnCtx, BigNum}; + use bn::{BigNumContext, BigNum}; #[test] fn test_to_from_slice() { @@ -805,7 +805,7 @@ mod tests { let mut p = BigNum::new().unwrap(); BigNum::generate_prime(&mut p, 128, true, None, Some(&a)).unwrap(); - let mut ctx = BnCtx::new().unwrap(); + let mut ctx = BigNumContext::new().unwrap(); assert!(ctx.is_prime(&p, 100).unwrap()); assert!(ctx.is_prime_fasttest(&p, 100, true).unwrap()); } From 772a50629455f195ba00009f008f6260c7b31f39 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 3 Nov 2016 21:06:23 -0700 Subject: [PATCH 166/186] Clean up some bignum APIs --- openssl/src/bn.rs | 135 +++++++++++++++++++++++----------------------- 1 file changed, 68 insertions(+), 67 deletions(-) diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs index a64d18bf..b398a048 100644 --- a/openssl/src/bn.rs +++ b/openssl/src/bn.rs @@ -10,18 +10,20 @@ use crypto::CryptoString; use error::ErrorStack; use types::{Ref, OpenSslType}; -/// Specifies the desired properties of a randomly generated `BigNum`. -#[derive(Copy, Clone)] -#[repr(C)] -pub enum RNGProperty { - /// The most significant bit of the number is allowed to be 0. - MsbMaybeZero = -1, - /// The MSB should be set to 1. - MsbOne = 0, - /// The two most significant bits of the number will be set to 1, so that the product of two - /// such random numbers will always have `2 * bits` length. - TwoMsbOne = 1, -} +/// Options for the most significant bits of a randomly generated `BigNum`. +pub struct MsbOption(c_int); + +/// The most significant bit of the number may be 0. +pub const MSB_MAYBE_ZERO: MsbOption = MsbOption(-1); + +/// The most significant bit of the number must be 1. +pub const MSB_ONE: MsbOption = MsbOption(0); + +/// The most significant two bits of the number must be 1. +/// +/// The number of bits in the product of two such numbers will always be exactly twice the number +/// of bits in the original numbers. +pub const TWO_MSB_ONE: MsbOption = MsbOption(1); type_!(BigNumContext, ffi::BN_CTX, ffi::BN_CTX_free); @@ -193,35 +195,6 @@ impl BigNumContext { .map(|r| r != 0) } } - - /// Generates a cryptographically strong pseudo-random `BigNum`, placing it in `r`. - /// - /// # Parameters - /// - /// * `bits`: Length of the number in bits. - /// * `prop`: The desired properties of the number. - /// * `odd`: If `true`, the generated number will be odd. - pub fn rand(r: &mut Ref, - bits: i32, - prop: RNGProperty, - odd: bool) - -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_rand(r.as_ptr(), bits.into(), prop as c_int, odd as c_int)).map(|_| ()) - } - } - - /// The cryptographically weak counterpart to `rand`. - pub fn pseudo_rand(r: &mut Ref, - bits: i32, - prop: RNGProperty, - odd: bool) - -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_pseudo_rand(r.as_ptr(), bits.into(), prop as c_int, odd as c_int)) - .map(|_| ()) - } - } } impl Ref { @@ -385,6 +358,59 @@ impl Ref { (self.num_bits() + 7) / 8 } + /// Generates a cryptographically strong pseudo-random `BigNum`, placing it in `self`. + /// + /// # Parameters + /// + /// * `bits`: Length of the number in bits. + /// * `msb`: The desired properties of the number. + /// * `odd`: If `true`, the generated number will be odd. + pub fn rand(&mut self, + bits: i32, + msb: MsbOption, + odd: bool) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_rand(self.as_ptr(), bits.into(), msb.0, odd as c_int)).map(|_| ()) + } + } + + /// The cryptographically weak counterpart to `rand`. + pub fn pseudo_rand(&mut self, + bits: i32, + msb: MsbOption, + odd: bool) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_pseudo_rand(self.as_ptr(), bits.into(), msb.0, odd as c_int)).map(|_| ()) + } + } + + /// Generates a prime number, placing it in `self`. + /// + /// # Parameters + /// + /// * `bits`: The length of the prime in bits (lower bound). + /// * `safe`: If true, returns a "safe" prime `p` so that `(p-1)/2` is also prime. + /// * `add`/`rem`: If `add` is set to `Some(add)`, `p % add == rem` will hold, where `p` is the + /// generated prime and `rem` is `1` if not specified (`None`). + pub fn generate_prime(&mut self, + bits: i32, + safe: bool, + add: Option<&Ref>, + rem: Option<&Ref>) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_generate_prime_ex(self.as_ptr(), + bits as c_int, + safe as c_int, + add.map(|n| n.as_ptr()).unwrap_or(ptr::null_mut()), + rem.map(|n| n.as_ptr()).unwrap_or(ptr::null_mut()), + ptr::null_mut())) + .map(|_| ()) + } + } + /// Returns a big-endian byte vector representation of the absolute value of `self`. /// /// `self` can be recreated by using `new_from_slice`. @@ -492,31 +518,6 @@ impl BigNum { .map(|p| BigNum::from_ptr(p)) } } - - /// Generates a prime number, placing it in `r`. - /// - /// # Parameters - /// - /// * `bits`: The length of the prime in bits (lower bound). - /// * `safe`: If true, returns a "safe" prime `p` so that `(p-1)/2` is also prime. - /// * `add`/`rem`: If `add` is set to `Some(add)`, `p % add == rem` will hold, where `p` is the - /// generated prime and `rem` is `1` if not specified (`None`). - pub fn generate_prime(r: &mut Ref, - bits: i32, - safe: bool, - add: Option<&Ref>, - rem: Option<&Ref>) - -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_generate_prime_ex(r.as_ptr(), - bits as c_int, - safe as c_int, - add.map(|n| n.as_ptr()).unwrap_or(ptr::null_mut()), - rem.map(|n| n.as_ptr()).unwrap_or(ptr::null_mut()), - ptr::null_mut())) - .map(|_| ()) - } - } } impl AsRef> for BigNum { @@ -803,7 +804,7 @@ mod tests { fn test_prime_numbers() { let a = BigNum::from_u32(19029017).unwrap(); let mut p = BigNum::new().unwrap(); - BigNum::generate_prime(&mut p, 128, true, None, Some(&a)).unwrap(); + p.generate_prime(128, true, None, Some(&a)).unwrap(); let mut ctx = BigNumContext::new().unwrap(); assert!(ctx.is_prime(&p, 100).unwrap()); From 6fe7dd3024e5c62fa12c2c3abd30af5c0235bba6 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 3 Nov 2016 21:15:47 -0700 Subject: [PATCH 167/186] Remove an enum --- openssl/src/ssl/mod.rs | 4 ++-- openssl/src/ssl/tests/mod.rs | 28 +++++++++++++--------------- openssl/src/x509/mod.rs | 16 ++++++++++------ 3 files changed, 25 insertions(+), 23 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 68d411c7..4f5039de 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -567,7 +567,7 @@ impl SslContextBuilder { unsafe { cvt(ffi::SSL_CTX_use_certificate_file(self.as_ptr(), file.as_ptr() as *const _, - file_type as c_int)) + file_type.as_raw())) .map(|_| ()) } } @@ -607,7 +607,7 @@ impl SslContextBuilder { unsafe { cvt(ffi::SSL_CTX_use_PrivateKey_file(self.as_ptr(), file.as_ptr() as *const _, - file_type as c_int)) + file_type.as_raw())) .map(|_| ()) } } diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 13b3a8a7..2a27dff4 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -20,9 +20,7 @@ use ssl::SSL_VERIFY_PEER; use ssl::{SslMethod, HandshakeError}; use ssl::{SslContext, SslStream, Ssl, ShutdownResult, SslConnectorBuilder, SslAcceptorBuilder, Error}; -use x509::X509StoreContext; -use x509::X509FileType; -use x509::X509; +use x509::{X509StoreContext, X509, X509_FILETYPE_PEM}; #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] use x509::verify::X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS; use pkey::PKey; @@ -369,8 +367,8 @@ fn test_write_hits_stream() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM).unwrap(); - ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM).unwrap(); + ctx.set_certificate_file(&Path::new("test/cert.pem"), X509_FILETYPE_PEM).unwrap(); + ctx.set_private_key_file(&Path::new("test/key.pem"), X509_FILETYPE_PEM).unwrap(); let stream = listener.accept().unwrap().0; let mut stream = Ssl::new(&ctx.build()).unwrap().accept(stream).unwrap(); @@ -634,9 +632,9 @@ fn test_npn_server_advertise_multiple() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); - assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) + assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509_FILETYPE_PEM) .is_ok()); - ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM) + ctx.set_private_key_file(&Path::new("test/key.pem"), X509_FILETYPE_PEM) .unwrap(); ctx.build() }; @@ -675,9 +673,9 @@ fn test_alpn_server_advertise_multiple() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); - assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) + assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509_FILETYPE_PEM) .is_ok()); - ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM) + ctx.set_private_key_file(&Path::new("test/key.pem"), X509_FILETYPE_PEM) .unwrap(); ctx.build() }; @@ -716,9 +714,9 @@ fn test_alpn_server_select_none() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); - assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) + assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509_FILETYPE_PEM) .is_ok()); - ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM) + ctx.set_private_key_file(&Path::new("test/key.pem"), X509_FILETYPE_PEM) .unwrap(); ctx.build() }; @@ -751,9 +749,9 @@ fn test_alpn_server_select_none() { let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); ctx.set_verify(SSL_VERIFY_PEER); ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); - assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM) + assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509_FILETYPE_PEM) .is_ok()); - ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM) + ctx.set_private_key_file(&Path::new("test/key.pem"), X509_FILETYPE_PEM) .unwrap(); ctx.build() }; @@ -1162,8 +1160,8 @@ fn shutdown() { thread::spawn(move || { let stream = listener.accept().unwrap().0; let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM).unwrap(); - ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM).unwrap(); + ctx.set_certificate_file(&Path::new("test/cert.pem"), X509_FILETYPE_PEM).unwrap(); + ctx.set_private_key_file(&Path::new("test/key.pem"), X509_FILETYPE_PEM).unwrap(); let ssl = Ssl::new(&ctx.build()).unwrap(); let mut stream = ssl.accept(stream).unwrap(); diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 02bdcb01..bffb193c 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -39,14 +39,18 @@ pub mod extension; #[cfg(test)] mod tests; -#[derive(Copy, Clone)] -#[repr(i32)] -pub enum X509FileType { - PEM = ffi::X509_FILETYPE_PEM, - ASN1 = ffi::X509_FILETYPE_ASN1, - Default = ffi::X509_FILETYPE_DEFAULT, +pub struct X509FileType(c_int); + +impl X509FileType { + pub fn as_raw(&self) -> c_int { + self.0 + } } +pub const X509_FILETYPE_PEM: X509FileType = X509FileType(ffi::X509_FILETYPE_PEM); +pub const X509_FILETYPE_ASN1: X509FileType = X509FileType(ffi::X509_FILETYPE_ASN1); +pub const X509_FILETYPE_DEFAULT: X509FileType = X509FileType(ffi::X509_FILETYPE_DEFAULT); + type_!(X509StoreContext, ffi::X509_STORE_CTX, ffi::X509_STORE_CTX_free); impl Ref { From 25443d7b486576b846ed90125e3e56e16c9bc734 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 4 Nov 2016 12:15:05 -0700 Subject: [PATCH 168/186] Make utility functions private --- openssl/src/lib.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index 03f702b5..785ffb39 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -85,7 +85,7 @@ pub mod stack; #[cfg(any(ossl102, ossl110))] mod verify; -pub fn cvt_p(r: *mut T) -> Result<*mut T, ErrorStack> { +fn cvt_p(r: *mut T) -> Result<*mut T, ErrorStack> { if r.is_null() { Err(ErrorStack::get()) } else { @@ -93,7 +93,7 @@ pub fn cvt_p(r: *mut T) -> Result<*mut T, ErrorStack> { } } -pub fn cvt(r: c_int) -> Result { +fn cvt(r: c_int) -> Result { if r <= 0 { Err(ErrorStack::get()) } else { @@ -101,6 +101,6 @@ pub fn cvt(r: c_int) -> Result { } } -pub fn cvt_n(r: c_int) -> Result { +fn cvt_n(r: c_int) -> Result { if r < 0 { Err(ErrorStack::get()) } else { Ok(r) } } From 01ae978db0dc8620b2cc754c0d5cf94a68c1f549 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 4 Nov 2016 16:32:20 -0700 Subject: [PATCH 169/186] Get rid of Ref There's unfortunately a rustdoc bug that causes all methods implemented for any Ref to be inlined in the deref methods section :( --- openssl/src/asn1.rs | 10 +- openssl/src/bn.rs | 178 +++++++++++++++++------------------ openssl/src/dh.rs | 6 +- openssl/src/dsa.rs | 20 ++-- openssl/src/ec_key.rs | 2 +- openssl/src/lib.rs | 25 ++--- openssl/src/pkey.rs | 12 +-- openssl/src/rsa.rs | 28 +++--- openssl/src/sign.rs | 12 +-- openssl/src/ssl/connector.rs | 33 ++++--- openssl/src/ssl/mod.rs | 82 ++++++++-------- openssl/src/ssl/tests/mod.rs | 2 +- openssl/src/stack.rs | 82 ++++++++-------- openssl/src/types.rs | 33 +++---- openssl/src/util.rs | 7 +- openssl/src/verify.rs | 6 +- openssl/src/x509/mod.rs | 78 +++++++-------- 17 files changed, 317 insertions(+), 299 deletions(-) diff --git a/openssl/src/asn1.rs b/openssl/src/asn1.rs index e1d94d09..46c28740 100644 --- a/openssl/src/asn1.rs +++ b/openssl/src/asn1.rs @@ -9,11 +9,11 @@ use {cvt, cvt_p}; use bio::MemBio; use crypto::CryptoString; use error::ErrorStack; -use types::{OpenSslType, Ref}; +use types::{OpenSslType, OpenSslTypeRef}; -type_!(Asn1Time, ffi::ASN1_TIME, ffi::ASN1_TIME_free); +type_!(Asn1Time, Asn1TimeRef, ffi::ASN1_TIME, ffi::ASN1_TIME_free); -impl fmt::Display for Ref { +impl fmt::Display for Asn1TimeRef { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { unsafe { let mem_bio = try!(MemBio::new()); @@ -39,9 +39,9 @@ impl Asn1Time { } } -type_!(Asn1String, ffi::ASN1_STRING, ffi::ASN1_STRING_free); +type_!(Asn1String, Asn1StringRef, ffi::ASN1_STRING, ffi::ASN1_STRING_free); -impl Ref { +impl Asn1StringRef { pub fn as_utf8(&self) -> Result { unsafe { let mut ptr = ptr::null_mut(); diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs index b398a048..a3235c1f 100644 --- a/openssl/src/bn.rs +++ b/openssl/src/bn.rs @@ -8,7 +8,7 @@ use std::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub, Deref}; use {cvt, cvt_p, cvt_n}; use crypto::CryptoString; use error::ErrorStack; -use types::{Ref, OpenSslType}; +use types::{OpenSslType, OpenSslTypeRef}; /// Options for the most significant bits of a randomly generated `BigNum`. pub struct MsbOption(c_int); @@ -25,7 +25,7 @@ pub const MSB_ONE: MsbOption = MsbOption(0); /// of bits in the original numbers. pub const TWO_MSB_ONE: MsbOption = MsbOption(1); -type_!(BigNumContext, ffi::BN_CTX, ffi::BN_CTX_free); +type_!(BigNumContext, BigNumContextRef, ffi::BN_CTX, ffi::BN_CTX_free); impl BigNumContext { /// Returns a new `BigNumContext`. @@ -35,19 +35,19 @@ impl BigNumContext { /// Places the result of `a * b` in `r`. pub fn mul(&mut self, - r: &mut Ref, - a: &Ref, - b: &Ref) + r: &mut BigNumRef, + a: &BigNumRef, + b: &BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_mul(r.as_ptr(), a.as_ptr(), b.as_ptr(), self.as_ptr())).map(|_| ()) } } /// Places the result of `a / b` in `dv` and `a mod b` in `rem`. pub fn div(&mut self, - dv: Option<&mut Ref>, - rem: Option<&mut Ref>, - a: &Ref, - b: &Ref) + dv: Option<&mut BigNumRef>, + rem: Option<&mut BigNumRef>, + a: &BigNumRef, + b: &BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_div(dv.map(|b| b.as_ptr()).unwrap_or(ptr::null_mut()), @@ -60,25 +60,25 @@ impl BigNumContext { } /// Places the result of `a²` in `r`. - pub fn sqr(&mut self, r: &mut Ref, a: &Ref) -> Result<(), ErrorStack> { + pub fn sqr(&mut self, r: &mut BigNumRef, a: &BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_sqr(r.as_ptr(), a.as_ptr(), self.as_ptr())).map(|_| ()) } } /// Places the result of `a mod m` in `r`. pub fn nnmod(&mut self, - r: &mut Ref, - a: &Ref, - m: &Ref) + r: &mut BigNumRef, + a: &BigNumRef, + m: &BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_nnmod(r.as_ptr(), a.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) } } /// Places the result of `(a + b) mod m` in `r`. pub fn mod_add(&mut self, - r: &mut Ref, - a: &Ref, - b: &Ref, - m: &Ref) + r: &mut BigNumRef, + a: &BigNumRef, + b: &BigNumRef, + m: &BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_mod_add(r.as_ptr(), a.as_ptr(), b.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) @@ -87,10 +87,10 @@ impl BigNumContext { /// Places the result of `(a - b) mod m` in `r`. pub fn mod_sub(&mut self, - r: &mut Ref, - a: &Ref, - b: &Ref, - m: &Ref) + r: &mut BigNumRef, + a: &BigNumRef, + b: &BigNumRef, + m: &BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_mod_sub(r.as_ptr(), a.as_ptr(), b.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) @@ -99,10 +99,10 @@ impl BigNumContext { /// Places the result of `(a * b) mod m` in `r`. pub fn mod_mul(&mut self, - r: &mut Ref, - a: &Ref, - b: &Ref, - m: &Ref) + r: &mut BigNumRef, + a: &BigNumRef, + b: &BigNumRef, + m: &BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_mod_mul(r.as_ptr(), a.as_ptr(), b.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) @@ -111,28 +111,28 @@ impl BigNumContext { /// Places the result of `a² mod m` in `r`. pub fn mod_sqr(&mut self, - r: &mut Ref, - a: &Ref, - m: &Ref) + r: &mut BigNumRef, + a: &BigNumRef, + m: &BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_mod_sqr(r.as_ptr(), a.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) } } /// Places the result of `a^p` in `r`. pub fn exp(&mut self, - r: &mut Ref, - a: &Ref, - p: &Ref) + r: &mut BigNumRef, + a: &BigNumRef, + p: &BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_exp(r.as_ptr(), a.as_ptr(), p.as_ptr(), self.0)).map(|_| ()) } } /// Places the result of `a^p mod m` in `r`. pub fn mod_exp(&mut self, - r: &mut Ref, - a: &Ref, - p: &Ref, - m: &Ref) + r: &mut BigNumRef, + a: &BigNumRef, + p: &BigNumRef, + m: &BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_mod_exp(r.as_ptr(), a.as_ptr(), p.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) @@ -141,9 +141,9 @@ impl BigNumContext { /// Places the inverse of `a` modulo `n` in `r`. pub fn mod_inverse(&mut self, - r: &mut Ref, - a: &Ref, - n: &Ref) + r: &mut BigNumRef, + a: &BigNumRef, + n: &BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt_p(ffi::BN_mod_inverse(r.as_ptr(), a.as_ptr(), n.as_ptr(), self.as_ptr())) @@ -153,9 +153,9 @@ impl BigNumContext { /// Places the greatest common denominator of `a` and `b` in `r`. pub fn gcd(&mut self, - r: &mut Ref, - a: &Ref, - b: &Ref) + r: &mut BigNumRef, + a: &BigNumRef, + b: &BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_gcd(r.as_ptr(), a.as_ptr(), b.as_ptr(), self.as_ptr())).map(|_| ()) } } @@ -165,7 +165,7 @@ impl BigNumContext { /// Performs a Miller-Rabin probabilistic primality test with `checks` iterations. /// /// Returns `true` if `p` is prime with an error probability of less than `0.25 ^ checks`. - pub fn is_prime(&mut self, p: &Ref, checks: i32) -> Result { + pub fn is_prime(&mut self, p: &BigNumRef, checks: i32) -> Result { unsafe { cvt_n(ffi::BN_is_prime_ex(p.as_ptr(), checks.into(), self.as_ptr(), ptr::null_mut())) .map(|r| r != 0) @@ -182,7 +182,7 @@ impl BigNumContext { /// /// Returns `true` if `p` is prime with an error probability of less than `0.25 ^ checks`. pub fn is_prime_fasttest(&mut self, - p: &Ref, + p: &BigNumRef, checks: i32, do_trial_division: bool) -> Result { @@ -197,7 +197,7 @@ impl BigNumContext { } } -impl Ref { +impl BigNumRef { /// Erases the memory used by this `BigNum`, resetting its value to 0. /// /// This can be used to destroy sensitive data such as keys when they are no longer needed. @@ -246,12 +246,12 @@ impl Ref { /// Places a cryptographically-secure pseudo-random number nonnegative /// number less than `self` in `rnd`. - pub fn rand_in_range(&self, rnd: &mut Ref) -> Result<(), ErrorStack> { + pub fn rand_in_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_rand_range(self.as_ptr(), rnd.as_ptr())).map(|_| ()) } } /// The cryptographically weak counterpart to `rand_in_range`. - pub fn pseudo_rand_in_range(&self, rnd: &mut Ref) -> Result<(), ErrorStack> { + pub fn pseudo_rand_in_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_pseudo_rand_range(self.as_ptr(), rnd.as_ptr())).map(|_| ()) } } @@ -282,32 +282,32 @@ impl Ref { } /// Places `self << 1` in `r`. - pub fn lshift1(&self, r: &mut Ref) -> Result<(), ErrorStack> { + pub fn lshift1(&self, r: &mut BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_lshift1(r.as_ptr(), self.as_ptr())).map(|_| ()) } } /// Places `self >> 1` in `r`. - pub fn rshift1(&self, r: &mut Ref) -> Result<(), ErrorStack> { + pub fn rshift1(&self, r: &mut BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_rshift1(r.as_ptr(), self.as_ptr())).map(|_| ()) } } /// Places `self + b` in `r`. - pub fn add(&self, r: &mut Ref, b: &Ref) -> Result<(), ErrorStack> { + pub fn add(&self, r: &mut BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_add(r.as_ptr(), self.as_ptr(), b.as_ptr())).map(|_| ()) } } /// Places `self - b` in `r`. - pub fn sub(&self, r: &mut Ref, b: &Ref) -> Result<(), ErrorStack> { + pub fn sub(&self, r: &mut BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_sub(r.as_ptr(), self.as_ptr(), b.as_ptr())).map(|_| ()) } } /// Places `self << n` in `r`. - pub fn lshift(&self, r: &mut Ref, b: i32) -> Result<(), ErrorStack> { + pub fn lshift(&self, r: &mut BigNumRef, b: i32) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_lshift(r.as_ptr(), self.as_ptr(), b.into())).map(|_| ()) } } /// Places `self >> n` in `r`. - pub fn rshift(&self, r: &mut Ref, n: i32) -> Result<(), ErrorStack> { + pub fn rshift(&self, r: &mut BigNumRef, n: i32) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_rshift(r.as_ptr(), self.as_ptr(), n.into())).map(|_| ()) } } @@ -330,7 +330,7 @@ impl Ref { /// /// assert_eq!(s.ucmp(&o), Ordering::Equal); /// ``` - pub fn ucmp(&self, oth: &Ref) -> Ordering { + pub fn ucmp(&self, oth: &BigNumRef) -> Ordering { unsafe { ffi::BN_ucmp(self.as_ptr(), oth.as_ptr()).cmp(&0) } } @@ -397,8 +397,8 @@ impl Ref { pub fn generate_prime(&mut self, bits: i32, safe: bool, - add: Option<&Ref>, - rem: Option<&Ref>) + add: Option<&BigNumRef>, + rem: Option<&BigNumRef>) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_generate_prime_ex(self.as_ptr(), @@ -464,7 +464,7 @@ impl Ref { } } -type_!(BigNum, ffi::BIGNUM, ffi::BN_free); +type_!(BigNum, BigNumRef, ffi::BIGNUM, ffi::BN_free); impl BigNum { /// Creates a new `BigNum` with the value 0. @@ -520,13 +520,13 @@ impl BigNum { } } -impl AsRef> for BigNum { - fn as_ref(&self) -> &Ref { +impl AsRef for BigNum { + fn as_ref(&self) -> &BigNumRef { self.deref() } } -impl fmt::Debug for Ref { +impl fmt::Debug for BigNumRef { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.to_dec_str() { Ok(s) => f.write_str(&s), @@ -544,7 +544,7 @@ impl fmt::Debug for BigNum { } } -impl fmt::Display for Ref { +impl fmt::Display for BigNumRef { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.to_dec_str() { Ok(s) => f.write_str(&s), @@ -562,19 +562,19 @@ impl fmt::Display for BigNum { } } -impl PartialEq> for Ref { - fn eq(&self, oth: &Ref) -> bool { +impl PartialEq for BigNumRef { + fn eq(&self, oth: &BigNumRef) -> bool { self.cmp(oth) == Ordering::Equal } } -impl PartialEq for Ref { +impl PartialEq for BigNumRef { fn eq(&self, oth: &BigNum) -> bool { self.eq(oth.deref()) } } -impl Eq for Ref {} +impl Eq for BigNumRef {} impl PartialEq for BigNum { fn eq(&self, oth: &BigNum) -> bool { @@ -582,28 +582,28 @@ impl PartialEq for BigNum { } } -impl PartialEq> for BigNum { - fn eq(&self, oth: &Ref) -> bool { +impl PartialEq for BigNum { + fn eq(&self, oth: &BigNumRef) -> bool { self.deref().eq(oth) } } impl Eq for BigNum {} -impl PartialOrd> for Ref { - fn partial_cmp(&self, oth: &Ref) -> Option { +impl PartialOrd for BigNumRef { + fn partial_cmp(&self, oth: &BigNumRef) -> Option { Some(self.cmp(oth)) } } -impl PartialOrd for Ref { +impl PartialOrd for BigNumRef { fn partial_cmp(&self, oth: &BigNum) -> Option { Some(self.cmp(oth.deref())) } } -impl Ord for Ref { - fn cmp(&self, oth: &Ref) -> Ordering { +impl Ord for BigNumRef { + fn cmp(&self, oth: &BigNumRef) -> Ordering { unsafe { ffi::BN_cmp(self.as_ptr(), oth.as_ptr()).cmp(&0) } } } @@ -614,8 +614,8 @@ impl PartialOrd for BigNum { } } -impl PartialOrd> for BigNum { - fn partial_cmp(&self, oth: &Ref) -> Option { +impl PartialOrd for BigNum { + fn partial_cmp(&self, oth: &BigNumRef) -> Option { self.deref().partial_cmp(oth) } } @@ -628,7 +628,7 @@ impl Ord for BigNum { macro_rules! delegate { ($t:ident, $m:ident) => { - impl<'a, 'b> $t<&'b BigNum> for &'a Ref { + impl<'a, 'b> $t<&'b BigNum> for &'a BigNumRef { type Output = BigNum; fn $m(self, oth: &BigNum) -> BigNum { @@ -636,10 +636,10 @@ macro_rules! delegate { } } - impl<'a, 'b> $t<&'b Ref> for &'a BigNum { + impl<'a, 'b> $t<&'b BigNumRef> for &'a BigNum { type Output = BigNum; - fn $m(self, oth: &Ref) -> BigNum { + fn $m(self, oth: &BigNumRef) -> BigNum { $t::$m(self.deref(), oth) } } @@ -654,10 +654,10 @@ macro_rules! delegate { } } -impl<'a, 'b> Add<&'b Ref> for &'a Ref { +impl<'a, 'b> Add<&'b BigNumRef> for &'a BigNumRef { type Output = BigNum; - fn add(self, oth: &Ref) -> BigNum { + fn add(self, oth: &BigNumRef) -> BigNum { let mut r = BigNum::new().unwrap(); self.add(&mut r, oth).unwrap(); r @@ -666,10 +666,10 @@ impl<'a, 'b> Add<&'b Ref> for &'a Ref { delegate!(Add, add); -impl<'a, 'b> Sub<&'b Ref> for &'a Ref { +impl<'a, 'b> Sub<&'b BigNumRef> for &'a BigNumRef { type Output = BigNum; - fn sub(self, oth: &Ref) -> BigNum { + fn sub(self, oth: &BigNumRef) -> BigNum { let mut r = BigNum::new().unwrap(); self.sub(&mut r, oth).unwrap(); r @@ -678,10 +678,10 @@ impl<'a, 'b> Sub<&'b Ref> for &'a Ref { delegate!(Sub, sub); -impl<'a, 'b> Mul<&'b Ref> for &'a Ref { +impl<'a, 'b> Mul<&'b BigNumRef> for &'a BigNumRef { type Output = BigNum; - fn mul(self, oth: &Ref) -> BigNum { + fn mul(self, oth: &BigNumRef) -> BigNum { let mut ctx = BigNumContext::new().unwrap(); let mut r = BigNum::new().unwrap(); ctx.mul(&mut r, self, oth).unwrap(); @@ -691,10 +691,10 @@ impl<'a, 'b> Mul<&'b Ref> for &'a Ref { delegate!(Mul, mul); -impl<'a, 'b> Div<&'b Ref> for &'a Ref { +impl<'a, 'b> Div<&'b BigNumRef> for &'a BigNumRef { type Output = BigNum; - fn div(self, oth: &'b Ref) -> BigNum { + fn div(self, oth: &'b BigNumRef) -> BigNum { let mut ctx = BigNumContext::new().unwrap(); let mut dv = BigNum::new().unwrap(); ctx.div(Some(&mut dv), None, self, oth).unwrap(); @@ -704,10 +704,10 @@ impl<'a, 'b> Div<&'b Ref> for &'a Ref { delegate!(Div, div); -impl<'a, 'b> Rem<&'b Ref> for &'a Ref { +impl<'a, 'b> Rem<&'b BigNumRef> for &'a BigNumRef { type Output = BigNum; - fn rem(self, oth: &'b Ref) -> BigNum { + fn rem(self, oth: &'b BigNumRef) -> BigNum { let mut ctx = BigNumContext::new().unwrap(); let mut rem = BigNum::new().unwrap(); ctx.div(None, Some(&mut rem), self, oth).unwrap(); @@ -717,7 +717,7 @@ impl<'a, 'b> Rem<&'b Ref> for &'a Ref { delegate!(Rem, rem); -impl<'a> Shl for &'a Ref { +impl<'a> Shl for &'a BigNumRef { type Output = BigNum; fn shl(self, n: i32) -> BigNum { @@ -735,7 +735,7 @@ impl<'a> Shl for &'a BigNum { } } -impl<'a> Shr for &'a Ref { +impl<'a> Shr for &'a BigNumRef { type Output = BigNum; fn shr(self, n: i32) -> BigNum { @@ -753,7 +753,7 @@ impl<'a> Shr for &'a BigNum { } } -impl<'a> Neg for &'a Ref { +impl<'a> Neg for &'a BigNumRef { type Output = BigNum; fn neg(self) -> BigNum { diff --git a/openssl/src/dh.rs b/openssl/src/dh.rs index 4dfe26cb..5a07e50f 100644 --- a/openssl/src/dh.rs +++ b/openssl/src/dh.rs @@ -7,11 +7,11 @@ use std::mem; use {cvt, cvt_p}; use bio::MemBio; use bn::BigNum; -use types::{OpenSslType, Ref}; +use types::OpenSslTypeRef; -type_!(Dh, ffi::DH, ffi::DH_free); +type_!(Dh, DhRef, ffi::DH, ffi::DH_free); -impl Ref { +impl DhRef { /// Encodes the parameters to PEM. pub fn to_pem(&self) -> Result, ErrorStack> { let mem_bio = try!(MemBio::new()); diff --git a/openssl/src/dsa.rs b/openssl/src/dsa.rs index 6efa7050..9dd5669c 100644 --- a/openssl/src/dsa.rs +++ b/openssl/src/dsa.rs @@ -5,14 +5,14 @@ use std::fmt; use std::ptr; use bio::{MemBio, MemBioSlice}; -use bn::BigNum; +use bn::BigNumRef; use {cvt, cvt_p}; -use types::Ref; +use types::OpenSslTypeRef; use util::{CallbackState, invoke_passwd_cb}; -type_!(Dsa, ffi::DSA, ffi::DSA_free); +type_!(Dsa, DsaRef, ffi::DSA, ffi::DSA_free); -impl Ref { +impl DsaRef { /// Writes an DSA private key as unencrypted PEM formatted data pub fn private_key_to_pem(&self) -> Result, ErrorStack> { assert!(self.has_private_key()); @@ -44,35 +44,35 @@ impl Ref { } } - pub fn p(&self) -> Option<&Ref> { + pub fn p(&self) -> Option<&BigNumRef> { unsafe { let p = compat::pqg(self.as_ptr())[0]; if p.is_null() { None } else { - Some(Ref::::from_ptr(p as *mut _)) + Some(BigNumRef::from_ptr(p as *mut _)) } } } - pub fn q(&self) -> Option<&Ref> { + pub fn q(&self) -> Option<&BigNumRef> { unsafe { let q = compat::pqg(self.as_ptr())[1]; if q.is_null() { None } else { - Some(Ref::::from_ptr(q as *mut _)) + Some(BigNumRef::from_ptr(q as *mut _)) } } } - pub fn g(&self) -> Option<&Ref> { + pub fn g(&self) -> Option<&BigNumRef> { unsafe { let g = compat::pqg(self.as_ptr())[2]; if g.is_null() { None } else { - Some(Ref::::from_ptr(g as *mut _)) + Some(BigNumRef::from_ptr(g as *mut _)) } } } diff --git a/openssl/src/ec_key.rs b/openssl/src/ec_key.rs index 95175eaa..41501c14 100644 --- a/openssl/src/ec_key.rs +++ b/openssl/src/ec_key.rs @@ -4,7 +4,7 @@ use cvt_p; use error::ErrorStack; use nid::Nid; -type_!(EcKey, ffi::EC_KEY, ffi::EC_KEY_free); +type_!(EcKey, EcKeyRef, ffi::EC_KEY, ffi::EC_KEY_free); impl EcKey { pub fn new_by_curve_name(nid: Nid) -> Result { diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index 785ffb39..183bf495 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -21,19 +21,16 @@ use libc::c_int; use error::ErrorStack; macro_rules! type_ { - ($n:ident, $c:path, $d:path) => { + ($n:ident, $r:ident, $c:path, $d:path) => { pub struct $n(*mut $c); - unsafe impl ::types::OpenSslType for $n { + impl ::types::OpenSslType for $n { type CType = $c; + type Ref = $r; unsafe fn from_ptr(ptr: *mut $c) -> $n { $n(ptr) } - - fn as_ptr(&self) -> *mut $c { - self.0 - } } impl Drop for $n { @@ -43,18 +40,24 @@ macro_rules! type_ { } impl ::std::ops::Deref for $n { - type Target = ::types::Ref<$n>; + type Target = $r; - fn deref(&self) -> &::types::Ref<$n> { - unsafe { ::types::Ref::from_ptr(self.0) } + fn deref(&self) -> &$r { + unsafe { ::types::OpenSslTypeRef::from_ptr(self.0) } } } impl ::std::ops::DerefMut for $n { - fn deref_mut(&mut self) -> &mut ::types::Ref<$n> { - unsafe { ::types::Ref::from_ptr_mut(self.0) } + fn deref_mut(&mut self) -> &mut $r { + unsafe { ::types::OpenSslTypeRef::from_ptr_mut(self.0) } } } + + pub struct $r(::util::Opaque); + + impl ::types::OpenSslTypeRef for $r { + type CType = $c; + } } } diff --git a/openssl/src/pkey.rs b/openssl/src/pkey.rs index 4885ad3c..a1b90a86 100644 --- a/openssl/src/pkey.rs +++ b/openssl/src/pkey.rs @@ -6,14 +6,14 @@ use ffi; use {cvt, cvt_p}; use bio::{MemBio, MemBioSlice}; use dsa::Dsa; -use rsa::Rsa; +use rsa::{Rsa, RsaRef}; use error::ErrorStack; use util::{CallbackState, invoke_passwd_cb}; -use types::{OpenSslType, Ref}; +use types::{OpenSslType, OpenSslTypeRef}; -type_!(PKey, ffi::EVP_PKEY, ffi::EVP_PKEY_free); +type_!(PKey, PKeyRef, ffi::EVP_PKEY, ffi::EVP_PKEY_free); -impl Ref { +impl PKeyRef { /// Get a reference to the interal RSA key for direct access to the key components pub fn rsa(&self) -> Result { unsafe { @@ -58,7 +58,7 @@ impl Ref { Ok(mem_bio.get_buf().to_owned()) } - pub fn public_eq(&self, other: &Ref) -> bool { + pub fn public_eq(&self, other: &PKeyRef) -> bool { unsafe { ffi::EVP_PKEY_cmp(self.as_ptr(), other.as_ptr()) == 1 } } } @@ -148,7 +148,7 @@ impl PKey { } /// Assign an RSA key to this pkey. - pub fn set_rsa(&mut self, rsa: &Ref) -> Result<(), ErrorStack> { + pub fn set_rsa(&mut self, rsa: &RsaRef) -> Result<(), ErrorStack> { unsafe { // this needs to be a reference as the set1_RSA ups the reference count let rsa_ptr = rsa.as_ptr(); diff --git a/openssl/src/rsa.rs b/openssl/src/rsa.rs index 57a07bd1..bd1d16d3 100644 --- a/openssl/src/rsa.rs +++ b/openssl/src/rsa.rs @@ -5,11 +5,11 @@ use std::mem; use libc::{c_int, c_void, c_char}; use {cvt, cvt_p, cvt_n}; -use bn::BigNum; +use bn::{BigNum, BigNumRef}; use bio::{MemBio, MemBioSlice}; use error::ErrorStack; use util::{CallbackState, invoke_passwd_cb}; -use types::{OpenSslType, Ref}; +use types::OpenSslTypeRef; /// Type of encryption padding to use. #[derive(Copy, Clone)] @@ -19,9 +19,9 @@ pub const NO_PADDING: Padding = Padding(ffi::RSA_NO_PADDING); pub const PKCS1_PADDING: Padding = Padding(ffi::RSA_PKCS1_PADDING); pub const PKCS1_OAEP_PADDING: Padding = Padding(ffi::RSA_PKCS1_OAEP_PADDING); -type_!(Rsa, ffi::RSA, ffi::RSA_free); +type_!(Rsa, RsaRef, ffi::RSA, ffi::RSA_free); -impl Ref { +impl RsaRef { /// Writes an RSA private key as unencrypted PEM formatted data pub fn private_key_to_pem(&self) -> Result, ErrorStack> { let mem_bio = try!(MemBio::new()); @@ -153,57 +153,57 @@ impl Ref { } } - pub fn n(&self) -> Option<&Ref> { + pub fn n(&self) -> Option<&BigNumRef> { unsafe { let n = compat::key(self.as_ptr())[0]; if n.is_null() { None } else { - Some(Ref::::from_ptr(n as *mut _)) + Some(BigNumRef::from_ptr(n as *mut _)) } } } - pub fn d(&self) -> Option<&Ref> { + pub fn d(&self) -> Option<&BigNumRef> { unsafe { let d = compat::key(self.as_ptr())[2]; if d.is_null() { None } else { - Some(Ref::::from_ptr(d as *mut _)) + Some(BigNumRef::from_ptr(d as *mut _)) } } } - pub fn e(&self) -> Option<&Ref> { + pub fn e(&self) -> Option<&BigNumRef> { unsafe { let e = compat::key(self.as_ptr())[1]; if e.is_null() { None } else { - Some(Ref::::from_ptr(e as *mut _)) + Some(BigNumRef::from_ptr(e as *mut _)) } } } - pub fn p(&self) -> Option<&Ref> { + pub fn p(&self) -> Option<&BigNumRef> { unsafe { let p = compat::factors(self.as_ptr())[0]; if p.is_null() { None } else { - Some(Ref::::from_ptr(p as *mut _)) + Some(BigNumRef::from_ptr(p as *mut _)) } } } - pub fn q(&self) -> Option<&Ref> { + pub fn q(&self) -> Option<&BigNumRef> { unsafe { let q = compat::factors(self.as_ptr())[1]; if q.is_null() { None } else { - Some(Ref::::from_ptr(q as *mut _)) + Some(BigNumRef::from_ptr(q as *mut _)) } } } diff --git a/openssl/src/sign.rs b/openssl/src/sign.rs index aebfcca7..4ca551b6 100644 --- a/openssl/src/sign.rs +++ b/openssl/src/sign.rs @@ -61,16 +61,16 @@ use std::ptr; use {cvt, cvt_p}; use hash::MessageDigest; -use pkey::PKey; +use pkey::PKeyRef; use error::ErrorStack; -use types::Ref; +use types::OpenSslTypeRef; #[cfg(ossl110)] use ffi::{EVP_MD_CTX_new, EVP_MD_CTX_free}; #[cfg(any(ossl101, ossl102))] use ffi::{EVP_MD_CTX_create as EVP_MD_CTX_new, EVP_MD_CTX_destroy as EVP_MD_CTX_free}; -pub struct Signer<'a>(*mut ffi::EVP_MD_CTX, PhantomData<&'a Ref>); +pub struct Signer<'a>(*mut ffi::EVP_MD_CTX, PhantomData<&'a PKeyRef>); impl<'a> Drop for Signer<'a> { fn drop(&mut self) { @@ -81,7 +81,7 @@ impl<'a> Drop for Signer<'a> { } impl<'a> Signer<'a> { - pub fn new(type_: MessageDigest, pkey: &'a Ref) -> Result, ErrorStack> { + pub fn new(type_: MessageDigest, pkey: &'a PKeyRef) -> Result, ErrorStack> { unsafe { ffi::init(); @@ -129,7 +129,7 @@ impl<'a> Write for Signer<'a> { } } -pub struct Verifier<'a>(*mut ffi::EVP_MD_CTX, PhantomData<&'a Ref>); +pub struct Verifier<'a>(*mut ffi::EVP_MD_CTX, PhantomData<&'a PKeyRef>); impl<'a> Drop for Verifier<'a> { fn drop(&mut self) { @@ -140,7 +140,7 @@ impl<'a> Drop for Verifier<'a> { } impl<'a> Verifier<'a> { - pub fn new(type_: MessageDigest, pkey: &'a Ref) -> Result, ErrorStack> { + pub fn new(type_: MessageDigest, pkey: &'a PKeyRef) -> Result, ErrorStack> { unsafe { ffi::init(); diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index 75a1a03c..52d26ef5 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -4,9 +4,8 @@ use dh::Dh; use error::ErrorStack; use ssl::{self, SslMethod, SslContextBuilder, SslContext, Ssl, SSL_VERIFY_PEER, SslStream, HandshakeError}; -use pkey::PKey; -use x509::X509; -use types::Ref; +use pkey::PKeyRef; +use x509::X509Ref; // Serialized form of DH_get_2048_256 #[cfg(any(ossl101, all(test, any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))))] @@ -118,12 +117,12 @@ impl SslAcceptorBuilder { /// /// [docs]: https://wiki.mozilla.org/Security/Server_Side_TLS pub fn mozilla_intermediate(method: SslMethod, - private_key: &Ref, - certificate: &Ref, + private_key: &PKeyRef, + certificate: &X509Ref, chain: I) -> Result where I: IntoIterator, - I::Item: AsRef> + I::Item: AsRef { let mut ctx = try!(ctx(method)); let dh = try!(get_dh()); @@ -153,12 +152,12 @@ impl SslAcceptorBuilder { /// /// [docs]: https://wiki.mozilla.org/Security/Server_Side_TLS pub fn mozilla_modern(method: SslMethod, - private_key: &Ref, - certificate: &Ref, + private_key: &PKeyRef, + certificate: &X509Ref, chain: I) -> Result where I: IntoIterator, - I::Item: AsRef> + I::Item: AsRef { let mut ctx = try!(ctx(method)); try!(setup_curves(&mut ctx)); @@ -171,12 +170,12 @@ impl SslAcceptorBuilder { } fn finish_setup(mut ctx: SslContextBuilder, - private_key: &Ref, - certificate: &Ref, + private_key: &PKeyRef, + certificate: &X509Ref, chain: I) -> Result where I: IntoIterator, - I::Item: AsRef> + I::Item: AsRef { try!(ctx.set_private_key(private_key)); try!(ctx.set_certificate(certificate)); @@ -278,13 +277,13 @@ mod verify { use std::str; use nid; - use x509::{X509StoreContext, X509, X509Name, GeneralName}; + use x509::{X509StoreContextRef, X509Ref, X509NameRef, GeneralName}; use stack::Stack; - use types::Ref; + use types::OpenSslTypeRef; pub fn verify_callback(domain: &str, preverify_ok: bool, - x509_ctx: &Ref) + x509_ctx: &X509StoreContextRef) -> bool { if !preverify_ok || x509_ctx.error_depth() != 0 { return preverify_ok; @@ -296,7 +295,7 @@ mod verify { } } - fn verify_hostname(domain: &str, cert: &Ref) -> bool { + fn verify_hostname(domain: &str, cert: &X509Ref) -> bool { match cert.subject_alt_names() { Some(names) => verify_subject_alt_names(domain, names), None => verify_subject_name(domain, &cert.subject_name()), @@ -329,7 +328,7 @@ mod verify { false } - fn verify_subject_name(domain: &str, subject_name: &Ref) -> bool { + fn verify_subject_name(domain: &str, subject_name: &X509NameRef) -> bool { if let Some(pattern) = subject_name.entries_by_nid(nid::COMMONNAME).next() { let pattern = match str::from_utf8(pattern.data().as_slice()) { Ok(pattern) => pattern, diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 4f5039de..85186e28 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -90,14 +90,15 @@ use std::marker::PhantomData; use ffi; use {init, cvt, cvt_p}; -use dh::Dh; -use ec_key::EcKey; -use x509::{X509StoreContext, X509FileType, X509, X509VerifyError}; +use dh::DhRef; +use ec_key::EcKeyRef; +use x509::{X509StoreContextRef, X509FileType, X509, X509Ref, X509VerifyError}; #[cfg(any(ossl102, ossl110))] -use verify::X509VerifyParam; -use pkey::PKey; +use verify::X509VerifyParamRef; +use pkey::PKeyRef; use error::ErrorStack; -use types::{OpenSslType, Ref}; +use types::{OpenSslType, OpenSslTypeRef}; +use util::Opaque; mod error; mod connector; @@ -262,7 +263,7 @@ fn get_new_ssl_idx() -> c_int { } extern "C" fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int - where F: Fn(bool, &Ref) -> bool + Any + 'static + Sync + Send + where F: Fn(bool, &X509StoreContextRef) -> bool + Any + 'static + Sync + Send { unsafe { let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx(); @@ -271,14 +272,14 @@ extern "C" fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_ let verify = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_verify_data_idx::()); let verify: &F = &*(verify as *mut F); - let ctx = Ref::from_ptr(x509_ctx); + let ctx = X509StoreContextRef::from_ptr(x509_ctx); verify(preverify_ok != 0, ctx) as c_int } } extern "C" fn ssl_raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int - where F: Fn(bool, &Ref) -> bool + Any + 'static + Sync + Send + where F: Fn(bool, &X509StoreContextRef) -> bool + Any + 'static + Sync + Send { unsafe { let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx(); @@ -286,20 +287,20 @@ extern "C" fn ssl_raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_ST let verify = ffi::SSL_get_ex_data(ssl as *const _, get_ssl_verify_data_idx::()); let verify: &F = &*(verify as *mut F); - let ctx = Ref::from_ptr(x509_ctx); + let ctx = X509StoreContextRef::from_ptr(x509_ctx); verify(preverify_ok != 0, ctx) as c_int } } extern "C" fn raw_sni(ssl: *mut ffi::SSL, al: *mut c_int, _arg: *mut c_void) -> c_int - where F: Fn(&mut Ref) -> Result<(), SniError> + Any + 'static + Sync + Send + where F: Fn(&mut SslRef) -> Result<(), SniError> + Any + 'static + Sync + Send { unsafe { let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_verify_data_idx::()); let callback: &F = &*(callback as *mut F); - let ssl = Ref::from_ptr_mut(ssl); + let ssl = SslRef::from_ptr_mut(ssl); match callback(ssl) { Ok(()) => ffi::SSL_TLSEXT_ERR_OK, @@ -463,7 +464,7 @@ impl SslContextBuilder { /// Configures the certificate verification method for new connections and /// registers a verification callback. pub fn set_verify_callback(&mut self, mode: SslVerifyMode, verify: F) - where F: Fn(bool, &Ref) -> bool + Any + 'static + Sync + Send + where F: Fn(bool, &X509StoreContextRef) -> bool + Any + 'static + Sync + Send { unsafe { let verify = Box::new(verify); @@ -479,7 +480,7 @@ impl SslContextBuilder { /// Obtain the server name with `servername` then set the corresponding context /// with `set_ssl_context` pub fn set_servername_callback(&mut self, callback: F) - where F: Fn(&mut Ref) -> Result<(), SniError> + Any + 'static + Sync + Send + where F: Fn(&mut SslRef) -> Result<(), SniError> + Any + 'static + Sync + Send { unsafe { let callback = Box::new(callback); @@ -512,11 +513,11 @@ impl SslContextBuilder { } } - pub fn set_tmp_dh(&mut self, dh: &Ref) -> Result<(), ErrorStack> { + pub fn set_tmp_dh(&mut self, dh: &DhRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::SSL_CTX_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as c_int).map(|_| ()) } } - pub fn set_tmp_ecdh(&mut self, key: &Ref) -> Result<(), ErrorStack> { + pub fn set_tmp_ecdh(&mut self, key: &EcKeyRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::SSL_CTX_set_tmp_ecdh(self.as_ptr(), key.as_ptr()) as c_int).map(|_| ()) } } @@ -584,7 +585,7 @@ impl SslContextBuilder { } /// Specifies the certificate - pub fn set_certificate(&mut self, cert: &Ref) -> Result<(), ErrorStack> { + pub fn set_certificate(&mut self, cert: &X509Ref) -> Result<(), ErrorStack> { unsafe { cvt(ffi::SSL_CTX_use_certificate(self.as_ptr(), cert.as_ptr())).map(|_| ()) } } @@ -613,7 +614,7 @@ impl SslContextBuilder { } /// Specifies the private key - pub fn set_private_key(&mut self, key: &Ref) -> Result<(), ErrorStack> { + pub fn set_private_key(&mut self, key: &PKeyRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::SSL_CTX_use_PrivateKey(self.as_ptr(), key.as_ptr())).map(|_| ()) } } @@ -733,7 +734,7 @@ impl SslContextBuilder { } } -type_!(SslContext, ffi::SSL_CTX, ffi::SSL_CTX_free); +type_!(SslContext, SslContextRef, ffi::SSL_CTX, ffi::SSL_CTX_free); unsafe impl Send for SslContext {} unsafe impl Sync for SslContext {} @@ -771,19 +772,22 @@ pub struct CipherBits { pub struct SslCipher(*mut ffi::SSL_CIPHER); -unsafe impl OpenSslType for SslCipher { +impl OpenSslType for SslCipher { type CType = ffi::SSL_CIPHER; + type Ref = SslCipherRef; unsafe fn from_ptr(ptr: *mut ffi::SSL_CIPHER) -> SslCipher { SslCipher(ptr) } - - fn as_ptr(&self) -> *mut ffi::SSL_CIPHER { - self.0 - } } -impl Ref { +pub struct SslCipherRef(Opaque); + +impl OpenSslTypeRef for SslCipherRef { + type CType = ffi::SSL_CIPHER; +} + +impl SslCipherRef { /// Returns the name of cipher. pub fn name(&self) -> &'static str { let name = unsafe { @@ -827,9 +831,9 @@ impl Ref { } } -type_!(Ssl, ffi::SSL, ffi::SSL_free); +type_!(Ssl, SslRef, ffi::SSL, ffi::SSL_free); -impl fmt::Debug for Ref { +impl fmt::Debug for SslRef { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let mut builder = fmt.debug_struct("Ssl"); builder.field("state", &self.state_string_long()); @@ -840,7 +844,7 @@ impl fmt::Debug for Ref { } } -impl Ref { +impl SslRef { fn get_raw_rbio(&self) -> *mut ffi::BIO { unsafe { ffi::SSL_get_rbio(self.as_ptr()) } } @@ -874,7 +878,7 @@ impl Ref { /// to the certificate chain. It should return `true` if the certificate /// chain is valid and `false` otherwise. pub fn set_verify_callback(&mut self, mode: SslVerifyMode, verify: F) - where F: Fn(bool, &Ref) -> bool + Any + 'static + Sync + Send + where F: Fn(bool, &X509StoreContextRef) -> bool + Any + 'static + Sync + Send { unsafe { let verify = Box::new(verify); @@ -885,14 +889,14 @@ impl Ref { } } - pub fn current_cipher(&self) -> Option<&Ref> { + pub fn current_cipher(&self) -> Option<&SslCipherRef> { unsafe { let ptr = ffi::SSL_get_current_cipher(self.as_ptr()); if ptr.is_null() { None } else { - Some(Ref::from_ptr(ptr as *mut _)) + Some(SslCipherRef::from_ptr(ptr as *mut _)) } } } @@ -1033,15 +1037,15 @@ impl Ref { } /// Changes the context corresponding to the current connection. - pub fn set_ssl_context(&mut self, ctx: &Ref) -> Result<(), ErrorStack> { + pub fn set_ssl_context(&mut self, ctx: &SslContextRef) -> Result<(), ErrorStack> { unsafe { cvt_p(ffi::SSL_set_SSL_CTX(self.as_ptr(), ctx.as_ptr())).map(|_| ()) } } /// Returns the context corresponding to the current connection - pub fn ssl_context(&self) -> &Ref { + pub fn ssl_context(&self) -> &SslContextRef { unsafe { let ssl_ctx = ffi::SSL_get_SSL_CTX(self.as_ptr()); - Ref::from_ptr(ssl_ctx) + SslContextRef::from_ptr(ssl_ctx) } } @@ -1049,13 +1053,13 @@ impl Ref { /// /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or 1.1.0. #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - pub fn param_mut(&mut self) -> &mut Ref { + pub fn param_mut(&mut self) -> &mut X509VerifyParamRef { self._param_mut() } #[cfg(any(ossl102, ossl110))] - fn _param_mut(&mut self) -> &mut Ref { - unsafe { Ref::from_ptr_mut(ffi::SSL_get0_param(self.as_ptr())) } + fn _param_mut(&mut self) -> &mut X509VerifyParamRef { + unsafe { X509VerifyParamRef::from_ptr_mut(ffi::SSL_get0_param(self.as_ptr())) } } /// Returns the result of X509 certificate verification. @@ -1165,7 +1169,7 @@ impl MidHandshakeSslStream { } /// Returns a shared reference to the `Ssl` of the stream. - pub fn ssl(&self) -> &Ref { + pub fn ssl(&self) -> &SslRef { self.stream.ssl() } @@ -1347,7 +1351,7 @@ impl SslStream { } /// Returns the OpenSSL `Ssl` object associated with this stream. - pub fn ssl(&self) -> &Ref { + pub fn ssl(&self) -> &SslRef { &self.ssl } } diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 2a27dff4..df02c778 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -171,7 +171,7 @@ macro_rules! run_test( use hash::MessageDigest; use x509::X509StoreContext; use serialize::hex::FromHex; - use types::Ref; + use types::OpenSslTypeRef; use super::Server; #[test] diff --git a/openssl/src/stack.rs b/openssl/src/stack.rs index 368b6e07..ad208377 100644 --- a/openssl/src/stack.rs +++ b/openssl/src/stack.rs @@ -2,10 +2,12 @@ use std::ops::{Deref, DerefMut, Index, IndexMut}; use std::iter; use std::borrow::Borrow; use std::convert::AsRef; +use std::marker::PhantomData; use libc::c_int; use ffi; -use types::{OpenSslType, Ref}; +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, @@ -55,45 +57,49 @@ impl Drop for Stack { } } -impl AsRef>> for Stack { - fn as_ref(&self) -> &Ref> { +impl AsRef> for Stack { + fn as_ref(&self) -> &StackRef { &*self } } -impl Borrow>> for Stack { - fn borrow(&self) -> &Ref> { +impl Borrow> for Stack { + fn borrow(&self) -> &StackRef { &*self } } -unsafe impl OpenSslType for Stack { +impl OpenSslType for Stack { type CType = T::StackType; + type Ref = StackRef; unsafe fn from_ptr(ptr: *mut T::StackType) -> Stack { Stack(ptr) } - - fn as_ptr(&self) -> *mut T::StackType { - self.0 - } } impl Deref for Stack { - type Target = Ref>; + type Target = StackRef; - fn deref(&self) -> &Ref> { - unsafe { Ref::from_ptr(self.0) } + fn deref(&self) -> &StackRef { + unsafe { StackRef::from_ptr(self.0) } } } impl DerefMut for Stack { - fn deref_mut(&mut self) -> &mut ::types::Ref> { - unsafe { Ref::from_ptr_mut(self.0) } + fn deref_mut(&mut self) -> &mut StackRef { + unsafe { StackRef::from_ptr_mut(self.0) } } } -impl Ref> { +pub struct StackRef(Opaque, PhantomData); + +impl OpenSslTypeRef for StackRef { + type CType = T::StackType; +} + + +impl StackRef { /// OpenSSL stack types are just a (kinda) typesafe wrapper around /// a `_STACK` object. We can therefore safely cast it and access /// the `_STACK` members without having to worry about the real @@ -141,25 +147,25 @@ impl Ref> { /// Returns a reference to the element at the given index in the /// stack or `None` if the index is out of bounds - pub fn get(&self, idx: usize) -> Option<&Ref> { + pub fn get(&self, idx: usize) -> Option<&T::Ref> { unsafe { if idx >= self.len() { return None; } - Some(Ref::from_ptr(self._get(idx))) + Some(T::Ref::from_ptr(self._get(idx))) } } /// Returns a mutable reference to the element at the given index in the /// stack or `None` if the index is out of bounds - pub fn get_mut(&mut self, idx: usize) -> Option<&mut Ref> { + pub fn get_mut(&mut self, idx: usize) -> Option<&mut T::Ref> { unsafe { if idx >= self.len() { return None; } - Some(Ref::from_ptr_mut(self._get(idx))) + Some(T::Ref::from_ptr_mut(self._get(idx))) } } @@ -168,22 +174,22 @@ impl Ref> { } } -impl Index for Ref> { - type Output = Ref; +impl Index for StackRef { + type Output = T::Ref; - fn index(&self, index: usize) -> &Ref { + fn index(&self, index: usize) -> &T::Ref { self.get(index).unwrap() } } -impl IndexMut for Ref> { - fn index_mut(&mut self, index: usize) -> &mut Ref { +impl IndexMut for StackRef { + fn index_mut(&mut self, index: usize) -> &mut T::Ref { self.get_mut(index).unwrap() } } -impl<'a, T: Stackable> iter::IntoIterator for &'a Ref> { - type Item = &'a Ref; +impl<'a, T: Stackable> iter::IntoIterator for &'a StackRef { + type Item = &'a T::Ref; type IntoIter = Iter<'a, T>; fn into_iter(self) -> Iter<'a, T> { @@ -191,8 +197,8 @@ impl<'a, T: Stackable> iter::IntoIterator for &'a Ref> { } } -impl<'a, T: Stackable> iter::IntoIterator for &'a mut Ref> { - type Item = &'a mut Ref; +impl<'a, T: Stackable> iter::IntoIterator for &'a mut StackRef { + type Item = &'a mut T::Ref; type IntoIter = IterMut<'a, T>; fn into_iter(self) -> IterMut<'a, T> { @@ -201,7 +207,7 @@ impl<'a, T: Stackable> iter::IntoIterator for &'a mut Ref> { } impl<'a, T: Stackable> iter::IntoIterator for &'a Stack { - type Item = &'a Ref; + type Item = &'a T::Ref; type IntoIter = Iter<'a, T>; fn into_iter(self) -> Iter<'a, T> { @@ -210,7 +216,7 @@ impl<'a, T: Stackable> iter::IntoIterator for &'a Stack { } impl<'a, T: Stackable> iter::IntoIterator for &'a mut Stack { - type Item = &'a mut Ref; + type Item = &'a mut T::Ref; type IntoIter = IterMut<'a, T>; fn into_iter(self) -> IterMut<'a, T> { @@ -221,14 +227,14 @@ impl<'a, T: Stackable> iter::IntoIterator for &'a mut Stack { /// An iterator over the stack's contents. pub struct Iter<'a, T: Stackable> where T: 'a { - stack: &'a Ref>, + stack: &'a StackRef, pos: usize, } impl<'a, T: Stackable> iter::Iterator for Iter<'a, T> { - type Item = &'a Ref; + type Item = &'a T::Ref; - fn next(&mut self) -> Option<&'a Ref> { + fn next(&mut self) -> Option<&'a T::Ref> { let n = self.stack.get(self.pos); if n.is_some() { @@ -250,14 +256,14 @@ impl<'a, T: Stackable> iter::ExactSizeIterator for Iter<'a, T> { /// A mutable iterator over the stack's contents. pub struct IterMut<'a, T: Stackable + 'a> { - stack: &'a mut Ref>, + stack: &'a mut StackRef, pos: usize, } impl<'a, T: Stackable> iter::Iterator for IterMut<'a, T> { - type Item = &'a mut Ref; + type Item = &'a mut T::Ref; - fn next(&mut self) -> Option<&'a mut Ref> { + fn next(&mut self) -> Option<&'a mut T::Ref> { if self.pos >= self.stack.len() { None } else { @@ -267,7 +273,7 @@ impl<'a, T: Stackable> iter::Iterator for IterMut<'a, T> { // the same object, so we have to use unsafe code for // mutable iterators. let n = unsafe { - Some(Ref::from_ptr_mut(self.stack._get(self.pos))) + Some(T::Ref::from_ptr_mut(self.stack._get(self.pos))) }; self.pos += 1; diff --git a/openssl/src/types.rs b/openssl/src/types.rs index 40831ee8..2fadfd42 100644 --- a/openssl/src/types.rs +++ b/openssl/src/types.rs @@ -1,39 +1,40 @@ //! Items used by other types. -use std::cell::UnsafeCell; -use std::marker::PhantomData; - /// A type implemented by wrappers over OpenSSL types. /// /// This should not be implemented by anything outside of this crate; new methods may be added at /// any time. -pub unsafe trait OpenSslType { +pub trait OpenSslType: Sized { /// The raw C type. type CType; + /// The type representing a reference to this type. + type Ref: OpenSslTypeRef; + /// Constructs an instance of this type from its raw type. unsafe fn from_ptr(ptr: *mut Self::CType) -> Self; - - /// Returns a pointer to its raw type. - fn as_ptr(&self) -> *mut Self::CType; } -/// A reference to an OpenSSL type. -pub struct Ref(UnsafeCell<()>, PhantomData); +/// A trait implemented by types which reference borrowed OpenSSL types. +/// +/// This should not be implemented by anything outside of this crate; new methods may be added at +/// any time. +pub trait OpenSslTypeRef: Sized { + /// The raw C type. + type CType; -impl Ref { - /// Constructs a shared reference to this type from its raw type. - pub unsafe fn from_ptr<'a>(ptr: *mut T::CType) -> &'a Ref { + /// Constructs a shared instance of this type from its raw type. + unsafe fn from_ptr<'a>(ptr: *mut Self::CType) -> &'a Self { &*(ptr as *mut _) } - /// Constructs a mutable reference to this type from its raw type. - pub unsafe fn from_ptr_mut<'a>(ptr: *mut T::CType) -> &'a mut Ref { + /// Constructs a mutable reference of this type from its raw type. + unsafe fn from_ptr_mut<'a>(ptr: *mut Self::CType) -> &'a mut Self { &mut *(ptr as *mut _) } - /// Returns a pointer to its raw type. - pub fn as_ptr(&self) -> *mut T::CType { + /// Returns a raw pointer to the wrapped value. + fn as_ptr(&self) -> *mut Self::CType { self as *const _ as *mut _ } } diff --git a/openssl/src/util.rs b/openssl/src/util.rs index 49f38c3d..302bd316 100644 --- a/openssl/src/util.rs +++ b/openssl/src/util.rs @@ -1,6 +1,6 @@ use libc::{c_int, c_char, c_void}; - use std::any::Any; +use std::cell::UnsafeCell; use std::panic::{self, AssertUnwindSafe}; use std::slice; @@ -60,3 +60,8 @@ pub unsafe extern "C" fn invoke_passwd_cb(buf: *mut c_char, } } } + +/// This is intended to be used as the inner type for `FooRef` types converted from raw C pointers. +/// It has an `UnsafeCell` internally to inform the compiler about aliasability and doesn't +/// implement `Copy`, so it can't be dereferenced. +pub struct Opaque(UnsafeCell<()>); diff --git a/openssl/src/verify.rs b/openssl/src/verify.rs index c067e08e..2f070fe5 100644 --- a/openssl/src/verify.rs +++ b/openssl/src/verify.rs @@ -3,7 +3,7 @@ use ffi; use cvt; use error::ErrorStack; -use types::Ref; +use types::OpenSslTypeRef; bitflags! { pub flags X509CheckFlags: c_uint { @@ -19,9 +19,9 @@ bitflags! { } } -type_!(X509VerifyParam, ffi::X509_VERIFY_PARAM, ffi::X509_VERIFY_PARAM_free); +type_!(X509VerifyParam, X509VerifyParamRef, ffi::X509_VERIFY_PARAM, ffi::X509_VERIFY_PARAM_free); -impl Ref { +impl X509VerifyParamRef { pub fn set_hostflags(&mut self, hostflags: X509CheckFlags) { unsafe { ffi::X509_VERIFY_PARAM_set_hostflags(self.as_ptr(), hostflags.bits); diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index bffb193c..c3ba9eae 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -11,16 +11,16 @@ use std::slice; use std::str; use {cvt, cvt_p}; -use asn1::{Asn1String, Asn1Time}; +use asn1::{Asn1StringRef, Asn1Time, Asn1TimeRef}; use bio::{MemBio, MemBioSlice}; use hash::MessageDigest; -use pkey::PKey; +use pkey::{PKey, PKeyRef}; use rand::rand_bytes; use error::ErrorStack; use ffi; use nid::Nid; -use types::{OpenSslType, Ref}; -use stack::{Stack, Stackable}; +use types::{OpenSslType, OpenSslTypeRef}; +use stack::{Stack, StackRef, Stackable}; #[cfg(ossl10x)] use ffi::{X509_set_notBefore, X509_set_notAfter, ASN1_STRING_data, X509_STORE_CTX_get_chain}; @@ -51,20 +51,20 @@ pub const X509_FILETYPE_PEM: X509FileType = X509FileType(ffi::X509_FILETYPE_PEM) pub const X509_FILETYPE_ASN1: X509FileType = X509FileType(ffi::X509_FILETYPE_ASN1); pub const X509_FILETYPE_DEFAULT: X509FileType = X509FileType(ffi::X509_FILETYPE_DEFAULT); -type_!(X509StoreContext, ffi::X509_STORE_CTX, ffi::X509_STORE_CTX_free); +type_!(X509StoreContext, X509StoreContextRef, ffi::X509_STORE_CTX, ffi::X509_STORE_CTX_free); -impl Ref { +impl X509StoreContextRef { pub fn error(&self) -> Option { unsafe { X509VerifyError::from_raw(ffi::X509_STORE_CTX_get_error(self.as_ptr()) as c_long) } } - pub fn current_cert(&self) -> Option<&Ref> { + pub fn current_cert(&self) -> Option<&X509Ref> { unsafe { let ptr = ffi::X509_STORE_CTX_get_current_cert(self.as_ptr()); if ptr.is_null() { None } else { - Some(Ref::from_ptr(ptr)) + Some(X509Ref::from_ptr(ptr)) } } } @@ -73,7 +73,7 @@ impl Ref { unsafe { ffi::X509_STORE_CTX_get_error_depth(self.as_ptr()) as u32 } } - pub fn chain(&self) -> Option<&Ref>> { + pub fn chain(&self) -> Option<&StackRef> { unsafe { let chain = X509_STORE_CTX_get_chain(self.as_ptr()); @@ -81,7 +81,7 @@ impl Ref { return None; } - Some(Ref::from_ptr(chain)) + Some(StackRef::from_ptr(chain)) } } } @@ -275,7 +275,7 @@ impl X509Generator { } /// Sets the certificate public-key, then self-sign and return it - pub fn sign(&self, p_key: &Ref) -> Result { + pub fn sign(&self, p_key: &PKeyRef) -> Result { ffi::init(); unsafe { @@ -327,7 +327,7 @@ impl X509Generator { } /// Obtain a certificate signing request (CSR) - pub fn request(&self, p_key: &Ref) -> Result { + pub fn request(&self, p_key: &PKeyRef) -> Result { let cert = match self.sign(p_key) { Ok(c) => c, Err(x) => return Err(x), @@ -352,13 +352,13 @@ impl X509Generator { } } -type_!(X509, ffi::X509, ffi::X509_free); +type_!(X509, X509Ref, ffi::X509, ffi::X509_free); -impl Ref { - pub fn subject_name(&self) -> &Ref { +impl X509Ref { + pub fn subject_name(&self) -> &X509NameRef { unsafe { let name = ffi::X509_get_subject_name(self.as_ptr()); - Ref::from_ptr(name) + X509NameRef::from_ptr(name) } } @@ -397,20 +397,20 @@ impl Ref { } /// Returns certificate Not After validity period. - pub fn not_after<'a>(&'a self) -> &'a Ref { + pub fn not_after<'a>(&'a self) -> &'a Asn1TimeRef { unsafe { let date = compat::X509_get_notAfter(self.as_ptr()); assert!(!date.is_null()); - Ref::from_ptr(date) + Asn1TimeRef::from_ptr(date) } } /// Returns certificate Not Before validity period. - pub fn not_before<'a>(&'a self) -> &'a Ref { + pub fn not_before<'a>(&'a self) -> &'a Asn1TimeRef { unsafe { let date = compat::X509_get_notBefore(self.as_ptr()); assert!(!date.is_null()); - Ref::from_ptr(date) + Asn1TimeRef::from_ptr(date) } } @@ -433,7 +433,7 @@ impl Ref { } } -impl ToOwned for Ref { +impl ToOwned for X509Ref { type Owned = X509; fn to_owned(&self) -> X509 { @@ -474,14 +474,14 @@ impl Clone for X509 { } } -impl AsRef> for X509 { - fn as_ref(&self) -> &Ref { +impl AsRef for X509 { + fn as_ref(&self) -> &X509Ref { &*self } } -impl Borrow> for X509 { - fn borrow(&self) -> &Ref { +impl Borrow for X509 { + fn borrow(&self) -> &X509Ref { &*self } } @@ -490,9 +490,9 @@ impl Stackable for X509 { type StackType = ffi::stack_st_X509; } -type_!(X509Name, ffi::X509_NAME, ffi::X509_NAME_free); +type_!(X509Name, X509NameRef, ffi::X509_NAME, ffi::X509_NAME_free); -impl Ref { +impl X509NameRef { pub fn entries_by_nid<'a>(&'a self, nid: Nid) -> X509NameEntries<'a> { X509NameEntries { name: self, @@ -503,15 +503,15 @@ impl Ref { } pub struct X509NameEntries<'a> { - name: &'a Ref, + name: &'a X509NameRef, nid: Nid, loc: c_int, } impl<'a> Iterator for X509NameEntries<'a> { - type Item = &'a Ref; + type Item = &'a X509NameEntryRef; - fn next(&mut self) -> Option<&'a Ref> { + fn next(&mut self) -> Option<&'a X509NameEntryRef> { unsafe { self.loc = ffi::X509_NAME_get_index_by_NID(self.name.as_ptr(), self.nid.as_raw(), @@ -524,25 +524,25 @@ impl<'a> Iterator for X509NameEntries<'a> { let entry = ffi::X509_NAME_get_entry(self.name.as_ptr(), self.loc); assert!(!entry.is_null()); - Some(Ref::from_ptr(entry)) + Some(X509NameEntryRef::from_ptr(entry)) } } } -type_!(X509NameEntry, ffi::X509_NAME_ENTRY, ffi::X509_NAME_ENTRY_free); +type_!(X509NameEntry, X509NameEntryRef, ffi::X509_NAME_ENTRY, ffi::X509_NAME_ENTRY_free); -impl Ref { - pub fn data(&self) -> &Ref { +impl X509NameEntryRef { + pub fn data(&self) -> &Asn1StringRef { unsafe { let data = ffi::X509_NAME_ENTRY_get_data(self.as_ptr()); - Ref::from_ptr(data) + Asn1StringRef::from_ptr(data) } } } -type_!(X509Req, ffi::X509_REQ, ffi::X509_REQ_free); +type_!(X509Req, X509ReqRef, ffi::X509_REQ, ffi::X509_REQ_free); -impl Ref { +impl X509ReqRef { /// Writes CSR as PEM pub fn to_pem(&self) -> Result, ErrorStack> { let mem_bio = try!(MemBio::new()); @@ -699,9 +699,9 @@ impl X509VerifyError { } } -type_!(GeneralName, ffi::GENERAL_NAME, ffi::GENERAL_NAME_free); +type_!(GeneralName, GeneralNameRef, ffi::GENERAL_NAME, ffi::GENERAL_NAME_free); -impl Ref { +impl GeneralNameRef { /// Returns the contents of this `GeneralName` if it is a `dNSName`. pub fn dnsname(&self) -> Option<&str> { unsafe { From 9198bcda3a7baf2877cb97db260f9f2147b994a6 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 4 Nov 2016 21:08:34 -0700 Subject: [PATCH 170/186] Improve buildscript logic --- openssl-sys/build.rs | 6 +++--- openssl/build.rs | 25 +++++++++++++------------ 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/openssl-sys/build.rs b/openssl-sys/build.rs index 5a009204..391e75b1 100644 --- a/openssl-sys/build.rs +++ b/openssl-sys/build.rs @@ -219,13 +219,13 @@ fn validate_headers(include_dirs: &[PathBuf], }; if version_text.contains("0x10001") { println!("cargo:rustc-cfg=ossl101"); - println!("cargo:is_101=1"); + println!("cargo:version=101"); } else if version_text.contains("0x10002") { println!("cargo:rustc-cfg=ossl102"); - println!("cargo:is_102=1"); + println!("cargo:version=102"); } else if version_text.contains("0x10100") { println!("cargo:rustc-cfg=ossl110"); - println!("cargo:is_110=1"); + println!("cargo:version=110"); } else { panic!(" diff --git a/openssl/build.rs b/openssl/build.rs index cd1dc3ec..41847b0f 100644 --- a/openssl/build.rs +++ b/openssl/build.rs @@ -1,18 +1,19 @@ use std::env; fn main() { - if env::var("DEP_OPENSSL_IS_110").is_ok() { - println!("cargo:rustc-cfg=ossl110"); - return; - } else if env::var("DEP_OPENSSL_IS_102").is_ok() { - println!("cargo:rustc-cfg=ossl102"); - println!("cargo:rustc-cfg=ossl10x"); - return; - } else if env::var("DEP_OPENSSL_IS_101").is_ok() { - println!("cargo:rustc-cfg=ossl101"); - println!("cargo:rustc-cfg=ossl10x"); - } else { - panic!("Unable to detect OpenSSL version"); + match env::var("DEP_OPENSSL_VERSION") { + Ok(ref v) if v == "101" => { + println!("cargo:rustc-cfg=ossl101"); + println!("cargo:rustc-cfg=ossl10x"); + } + Ok(ref v) if v == "102" => { + println!("cargo:rustc-cfg=ossl102"); + println!("cargo:rustc-cfg=ossl10x"); + } + Ok(ref v) if v == "110" => { + println!("cargo:rustc-cfg=ossl110"); + } + _ => panic!("Unable to detect OpenSSL version"), } if let Ok(vars) = env::var("DEP_OPENSSL_OSSLCONF") { From 91fd58b4c2e31c8114c060bc30a256a089206b3b Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 4 Nov 2016 21:10:49 -0700 Subject: [PATCH 171/186] More buildscript tweaks --- openssl-sys/build.rs | 2 +- openssl/build.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/openssl-sys/build.rs b/openssl-sys/build.rs index 391e75b1..c5968407 100644 --- a/openssl-sys/build.rs +++ b/openssl-sys/build.rs @@ -295,7 +295,7 @@ The build is now aborting due to this version mismatch. vars.push(var); } } - println!("cargo:osslconf={}", vars.join(",")); + println!("cargo:conf={}", vars.join(",")); } return version_text.to_string() diff --git a/openssl/build.rs b/openssl/build.rs index 41847b0f..7a0c60dc 100644 --- a/openssl/build.rs +++ b/openssl/build.rs @@ -16,7 +16,7 @@ fn main() { _ => panic!("Unable to detect OpenSSL version"), } - if let Ok(vars) = env::var("DEP_OPENSSL_OSSLCONF") { + if let Ok(vars) = env::var("DEP_OPENSSL_CONF") { for var in vars.split(",") { println!("cargo:rustc-cfg=osslconf=\"{}\"", var); } From fb9420fc91c750bb6f3e40ce13665339dcebe1be Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 4 Nov 2016 21:15:07 -0700 Subject: [PATCH 172/186] Always dump openssl confs --- openssl-sys/build.rs | 90 ++++++++++++++++++++++---------------------- 1 file changed, 44 insertions(+), 46 deletions(-) diff --git a/openssl-sys/build.rs b/openssl-sys/build.rs index c5968407..a435b192 100644 --- a/openssl-sys/build.rs +++ b/openssl-sys/build.rs @@ -247,56 +247,54 @@ The build is now aborting due to this version mismatch. // file of OpenSSL, `opensslconf.h`, and then dump out everything it defines // as our own #[cfg] directives. That way the `ossl10x.rs` bindings can // account for compile differences and such. - if version_text.contains("0x1000") { - let mut conf_header = String::new(); - let mut include = include_dirs.iter() - .map(|p| p.join("openssl/opensslconf.h")) - .filter(|p| p.exists()); - let mut f = match include.next() { - Some(f) => File::open(f).unwrap(), - None => { - // It's been seen that on linux the include dir printed out by - // `pkg-config` doesn't actually have opensslconf.h. Instead - // it's in an architecture-specific include directory. - // - // Try to detect that case to see if it exists. - let mut libdirs = libdirs.iter().map(|p| { - p.iter() - .map(|p| if p == "lib" {"include".as_ref()} else {p}) - .collect::() - }).map(|p| { - p.join("openssl/opensslconf.h") - }).filter(|p| p.exists()); - match libdirs.next() { - Some(f) => File::open(f).unwrap(), - None => { - panic!("failed to open header file at - `openssl/opensslconf.h` to learn about \ - OpenSSL's version number, looked \ - inside:\n\n{:#?}\n\n", - include_dirs); - } + let mut conf_header = String::new(); + let mut include = include_dirs.iter() + .map(|p| p.join("openssl/opensslconf.h")) + .filter(|p| p.exists()); + let mut f = match include.next() { + Some(f) => File::open(f).unwrap(), + None => { + // It's been seen that on linux the include dir printed out by + // `pkg-config` doesn't actually have opensslconf.h. Instead + // it's in an architecture-specific include directory. + // + // Try to detect that case to see if it exists. + let mut libdirs = libdirs.iter().map(|p| { + p.iter() + .map(|p| if p == "lib" {"include".as_ref()} else {p}) + .collect::() + }).map(|p| { + p.join("openssl/opensslconf.h") + }).filter(|p| p.exists()); + match libdirs.next() { + Some(f) => File::open(f).unwrap(), + None => { + panic!("failed to open header file at + `openssl/opensslconf.h` to learn about \ + OpenSSL's version number, looked \ + inside:\n\n{:#?}\n\n", + include_dirs); } } - }; - f.read_to_string(&mut conf_header).unwrap(); - - // Look for `#define OPENSSL_FOO`, print out everything as our own - // #[cfg] flag. - let mut vars = vec![]; - for line in conf_header.lines() { - let i = match line.find("define ") { - Some(i) => i, - None => continue, - }; - let var = line[i + "define ".len()..].trim(); - if var.starts_with("OPENSSL") && !var.contains(" ") { - println!("cargo:rustc-cfg=osslconf=\"{}\"", var); - vars.push(var); - } } - println!("cargo:conf={}", vars.join(",")); + }; + f.read_to_string(&mut conf_header).unwrap(); + + // Look for `#define OPENSSL_FOO`, print out everything as our own + // #[cfg] flag. + let mut vars = vec![]; + for line in conf_header.lines() { + let i = match line.find("define ") { + Some(i) => i, + None => continue, + }; + let var = line[i + "define ".len()..].trim(); + if var.starts_with("OPENSSL") && !var.contains(" ") { + println!("cargo:rustc-cfg=osslconf=\"{}\"", var); + vars.push(var); + } } + println!("cargo:conf={}", vars.join(",")); return version_text.to_string() } From 3421ee126c3ef3a85b2415b32e5b9a0109c8f762 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 4 Nov 2016 22:08:08 -0700 Subject: [PATCH 173/186] Fix systest --- systest/build.rs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/systest/build.rs b/systest/build.rs index 38d43995..81907a57 100644 --- a/systest/build.rs +++ b/systest/build.rs @@ -22,16 +22,8 @@ fn main() { } } - if env::var("DEP_OPENSSL_IS_101").is_ok() { - cfg.cfg("ossl101", None); - } - if env::var("DEP_OPENSSL_IS_102").is_ok() { - cfg.cfg("ossl102", None); - } - if env::var("DEP_OPENSSL_IS_110").is_ok() { - cfg.cfg("ossl110", None); - } - if let Ok(vars) = env::var("DEP_OPENSSL_OSSLCONF") { + cfg.cfg(&format!("ossl{}", env::var("DEP_OPENSSL_VERSION").unwrap()), None); + if let Ok(vars) = env::var("DEP_OPENSSL_CONF") { for var in vars.split(",") { cfg.cfg("osslconf", Some(var)); } From 99b41a005041018484284d3c85bf2474f90d7d8a Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 5 Nov 2016 10:13:21 -0700 Subject: [PATCH 174/186] Rename accessors --- openssl/src/ssl/connector.rs | 8 ++++---- openssl/src/ssl/tests/mod.rs | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index 52d26ef5..4bebecd8 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -66,12 +66,12 @@ impl SslConnectorBuilder { } /// Returns a shared reference to the inner `SslContextBuilder`. - pub fn context(&self) -> &SslContextBuilder { + pub fn builder(&self) -> &SslContextBuilder { &self.0 } /// Returns a mutable reference to the inner `SslContextBuilder`. - pub fn context_mut(&mut self) -> &mut SslContextBuilder { + pub fn builder_mut(&mut self) -> &mut SslContextBuilder { &mut self.0 } @@ -187,12 +187,12 @@ impl SslAcceptorBuilder { } /// Returns a shared reference to the inner `SslContextBuilder`. - pub fn context(&self) -> &SslContextBuilder { + pub fn builder(&self) -> &SslContextBuilder { &self.0 } /// Returns a mutable reference to the inner `SslContextBuilder`. - pub fn context_mut(&mut self) -> &mut SslContextBuilder { + pub fn builder_mut(&mut self) -> &mut SslContextBuilder { &mut self.0 } diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index df02c778..a84f6b25 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -1107,7 +1107,7 @@ fn connector_client_server_mozilla_intermediate() { }); let mut connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap(); - connector.context_mut().set_ca_file("test/root-ca.pem").unwrap(); + connector.builder_mut().set_ca_file("test/root-ca.pem").unwrap(); let connector = connector.build(); let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); @@ -1139,7 +1139,7 @@ fn connector_client_server_mozilla_modern() { }); let mut connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap(); - connector.context_mut().set_ca_file("test/root-ca.pem").unwrap(); + connector.builder_mut().set_ca_file("test/root-ca.pem").unwrap(); let connector = connector.build(); let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); From 71a114707f9ed23bc43c9a5d41c8e42c9a4472ff Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 5 Nov 2016 10:38:12 -0700 Subject: [PATCH 175/186] Remove unused dependency --- openssl/Cargo.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/openssl/Cargo.toml b/openssl/Cargo.toml index 4891d79b..44a5bad1 100644 --- a/openssl/Cargo.toml +++ b/openssl/Cargo.toml @@ -23,7 +23,6 @@ libc = "0.2" openssl-sys = { version = "0.7.17", path = "../openssl-sys" } [dev-dependencies] -net2 = "0.2.16" rustc-serialize = "0.3" tempdir = "0.3" winapi = "0.2" From f15c817c2d1fad288fe0f88d4e3995df4aa4a477 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 5 Nov 2016 10:54:17 -0700 Subject: [PATCH 176/186] Rustfmt --- openssl/src/asn1.rs | 4 +--- openssl/src/bn.rs | 16 +++------------- openssl/src/ssl/connector.rs | 7 ++----- openssl/src/stack.rs | 17 +++++++---------- openssl/src/x509/mod.rs | 5 ++--- 5 files changed, 15 insertions(+), 34 deletions(-) diff --git a/openssl/src/asn1.rs b/openssl/src/asn1.rs index 46c28740..c0a23591 100644 --- a/openssl/src/asn1.rs +++ b/openssl/src/asn1.rs @@ -59,9 +59,7 @@ impl Asn1StringRef { } pub fn len(&self) -> usize { - unsafe { - ffi::ASN1_STRING_length(self.as_ptr()) as usize - } + unsafe { ffi::ASN1_STRING_length(self.as_ptr()) as usize } } } diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs index a3235c1f..fe3645d0 100644 --- a/openssl/src/bn.rs +++ b/openssl/src/bn.rs @@ -365,22 +365,12 @@ impl BigNumRef { /// * `bits`: Length of the number in bits. /// * `msb`: The desired properties of the number. /// * `odd`: If `true`, the generated number will be odd. - pub fn rand(&mut self, - bits: i32, - msb: MsbOption, - odd: bool) - -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_rand(self.as_ptr(), bits.into(), msb.0, odd as c_int)).map(|_| ()) - } + pub fn rand(&mut self, bits: i32, msb: MsbOption, odd: bool) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_rand(self.as_ptr(), bits.into(), msb.0, odd as c_int)).map(|_| ()) } } /// The cryptographically weak counterpart to `rand`. - pub fn pseudo_rand(&mut self, - bits: i32, - msb: MsbOption, - odd: bool) - -> Result<(), ErrorStack> { + pub fn pseudo_rand(&mut self, bits: i32, msb: MsbOption, odd: bool) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_pseudo_rand(self.as_ptr(), bits.into(), msb.0, odd as c_int)).map(|_| ()) } diff --git a/openssl/src/ssl/connector.rs b/openssl/src/ssl/connector.rs index 4bebecd8..0d92529d 100644 --- a/openssl/src/ssl/connector.rs +++ b/openssl/src/ssl/connector.rs @@ -215,9 +215,7 @@ fn get_dh() -> Result { use types::OpenSslType; // manually call into ffi to avoid forcing the features - unsafe { - cvt_p(ffi::DH_get_2048_256()).map(|p| Dh::from_ptr(p)) - } + unsafe { cvt_p(ffi::DH_get_2048_256()).map(|p| Dh::from_ptr(p)) } } #[cfg(ossl101)] @@ -302,8 +300,7 @@ mod verify { } } - fn verify_subject_alt_names(domain: &str, - names: Stack) -> bool { + fn verify_subject_alt_names(domain: &str, names: Stack) -> bool { let ip = domain.parse(); for name in &names { diff --git a/openssl/src/stack.rs b/openssl/src/stack.rs index ad208377..318791b8 100644 --- a/openssl/src/stack.rs +++ b/openssl/src/stack.rs @@ -10,8 +10,8 @@ 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}; +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}; #[cfg(ossl110)] use ffi::{OPENSSL_sk_pop, OPENSSL_sk_free, OPENSSL_sk_num, OPENSSL_sk_value}; @@ -226,7 +226,8 @@ impl<'a, T: Stackable> iter::IntoIterator for &'a mut Stack { /// An iterator over the stack's contents. pub struct Iter<'a, T: Stackable> - where T: 'a { + where T: 'a +{ stack: &'a StackRef, pos: usize, } @@ -251,8 +252,7 @@ impl<'a, T: Stackable> iter::Iterator for Iter<'a, T> { } } -impl<'a, T: Stackable> iter::ExactSizeIterator for Iter<'a, T> { -} +impl<'a, T: Stackable> iter::ExactSizeIterator for Iter<'a, T> {} /// A mutable iterator over the stack's contents. pub struct IterMut<'a, T: Stackable + 'a> { @@ -272,9 +272,7 @@ impl<'a, T: Stackable> iter::Iterator for IterMut<'a, T> { // guarantee that we won't return several references to // the same object, so we have to use unsafe code for // mutable iterators. - let n = unsafe { - Some(T::Ref::from_ptr_mut(self.stack._get(self.pos))) - }; + let n = unsafe { Some(T::Ref::from_ptr_mut(self.stack._get(self.pos))) }; self.pos += 1; @@ -289,5 +287,4 @@ impl<'a, T: Stackable> iter::Iterator for IterMut<'a, T> { } } -impl<'a, T: Stackable> iter::ExactSizeIterator for IterMut<'a, T> { -} +impl<'a, T: Stackable> iter::ExactSizeIterator for IterMut<'a, T> {} diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index c3ba9eae..ec17cbe2 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -513,9 +513,8 @@ impl<'a> Iterator for X509NameEntries<'a> { fn next(&mut self) -> Option<&'a X509NameEntryRef> { unsafe { - self.loc = ffi::X509_NAME_get_index_by_NID(self.name.as_ptr(), - self.nid.as_raw(), - self.loc); + self.loc = + ffi::X509_NAME_get_index_by_NID(self.name.as_ptr(), self.nid.as_raw(), self.loc); if self.loc == -1 { return None; From 398ab2fbc4f8c254633541a9c0e46b688be14668 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 5 Nov 2016 13:01:54 -0700 Subject: [PATCH 177/186] Add a consuming iterator for Stacks --- openssl/src/pkcs12.rs | 36 ++--------------- openssl/src/stack.rs | 91 +++++++++++++++++++++++++++++++++---------- 2 files changed, 73 insertions(+), 54 deletions(-) diff --git a/openssl/src/pkcs12.rs b/openssl/src/pkcs12.rs index 1318f7f7..6d7e8ba7 100644 --- a/openssl/src/pkcs12.rs +++ b/openssl/src/pkcs12.rs @@ -11,6 +11,7 @@ use pkey::PKey; use error::ErrorStack; use x509::X509; use types::OpenSslType; +use stack::Stack; /// A PKCS #12 archive. pub struct Pkcs12(*mut ffi::PKCS12); @@ -48,19 +49,12 @@ impl Pkcs12 { let pkey = PKey::from_ptr(pkey); let cert = X509::from_ptr(cert); - let chain = chain as *mut _; - - let mut chain_out = vec![]; - for i in 0..compat::OPENSSL_sk_num(chain) { - let x509 = compat::OPENSSL_sk_value(chain, i); - chain_out.push(X509::from_ptr(x509 as *mut _)); - } - compat::OPENSSL_sk_free(chain as *mut _); + let chain = Stack::from_ptr(chain).into_iter().collect(); Ok(ParsedPkcs12 { pkey: pkey, cert: cert, - chain: chain_out, + chain: chain, }) } } @@ -72,30 +66,6 @@ pub struct ParsedPkcs12 { pub chain: Vec, } -#[cfg(ossl110)] -mod compat { - pub use ffi::OPENSSL_sk_free; - pub use ffi::OPENSSL_sk_num; - pub use ffi::OPENSSL_sk_value; -} - -#[cfg(ossl10x)] -#[allow(bad_style)] -mod compat { - use libc::{c_int, c_void}; - use ffi; - - pub use ffi::sk_free as OPENSSL_sk_free; - - pub unsafe fn OPENSSL_sk_num(stack: *mut ffi::_STACK) -> c_int { - (*stack).num - } - - pub unsafe fn OPENSSL_sk_value(stack: *const ffi::_STACK, idx: c_int) -> *mut c_void { - *(*stack).data.offset(idx as isize) as *mut c_void - } -} - #[cfg(test)] mod test { use hash::MessageDigest; diff --git a/openssl/src/stack.rs b/openssl/src/stack.rs index 318791b8..8359f785 100644 --- a/openssl/src/stack.rs +++ b/openssl/src/stack.rs @@ -4,16 +4,16 @@ use std::borrow::Borrow; use std::convert::AsRef; use std::marker::PhantomData; use libc::c_int; +use std::mem; -use ffi; 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}; + sk_value as OPENSSL_sk_value, _STACK as OPENSSL_STACK}; #[cfg(ossl110)] -use ffi::{OPENSSL_sk_pop, OPENSSL_sk_free, OPENSSL_sk_num, OPENSSL_sk_value}; +use ffi::{OPENSSL_sk_pop, OPENSSL_sk_free, OPENSSL_sk_num, OPENSSL_sk_value, OPENSSL_STACK}; /// Trait implemented by types which can be placed in a stack. /// @@ -57,6 +57,20 @@ impl Drop for Stack { } } +impl iter::IntoIterator for Stack { + type IntoIter = IntoIter; + type Item = T; + + fn into_iter(self) -> IntoIter { + let it = IntoIter { + stack: self.0, + idx: 0, + }; + mem::forget(self); + it + } +} + impl AsRef> for Stack { fn as_ref(&self) -> &StackRef { &*self @@ -92,31 +106,66 @@ impl DerefMut for Stack { } } +pub struct IntoIter { + stack: *mut T::StackType, + idx: c_int, +} + +impl IntoIter { + fn stack_len(&self) -> c_int { + unsafe { OPENSSL_sk_num(self.stack as *mut _) } + } + + unsafe fn get(&mut self, i: c_int) -> T { + let ptr = OPENSSL_sk_value(self.stack as *mut _, i); + T::from_ptr(ptr as *mut _) + } +} + +impl Drop for IntoIter { + fn drop(&mut self) { + unsafe { + for i in self.idx..self.stack_len() { + self.get(i); + } + + OPENSSL_sk_free(self.stack as *mut _); + } + } +} + +impl Iterator for IntoIter { + type Item = T; + + fn next(&mut self) -> Option { + unsafe { + if self.idx == self.stack_len() { + None + } else { + let idx = self.idx; + self.idx += 1; + let v = self.get(idx); + Some(v) + } + } + } + + fn size_hint(&self) -> (usize, Option) { + let size = (self.stack_len() - self.idx) as usize; + (size, Some(size)) + } +} + +impl ExactSizeIterator for IntoIter {} + pub struct StackRef(Opaque, PhantomData); impl OpenSslTypeRef for StackRef { type CType = T::StackType; } - impl StackRef { - /// OpenSSL stack types are just a (kinda) typesafe wrapper around - /// a `_STACK` object. We can therefore safely cast it and access - /// the `_STACK` members without having to worry about the real - /// layout of `T::StackType`. - /// - /// If that sounds unsafe then keep in mind that's exactly how the - /// OpenSSL 1.1.0 new C stack code works. - #[cfg(ossl10x)] - fn as_stack(&self) -> *mut ffi::_STACK { - self.as_ptr() as *mut _ - } - - /// OpenSSL 1.1.0 replaced the stack macros with a functions and - /// only exposes an opaque OPENSSL_STACK struct - /// publicly. - #[cfg(ossl110)] - fn as_stack(&self) -> *mut ffi::OPENSSL_STACK { + fn as_stack(&self) -> *mut OPENSSL_STACK { self.as_ptr() as *mut _ } From ac36d542fd6de8e174cf4d70e38144da47412027 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 5 Nov 2016 13:10:50 -0700 Subject: [PATCH 178/186] Simplify destructor a bit --- openssl/src/stack.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/openssl/src/stack.rs b/openssl/src/stack.rs index 8359f785..c56c8230 100644 --- a/openssl/src/stack.rs +++ b/openssl/src/stack.rs @@ -125,10 +125,7 @@ impl IntoIter { impl Drop for IntoIter { fn drop(&mut self) { unsafe { - for i in self.idx..self.stack_len() { - self.get(i); - } - + while let Some(_) = self.next() {} OPENSSL_sk_free(self.stack as *mut _); } } From 52feaae59f91c4de368a7942519488aa3beed6f9 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 5 Nov 2016 13:15:14 -0700 Subject: [PATCH 179/186] More cleanup --- openssl/src/stack.rs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/openssl/src/stack.rs b/openssl/src/stack.rs index c56c8230..50694919 100644 --- a/openssl/src/stack.rs +++ b/openssl/src/stack.rs @@ -115,11 +115,6 @@ impl IntoIter { fn stack_len(&self) -> c_int { unsafe { OPENSSL_sk_num(self.stack as *mut _) } } - - unsafe fn get(&mut self, i: c_int) -> T { - let ptr = OPENSSL_sk_value(self.stack as *mut _, i); - T::from_ptr(ptr as *mut _) - } } impl Drop for IntoIter { @@ -139,10 +134,9 @@ impl Iterator for IntoIter { if self.idx == self.stack_len() { None } else { - let idx = self.idx; + let ptr = OPENSSL_sk_value(self.stack as *mut _, self.idx); self.idx += 1; - let v = self.get(idx); - Some(v) + Some(T::from_ptr(ptr as *mut _)) } } } From ed69d6b0370bd033e78accf6d7a397de25b4ca05 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 5 Nov 2016 13:40:53 -0700 Subject: [PATCH 180/186] Add Stack::pop --- openssl/src/stack.rs | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/openssl/src/stack.rs b/openssl/src/stack.rs index 50694919..dae42ca8 100644 --- a/openssl/src/stack.rs +++ b/openssl/src/stack.rs @@ -40,18 +40,7 @@ impl Stack { impl Drop for Stack { fn drop(&mut self) { unsafe { - loop { - let ptr = OPENSSL_sk_pop(self.as_stack()); - - if ptr.is_null() { - break; - } - - // Build the owned version of the object just to run - // its `drop` implementation and delete the item. - T::from_ptr(ptr as *mut _); - } - + while let Some(_) = self.pop() {} OPENSSL_sk_free(self.0 as *mut _); } } @@ -209,6 +198,18 @@ impl StackRef { } } + /// Removes the last element from the stack and returns it. + pub fn pop(&mut self) -> Option { + unsafe { + let ptr = OPENSSL_sk_pop(self.as_stack()); + if ptr.is_null() { + None + } else { + Some(T::from_ptr(ptr as *mut _)) + } + } + } + unsafe fn _get(&self, idx: usize) -> *mut T::CType { OPENSSL_sk_value(self.as_stack(), idx as c_int) as *mut _ } From 803725891331daf1839ea88e3035ae151e59cc2e Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 5 Nov 2016 13:57:05 -0700 Subject: [PATCH 181/186] Return a Stack in Pkcs12 --- openssl/src/pkcs12.rs | 4 ++-- openssl/src/x509/mod.rs | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/openssl/src/pkcs12.rs b/openssl/src/pkcs12.rs index 6d7e8ba7..8c884e7f 100644 --- a/openssl/src/pkcs12.rs +++ b/openssl/src/pkcs12.rs @@ -49,7 +49,7 @@ impl Pkcs12 { let pkey = PKey::from_ptr(pkey); let cert = X509::from_ptr(cert); - let chain = Stack::from_ptr(chain).into_iter().collect(); + let chain = Stack::from_ptr(chain); Ok(ParsedPkcs12 { pkey: pkey, @@ -63,7 +63,7 @@ impl Pkcs12 { pub struct ParsedPkcs12 { pub pkey: PKey, pub cert: X509, - pub chain: Vec, + pub chain: Stack, } #[cfg(test)] diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index ec17cbe2..eb517f80 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -480,6 +480,12 @@ impl AsRef for X509 { } } +impl AsRef for X509Ref { + fn as_ref(&self) -> &X509Ref { + self + } +} + impl Borrow for X509 { fn borrow(&self) -> &X509Ref { &*self From 4e2ffe5b9b6045dbc87f2c8606818fe00c8c4c42 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 5 Nov 2016 17:35:31 -0700 Subject: [PATCH 182/186] Re-adjust BigNum API --- openssl/src/bn.rs | 432 +++++++++++++++++++++++++--------------------- 1 file changed, 236 insertions(+), 196 deletions(-) diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs index fe3645d0..d52be884 100644 --- a/openssl/src/bn.rs +++ b/openssl/src/bn.rs @@ -32,169 +32,6 @@ impl BigNumContext { pub fn new() -> Result { unsafe { cvt_p(ffi::BN_CTX_new()).map(BigNumContext) } } - - /// Places the result of `a * b` in `r`. - pub fn mul(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - b: &BigNumRef) - -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_mul(r.as_ptr(), a.as_ptr(), b.as_ptr(), self.as_ptr())).map(|_| ()) } - } - - /// Places the result of `a / b` in `dv` and `a mod b` in `rem`. - pub fn div(&mut self, - dv: Option<&mut BigNumRef>, - rem: Option<&mut BigNumRef>, - a: &BigNumRef, - b: &BigNumRef) - -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_div(dv.map(|b| b.as_ptr()).unwrap_or(ptr::null_mut()), - rem.map(|b| b.as_ptr()).unwrap_or(ptr::null_mut()), - a.as_ptr(), - b.as_ptr(), - self.as_ptr())) - .map(|_| ()) - } - } - - /// Places the result of `a²` in `r`. - pub fn sqr(&mut self, r: &mut BigNumRef, a: &BigNumRef) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_sqr(r.as_ptr(), a.as_ptr(), self.as_ptr())).map(|_| ()) } - } - - /// Places the result of `a mod m` in `r`. - pub fn nnmod(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - m: &BigNumRef) - -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_nnmod(r.as_ptr(), a.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) } - } - - /// Places the result of `(a + b) mod m` in `r`. - pub fn mod_add(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - b: &BigNumRef, - m: &BigNumRef) - -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_mod_add(r.as_ptr(), a.as_ptr(), b.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) - } - } - - /// Places the result of `(a - b) mod m` in `r`. - pub fn mod_sub(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - b: &BigNumRef, - m: &BigNumRef) - -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_mod_sub(r.as_ptr(), a.as_ptr(), b.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) - } - } - - /// Places the result of `(a * b) mod m` in `r`. - pub fn mod_mul(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - b: &BigNumRef, - m: &BigNumRef) - -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_mod_mul(r.as_ptr(), a.as_ptr(), b.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) - } - } - - /// Places the result of `a² mod m` in `r`. - pub fn mod_sqr(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - m: &BigNumRef) - -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_mod_sqr(r.as_ptr(), a.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) } - } - - /// Places the result of `a^p` in `r`. - pub fn exp(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - p: &BigNumRef) - -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_exp(r.as_ptr(), a.as_ptr(), p.as_ptr(), self.0)).map(|_| ()) } - } - - /// Places the result of `a^p mod m` in `r`. - pub fn mod_exp(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - p: &BigNumRef, - m: &BigNumRef) - -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_mod_exp(r.as_ptr(), a.as_ptr(), p.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) - } - } - - /// Places the inverse of `a` modulo `n` in `r`. - pub fn mod_inverse(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - n: &BigNumRef) - -> Result<(), ErrorStack> { - unsafe { - cvt_p(ffi::BN_mod_inverse(r.as_ptr(), a.as_ptr(), n.as_ptr(), self.as_ptr())) - .map(|_| ()) - } - } - - /// Places the greatest common denominator of `a` and `b` in `r`. - pub fn gcd(&mut self, - r: &mut BigNumRef, - a: &BigNumRef, - b: &BigNumRef) - -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_gcd(r.as_ptr(), a.as_ptr(), b.as_ptr(), self.as_ptr())).map(|_| ()) } - } - - /// Checks whether `p` is prime. - /// - /// Performs a Miller-Rabin probabilistic primality test with `checks` iterations. - /// - /// Returns `true` if `p` is prime with an error probability of less than `0.25 ^ checks`. - pub fn is_prime(&mut self, p: &BigNumRef, checks: i32) -> Result { - unsafe { - cvt_n(ffi::BN_is_prime_ex(p.as_ptr(), checks.into(), self.as_ptr(), ptr::null_mut())) - .map(|r| r != 0) - } - } - - /// Checks whether `p` is prime with optional trial division. - /// - /// If `do_trial_division` is `true`, first performs trial division by a number of small primes. - /// Then, like `is_prime`, performs a Miller-Rabin probabilistic primality test with `checks` - /// iterations. - /// - /// # Return Value - /// - /// Returns `true` if `p` is prime with an error probability of less than `0.25 ^ checks`. - pub fn is_prime_fasttest(&mut self, - p: &BigNumRef, - checks: i32, - do_trial_division: bool) - -> Result { - unsafe { - cvt_n(ffi::BN_is_prime_fasttest_ex(p.as_ptr(), - checks.into(), - self.as_ptr(), - do_trial_division as c_int, - ptr::null_mut())) - .map(|r| r != 0) - } - } } impl BigNumRef { @@ -246,12 +83,12 @@ impl BigNumRef { /// Places a cryptographically-secure pseudo-random number nonnegative /// number less than `self` in `rnd`. - pub fn rand_in_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { + pub fn rand_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_rand_range(self.as_ptr(), rnd.as_ptr())).map(|_| ()) } } /// The cryptographically weak counterpart to `rand_in_range`. - pub fn pseudo_rand_in_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { + pub fn pseudo_rand_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { unsafe { cvt(ffi::BN_pseudo_rand_range(self.as_ptr(), rnd.as_ptr())).map(|_| ()) } } @@ -281,34 +118,34 @@ impl BigNumRef { unsafe { cvt(ffi::BN_mask_bits(self.as_ptr(), n.into())).map(|_| ()) } } - /// Places `self << 1` in `r`. - pub fn lshift1(&self, r: &mut BigNumRef) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_lshift1(r.as_ptr(), self.as_ptr())).map(|_| ()) } + /// Places `a << 1` in `self`. + pub fn lshift1(&mut self, a: &BigNumRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_lshift1(self.as_ptr(), a.as_ptr())).map(|_| ()) } } - /// Places `self >> 1` in `r`. - pub fn rshift1(&self, r: &mut BigNumRef) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_rshift1(r.as_ptr(), self.as_ptr())).map(|_| ()) } + /// Places `a >> 1` in `self`. + pub fn rshift1(&mut self, a: &BigNumRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_rshift1(self.as_ptr(), a.as_ptr())).map(|_| ()) } } - /// Places `self + b` in `r`. - pub fn add(&self, r: &mut BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_add(r.as_ptr(), self.as_ptr(), b.as_ptr())).map(|_| ()) } + /// Places `a + b` in `self`. + pub fn checked_add(&mut self, a: &BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_add(self.as_ptr(), a.as_ptr(), b.as_ptr())).map(|_| ()) } } - /// Places `self - b` in `r`. - pub fn sub(&self, r: &mut BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_sub(r.as_ptr(), self.as_ptr(), b.as_ptr())).map(|_| ()) } + /// Places `a - b` in `self`. + pub fn checked_sub(&mut self, a: &BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_sub(self.as_ptr(), a.as_ptr(), b.as_ptr())).map(|_| ()) } } - /// Places `self << n` in `r`. - pub fn lshift(&self, r: &mut BigNumRef, b: i32) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_lshift(r.as_ptr(), self.as_ptr(), b.into())).map(|_| ()) } + /// Places `a << n` in `self`. + pub fn lshift(&mut self, a: &BigNumRef, n: i32) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_lshift(self.as_ptr(), a.as_ptr(), n.into())).map(|_| ()) } } - /// Places `self >> n` in `r`. - pub fn rshift(&self, r: &mut BigNumRef, n: i32) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_rshift(r.as_ptr(), self.as_ptr(), n.into())).map(|_| ()) } + /// Places `a >> n` in `self`. + pub fn rshift(&mut self, a: &BigNumRef, n: i32) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_rshift(self.as_ptr(), a.as_ptr(), n.into())).map(|_| ()) } } pub fn to_owned(&self) -> Result { @@ -401,6 +238,209 @@ impl BigNumRef { } } + /// Places the result of `a * b` in `self`. + pub fn checked_mul(&mut self, + a: &BigNumRef, + b: &BigNumRef, + ctx: &mut BigNumContextRef) + -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_mul(self.as_ptr(), a.as_ptr(), b.as_ptr(), ctx.as_ptr())).map(|_| ()) } + } + + /// Places the result of `a / b` in `self`. + pub fn checked_div(&mut self, + a: &BigNumRef, + b: &BigNumRef, + ctx: &mut BigNumContextRef) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_div(self.as_ptr(), + ptr::null_mut(), + a.as_ptr(), + b.as_ptr(), + ctx.as_ptr())) + .map(|_| ()) + } + } + + /// Places the result of `a % b` in `self`. + pub fn checked_rem(&mut self, + a: &BigNumRef, + b: &BigNumRef, + ctx: &mut BigNumContextRef) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_div(ptr::null_mut(), + self.as_ptr(), + a.as_ptr(), + b.as_ptr(), + ctx.as_ptr())) + .map(|_| ()) + } + } + + /// Places the result of `a / b` in `self` and `a % b` in `rem`. + pub fn div_rem(&mut self, + rem: &mut BigNumRef, + a: &BigNumRef, + b: &BigNumRef, + ctx: &mut BigNumContextRef) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_div(self.as_ptr(), + rem.as_ptr(), + a.as_ptr(), + b.as_ptr(), + ctx.as_ptr())) + .map(|_| ()) + } + } + + /// Places the result of `a²` in `self`. + pub fn sqr(&mut self, a: &BigNumRef, ctx: &mut BigNumContextRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_sqr(self.as_ptr(), a.as_ptr(), ctx.as_ptr())).map(|_| ()) } + } + + /// Places the result of `a mod m` in `self`. + pub fn nnmod(&mut self, + a: &BigNumRef, + m: &BigNumRef, + ctx: &mut BigNumContextRef) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_nnmod(self.as_ptr(), a.as_ptr(), m.as_ptr(), ctx.as_ptr())).map(|_| ()) + } + } + + /// Places the result of `(a + b) mod m` in `self`. + pub fn mod_add(&mut self, + a: &BigNumRef, + b: &BigNumRef, + m: &BigNumRef, + ctx: &mut BigNumContextRef) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mod_add(self.as_ptr(), a.as_ptr(), b.as_ptr(), m.as_ptr(), ctx.as_ptr())) + .map(|_| ()) + } + } + + /// Places the result of `(a - b) mod m` in `self`. + pub fn mod_sub(&mut self, + a: &BigNumRef, + b: &BigNumRef, + m: &BigNumRef, + ctx: &mut BigNumContextRef) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mod_sub(self.as_ptr(), a.as_ptr(), b.as_ptr(), m.as_ptr(), ctx.as_ptr())) + .map(|_| ()) + } + } + + /// Places the result of `(a * b) mod m` in `self`. + pub fn mod_mul(&mut self, + a: &BigNumRef, + b: &BigNumRef, + m: &BigNumRef, + ctx: &mut BigNumContextRef) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mod_mul(self.as_ptr(), a.as_ptr(), b.as_ptr(), m.as_ptr(), ctx.as_ptr())) + .map(|_| ()) + } + } + + /// Places the result of `a² mod m` in `self`. + pub fn mod_sqr(&mut self, + a: &BigNumRef, + m: &BigNumRef, + ctx: &mut BigNumContextRef) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mod_sqr(self.as_ptr(), a.as_ptr(), m.as_ptr(), ctx.as_ptr())).map(|_| ()) + } + } + + /// Places the result of `a^p` in `self`. + pub fn exp(&mut self, + a: &BigNumRef, + p: &BigNumRef, + ctx: &mut BigNumContextRef) + -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_exp(self.as_ptr(), a.as_ptr(), p.as_ptr(), ctx.as_ptr())).map(|_| ()) } + } + + /// Places the result of `a^p mod m` in `self`. + pub fn mod_exp(&mut self, + a: &BigNumRef, + p: &BigNumRef, + m: &BigNumRef, + ctx: &mut BigNumContextRef) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mod_exp(self.as_ptr(), a.as_ptr(), p.as_ptr(), m.as_ptr(), ctx.as_ptr())) + .map(|_| ()) + } + } + + /// Places the inverse of `a` modulo `n` in `self`. + pub fn mod_inverse(&mut self, + a: &BigNumRef, + n: &BigNumRef, + ctx: &mut BigNumContextRef) + -> Result<(), ErrorStack> { + unsafe { + cvt_p(ffi::BN_mod_inverse(self.as_ptr(), a.as_ptr(), n.as_ptr(), ctx.as_ptr())) + .map(|_| ()) + } + } + + /// Places the greatest common denominator of `a` and `b` in `self`. + pub fn gcd(&mut self, + a: &BigNumRef, + b: &BigNumRef, + ctx: &mut BigNumContextRef) + -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_gcd(self.as_ptr(), a.as_ptr(), b.as_ptr(), ctx.as_ptr())).map(|_| ()) } + } + + /// Checks whether `self` is prime. + /// + /// Performs a Miller-Rabin probabilistic primality test with `checks` iterations. + /// + /// Returns `true` if `self` is prime with an error probability of less than `0.25 ^ checks`. + pub fn is_prime(&self, checks: i32, ctx: &mut BigNumContextRef) -> Result { + unsafe { + cvt_n(ffi::BN_is_prime_ex(self.as_ptr(), checks.into(), ctx.as_ptr(), ptr::null_mut())) + .map(|r| r != 0) + } + } + + /// Checks whether `self` is prime with optional trial division. + /// + /// If `do_trial_division` is `true`, first performs trial division by a number of small primes. + /// Then, like `is_prime`, performs a Miller-Rabin probabilistic primality test with `checks` + /// iterations. + /// + /// # Return Value + /// + /// Returns `true` if `self` is prime with an error probability of less than `0.25 ^ checks`. + pub fn is_prime_fasttest(&self, + checks: i32, + ctx: &mut BigNumContextRef, + do_trial_division: bool) + -> Result { + unsafe { + cvt_n(ffi::BN_is_prime_fasttest_ex(self.as_ptr(), + checks.into(), + ctx.as_ptr(), + do_trial_division as c_int, + ptr::null_mut())) + .map(|r| r != 0) + } + } + /// Returns a big-endian byte vector representation of the absolute value of `self`. /// /// `self` can be recreated by using `new_from_slice`. @@ -649,7 +689,7 @@ impl<'a, 'b> Add<&'b BigNumRef> for &'a BigNumRef { fn add(self, oth: &BigNumRef) -> BigNum { let mut r = BigNum::new().unwrap(); - self.add(&mut r, oth).unwrap(); + r.checked_add(self, oth).unwrap(); r } } @@ -661,7 +701,7 @@ impl<'a, 'b> Sub<&'b BigNumRef> for &'a BigNumRef { fn sub(self, oth: &BigNumRef) -> BigNum { let mut r = BigNum::new().unwrap(); - self.sub(&mut r, oth).unwrap(); + r.checked_sub(self, oth).unwrap(); r } } @@ -674,7 +714,7 @@ impl<'a, 'b> Mul<&'b BigNumRef> for &'a BigNumRef { fn mul(self, oth: &BigNumRef) -> BigNum { let mut ctx = BigNumContext::new().unwrap(); let mut r = BigNum::new().unwrap(); - ctx.mul(&mut r, self, oth).unwrap(); + r.checked_mul(self, oth, &mut ctx).unwrap(); r } } @@ -686,9 +726,9 @@ impl<'a, 'b> Div<&'b BigNumRef> for &'a BigNumRef { fn div(self, oth: &'b BigNumRef) -> BigNum { let mut ctx = BigNumContext::new().unwrap(); - let mut dv = BigNum::new().unwrap(); - ctx.div(Some(&mut dv), None, self, oth).unwrap(); - dv + let mut r = BigNum::new().unwrap(); + r.checked_div(self, oth, &mut ctx).unwrap(); + r } } @@ -699,9 +739,9 @@ impl<'a, 'b> Rem<&'b BigNumRef> for &'a BigNumRef { fn rem(self, oth: &'b BigNumRef) -> BigNum { let mut ctx = BigNumContext::new().unwrap(); - let mut rem = BigNum::new().unwrap(); - ctx.div(None, Some(&mut rem), self, oth).unwrap(); - rem + let mut r = BigNum::new().unwrap(); + r.checked_rem(self, oth, &mut ctx).unwrap(); + r } } @@ -712,7 +752,7 @@ impl<'a> Shl for &'a BigNumRef { fn shl(self, n: i32) -> BigNum { let mut r = BigNum::new().unwrap(); - self.lshift(&mut r, n).unwrap(); + r.lshift(self, n).unwrap(); r } } @@ -730,7 +770,7 @@ impl<'a> Shr for &'a BigNumRef { fn shr(self, n: i32) -> BigNum { let mut r = BigNum::new().unwrap(); - self.rshift(&mut r, n).unwrap(); + r.rshift(self, n).unwrap(); r } } @@ -797,7 +837,7 @@ mod tests { p.generate_prime(128, true, None, Some(&a)).unwrap(); let mut ctx = BigNumContext::new().unwrap(); - assert!(ctx.is_prime(&p, 100).unwrap()); - assert!(ctx.is_prime_fasttest(&p, 100, true).unwrap()); + assert!(p.is_prime(100, &mut ctx).unwrap()); + assert!(p.is_prime_fasttest(100, &mut ctx, true).unwrap()); } } From 96a5ccfc6b69a6038ee2217551e041ab8275ab4c Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 5 Nov 2016 18:46:34 -0700 Subject: [PATCH 183/186] Implement Pkcs12 via type_! --- openssl/src/pkcs12.rs | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/openssl/src/pkcs12.rs b/openssl/src/pkcs12.rs index 8c884e7f..1ef0bf3f 100644 --- a/openssl/src/pkcs12.rs +++ b/openssl/src/pkcs12.rs @@ -10,19 +10,10 @@ use {cvt, cvt_p}; use pkey::PKey; use error::ErrorStack; use x509::X509; -use types::OpenSslType; +use types::{OpenSslType, OpenSslTypeRef}; use stack::Stack; -/// A PKCS #12 archive. -pub struct Pkcs12(*mut ffi::PKCS12); - -impl Drop for Pkcs12 { - fn drop(&mut self) { - unsafe { - ffi::PKCS12_free(self.0); - } - } -} +type_!(Pkcs12, Pkcs12Ref, ffi::PKCS12, ffi::PKCS12_free); impl Pkcs12 { /// Deserializes a `Pkcs12` structure from DER-encoded data. @@ -35,7 +26,9 @@ impl Pkcs12 { Ok(Pkcs12(p12)) } } +} +impl Pkcs12Ref { /// Extracts the contents of the `Pkcs12`. pub fn parse(&self, pass: &str) -> Result { unsafe { @@ -45,7 +38,11 @@ impl Pkcs12 { let mut cert = ptr::null_mut(); let mut chain = ptr::null_mut(); - try!(cvt(ffi::PKCS12_parse(self.0, pass.as_ptr(), &mut pkey, &mut cert, &mut chain))); + try!(cvt(ffi::PKCS12_parse(self.as_ptr(), + pass.as_ptr(), + &mut pkey, + &mut cert, + &mut chain))); let pkey = PKey::from_ptr(pkey); let cert = X509::from_ptr(cert); From 8ad1e5565b530832a2cf45f3994393c9a77236f0 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 5 Nov 2016 18:49:09 -0700 Subject: [PATCH 184/186] Remove set_rsa PKey is reference counted so allowing mutation is unsound --- openssl/src/pkey.rs | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/openssl/src/pkey.rs b/openssl/src/pkey.rs index a1b90a86..a1ebd695 100644 --- a/openssl/src/pkey.rs +++ b/openssl/src/pkey.rs @@ -6,7 +6,7 @@ use ffi; use {cvt, cvt_p}; use bio::{MemBio, MemBioSlice}; use dsa::Dsa; -use rsa::{Rsa, RsaRef}; +use rsa::Rsa; use error::ErrorStack; use util::{CallbackState, invoke_passwd_cb}; use types::{OpenSslType, OpenSslTypeRef}; @@ -146,16 +146,6 @@ impl PKey { Ok(PKey::from_ptr(evp)) } } - - /// Assign an RSA key to this pkey. - pub fn set_rsa(&mut self, rsa: &RsaRef) -> Result<(), ErrorStack> { - unsafe { - // this needs to be a reference as the set1_RSA ups the reference count - let rsa_ptr = rsa.as_ptr(); - try!(cvt(ffi::EVP_PKEY_set1_RSA(self.0, rsa_ptr))); - Ok(()) - } - } } #[cfg(test)] From 79e2004eefcb129a03f1f6b8db34af07ed212dd8 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 5 Nov 2016 19:28:17 -0700 Subject: [PATCH 185/186] Fixes --- openssl/src/ssl/mod.rs | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index 85186e28..9a477993 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -1,6 +1,6 @@ //! SSL/TLS support. //! -//! The `SslConnector` and `SslAcceptor` should be used in most cases - they handle +//! `SslConnector` and `SslAcceptor` should be used in most cases - they handle //! configuration of the OpenSSL primitives for you. //! //! # Examples @@ -70,7 +70,9 @@ //! } //! } //! ``` +use ffi; use libc::{c_int, c_void, c_long, c_ulong}; +use libc::{c_uchar, c_uint}; use std::any::Any; use std::any::TypeId; use std::cmp; @@ -79,15 +81,14 @@ use std::ffi::{CStr, CString}; use std::fmt; use std::io; use std::io::prelude::*; +use std::marker::PhantomData; use std::mem; +use std::ops::{Deref, DerefMut}; use std::path::Path; use std::ptr; +use std::slice; use std::str; use std::sync::Mutex; -use libc::{c_uchar, c_uint}; -use std::slice; -use std::marker::PhantomData; -use ffi; use {init, cvt, cvt_p}; use dh::DhRef; @@ -781,6 +782,20 @@ impl OpenSslType for SslCipher { } } +impl Deref for SslCipher { + type Target = SslCipherRef; + + fn deref(&self) -> &SslCipherRef { + unsafe { SslCipherRef::from_ptr(self.0) } + } +} + +impl DerefMut for SslCipher { + fn deref_mut(&mut self) -> &mut SslCipherRef { + unsafe { SslCipherRef::from_ptr_mut(self.0) } + } +} + pub struct SslCipherRef(Opaque); impl OpenSslTypeRef for SslCipherRef { @@ -789,7 +804,7 @@ impl OpenSslTypeRef for SslCipherRef { impl SslCipherRef { /// Returns the name of cipher. - pub fn name(&self) -> &'static str { + pub fn name(&self) -> &str { let name = unsafe { let ptr = ffi::SSL_CIPHER_get_name(self.as_ptr()); CStr::from_ptr(ptr as *const _) @@ -799,7 +814,7 @@ impl SslCipherRef { } /// Returns the SSL/TLS protocol version that first defined the cipher. - pub fn version(&self) -> &'static str { + pub fn version(&self) -> &str { let version = unsafe { let ptr = ffi::SSL_CIPHER_get_version(self.as_ptr()); CStr::from_ptr(ptr as *const _) From 72ac2a01054392f4fde77d48b84865123a9a61f7 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 5 Nov 2016 20:05:50 -0700 Subject: [PATCH 186/186] Release v0.9.0 --- README.md | 2 +- openssl-sys/Cargo.toml | 4 ++-- openssl-sys/src/lib.rs | 2 +- openssl/Cargo.toml | 6 +++--- openssl/src/lib.rs | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index cb154412..3f17a571 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![Build Status](https://travis-ci.org/sfackler/rust-openssl.svg?branch=master)](https://travis-ci.org/sfackler/rust-openssl) -[Documentation](https://sfackler.github.io/rust-openssl/doc/v0.8.3/openssl). +[Documentation](https://sfackler.github.io/rust-openssl/doc/v0.9.0/openssl). ## Warning diff --git a/openssl-sys/Cargo.toml b/openssl-sys/Cargo.toml index d44dcfc1..11c20a1c 100644 --- a/openssl-sys/Cargo.toml +++ b/openssl-sys/Cargo.toml @@ -1,12 +1,12 @@ [package] name = "openssl-sys" -version = "0.7.17" +version = "0.9.0" authors = ["Alex Crichton ", "Steven Fackler "] license = "MIT" description = "FFI bindings to OpenSSL" repository = "https://github.com/sfackler/rust-openssl" -documentation = "https://sfackler.github.io/rust-openssl/doc/v0.7.17/openssl_sys" +documentation = "https://sfackler.github.io/rust-openssl/doc/v0.9.0/openssl_sys" links = "openssl" build = "build.rs" diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 5266b5bc..4ffd1f64 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1,6 +1,6 @@ #![allow(non_camel_case_types, non_upper_case_globals, non_snake_case)] #![allow(dead_code, overflowing_literals)] -#![doc(html_root_url="https://sfackler.github.io/rust-openssl/doc/v0.7.17")] +#![doc(html_root_url="https://sfackler.github.io/rust-openssl/doc/v0.9.0")] extern crate libc; diff --git a/openssl/Cargo.toml b/openssl/Cargo.toml index 44a5bad1..1417bea7 100644 --- a/openssl/Cargo.toml +++ b/openssl/Cargo.toml @@ -1,11 +1,11 @@ [package] name = "openssl" -version = "0.8.3" +version = "0.9.0" authors = ["Steven Fackler "] license = "Apache-2.0" description = "OpenSSL bindings" repository = "https://github.com/sfackler/rust-openssl" -documentation = "https://sfackler.github.io/rust-openssl/doc/v0.8.3/openssl" +documentation = "https://sfackler.github.io/rust-openssl/doc/v0.9.0/openssl" readme = "../README.md" keywords = ["crypto", "tls", "ssl", "dtls"] build = "build.rs" @@ -20,7 +20,7 @@ v110 = [] bitflags = "0.7" lazy_static = "0.2" libc = "0.2" -openssl-sys = { version = "0.7.17", path = "../openssl-sys" } +openssl-sys = { version = "0.9", path = "../openssl-sys" } [dev-dependencies] rustc-serialize = "0.3" diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index 183bf495..a9d937ba 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -1,4 +1,4 @@ -#![doc(html_root_url="https://sfackler.github.io/rust-openssl/doc/v0.8.3")] +#![doc(html_root_url="https://sfackler.github.io/rust-openssl/doc/v0.9.0")] #[macro_use] extern crate bitflags;