This commit is contained in:
Steven Fackler 2016-05-16 23:03:00 -07:00
parent 2077449bc8
commit 1b0757409d
10 changed files with 201 additions and 185 deletions

View File

@ -387,8 +387,7 @@ mod tests {
let tests: [(Vec<u8>, Vec<u8>); 6] = let tests: [(Vec<u8>, Vec<u8>); 6] =
[(repeat(0xb_u8).take(20).collect(), b"Hi There".to_vec()), [(repeat(0xb_u8).take(20).collect(), b"Hi There".to_vec()),
(b"Jefe".to_vec(), b"what do ya want for nothing?".to_vec()), (b"Jefe".to_vec(), b"what do ya want for nothing?".to_vec()),
(repeat(0xaa_u8).take(20).collect(), (repeat(0xaa_u8).take(20).collect(), repeat(0xdd_u8).take(50).collect()),
repeat(0xdd_u8).take(50).collect()),
("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(), ("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(),
repeat(0xcd_u8).take(50).collect()), repeat(0xcd_u8).take(50).collect()),
(repeat(0xaa_u8).take(131).collect(), (repeat(0xaa_u8).take(131).collect(),

View File

@ -114,7 +114,7 @@ impl PKey {
/// Reads an RSA private key from PEM, takes ownership of handle /// Reads an RSA private key from PEM, takes ownership of handle
pub fn private_rsa_key_from_pem<R>(reader: &mut R) -> Result<PKey, SslError> pub fn private_rsa_key_from_pem<R>(reader: &mut R) -> Result<PKey, SslError>
where R: Read where R: Read
{ {
let rsa = try!(RSA::private_key_from_pem(reader)); let rsa = try!(RSA::private_key_from_pem(reader));
unsafe { unsafe {
@ -130,7 +130,7 @@ impl PKey {
/// Reads an RSA public key from PEM, takes ownership of handle /// Reads an RSA public key from PEM, takes ownership of handle
pub fn public_rsa_key_from_pem<R>(reader: &mut R) -> Result<PKey, SslError> pub fn public_rsa_key_from_pem<R>(reader: &mut R) -> Result<PKey, SslError>
where R: Read where R: Read
{ {
let rsa = try!(RSA::public_key_from_pem(reader)); let rsa = try!(RSA::public_key_from_pem(reader));
unsafe { unsafe {
@ -600,16 +600,15 @@ impl Drop for PKey {
impl Clone for PKey { impl Clone for PKey {
fn clone(&self) -> Self { fn clone(&self) -> Self {
let mut pkey = PKey::from_handle(unsafe { ffi::EVP_PKEY_new() }, self.parts); let mut pkey = PKey::from_handle(unsafe { ffi::EVP_PKEY_new() }, self.parts);
// copy by encoding to DER and back // copy by encoding to DER and back
match self.parts { match self.parts {
Parts::Public => { Parts::Public => {
pkey.load_pub(&self.save_pub()[..]); pkey.load_pub(&self.save_pub()[..]);
}, }
Parts::Both => { Parts::Both => {
pkey.load_priv(&self.save_priv()[..]); pkey.load_priv(&self.save_priv()[..]);
}, }
Parts::Neither => { Parts::Neither => {}
},
} }
pkey pkey
} }
@ -684,8 +683,8 @@ mod tests {
fn test_private_rsa_key_from_pem() { fn test_private_rsa_key_from_pem() {
let key_path = Path::new("test/key.pem"); let key_path = Path::new("test/key.pem");
let mut file = File::open(&key_path) let mut file = File::open(&key_path)
.ok() .ok()
.expect("Failed to open `test/key.pem`"); .expect("Failed to open `test/key.pem`");
super::PKey::private_rsa_key_from_pem(&mut file).unwrap(); super::PKey::private_rsa_key_from_pem(&mut file).unwrap();
} }
@ -694,8 +693,8 @@ mod tests {
fn test_public_rsa_key_from_pem() { fn test_public_rsa_key_from_pem() {
let key_path = Path::new("test/key.pem.pub"); let key_path = Path::new("test/key.pem.pub");
let mut file = File::open(&key_path) let mut file = File::open(&key_path)
.ok() .ok()
.expect("Failed to open `test/key.pem.pub`"); .expect("Failed to open `test/key.pem.pub`");
super::PKey::public_rsa_key_from_pem(&mut file).unwrap(); super::PKey::public_rsa_key_from_pem(&mut file).unwrap();
} }

View File

@ -31,8 +31,16 @@ impl RSA {
Ok(RSA(rsa)) Ok(RSA(rsa))
} }
} }
pub fn from_private_components(n: BigNum, e: BigNum, d: BigNum, p: BigNum, q: BigNum, dp: BigNum, dq: BigNum, qi: BigNum) -> Result<RSA, SslError> { pub fn from_private_components(n: BigNum,
e: BigNum,
d: BigNum,
p: BigNum,
q: BigNum,
dp: BigNum,
dq: BigNum,
qi: BigNum)
-> Result<RSA, SslError> {
unsafe { unsafe {
let rsa = try_ssl_null!(ffi::RSA_new()); let rsa = try_ssl_null!(ffi::RSA_new());
(*rsa).n = n.into_raw(); (*rsa).n = n.into_raw();
@ -54,7 +62,7 @@ impl RSA {
/// Reads an RSA private key from PEM formatted data. /// Reads an RSA private key from PEM formatted data.
pub fn private_key_from_pem<R>(reader: &mut R) -> Result<RSA, SslError> pub fn private_key_from_pem<R>(reader: &mut R) -> Result<RSA, SslError>
where R: Read where R: Read
{ {
let mut mem_bio = try!(MemBio::new()); let mut mem_bio = try!(MemBio::new());
try!(io::copy(reader, &mut mem_bio).map_err(StreamError)); try!(io::copy(reader, &mut mem_bio).map_err(StreamError));
@ -67,29 +75,35 @@ impl RSA {
Ok(RSA(rsa)) Ok(RSA(rsa))
} }
} }
/// Writes an RSA private key as unencrypted PEM formatted data /// Writes an RSA private key as unencrypted PEM formatted data
pub fn private_key_to_pem<W>(&self, writer: &mut W) -> Result<(), SslError> pub fn private_key_to_pem<W>(&self, writer: &mut W) -> Result<(), SslError>
where W: Write where W: Write
{ {
let mut mem_bio = try!(MemBio::new()); let mut mem_bio = try!(MemBio::new());
let result = unsafe { let result = unsafe {
ffi::PEM_write_bio_RSAPrivateKey(mem_bio.get_handle(), self.0, ptr::null(), ptr::null_mut(), 0, None, ptr::null_mut()) ffi::PEM_write_bio_RSAPrivateKey(mem_bio.get_handle(),
}; self.0,
ptr::null(),
if result == 1 { ptr::null_mut(),
try!(io::copy(&mut mem_bio, writer).map_err(StreamError)); 0,
None,
Ok(()) ptr::null_mut())
} else { };
Err(SslError::OpenSslErrors(vec![]))
} if result == 1 {
try!(io::copy(&mut mem_bio, writer).map_err(StreamError));
Ok(())
} else {
Err(SslError::OpenSslErrors(vec![]))
}
} }
/// Reads an RSA public key from PEM formatted data. /// Reads an RSA public key from PEM formatted data.
pub fn public_key_from_pem<R>(reader: &mut R) -> Result<RSA, SslError> pub fn public_key_from_pem<R>(reader: &mut R) -> Result<RSA, SslError>
where R: Read where R: Read
{ {
let mut mem_bio = try!(MemBio::new()); let mut mem_bio = try!(MemBio::new());
try!(io::copy(reader, &mut mem_bio).map_err(StreamError)); try!(io::copy(reader, &mut mem_bio).map_err(StreamError));
@ -102,45 +116,46 @@ impl RSA {
Ok(RSA(rsa)) Ok(RSA(rsa))
} }
} }
/// Writes an RSA public key as PEM formatted data /// Writes an RSA public key as PEM formatted data
pub fn public_key_to_pem<W>(&self, writer: &mut W) -> Result<(), SslError> pub fn public_key_to_pem<W>(&self, writer: &mut W) -> Result<(), SslError>
where W: Write where W: Write
{ {
let mut mem_bio = try!(MemBio::new()); let mut mem_bio = try!(MemBio::new());
let result = unsafe { let result = unsafe { ffi::PEM_write_bio_RSA_PUBKEY(mem_bio.get_handle(), self.0) };
ffi::PEM_write_bio_RSA_PUBKEY(mem_bio.get_handle(), self.0)
}; if result == 1 {
try!(io::copy(&mut mem_bio, writer).map_err(StreamError));
if result == 1 {
try!(io::copy(&mut mem_bio, writer).map_err(StreamError)); Ok(())
Ok(())
} else {
Err(SslError::OpenSslErrors(vec![]))
}
}
pub fn size(&self) -> Result<u32, SslError> {
if self.has_n() {
unsafe {
Ok(ffi::RSA_size(self.0) as u32)
}
} else { } else {
Err(SslError::OpenSslErrors(vec![])) Err(SslError::OpenSslErrors(vec![]))
} }
} }
pub fn size(&self) -> Result<u32, SslError> {
if self.has_n() {
unsafe { Ok(ffi::RSA_size(self.0) as u32) }
} else {
Err(SslError::OpenSslErrors(vec![]))
}
}
pub fn sign(&self, hash: hash::Type, message: &[u8]) -> Result<Vec<u8>, SslError> { pub fn sign(&self, hash: hash::Type, message: &[u8]) -> Result<Vec<u8>, SslError> {
let k_len = try!(self.size()); let k_len = try!(self.size());
let mut sig = vec![0;k_len as usize]; let mut sig = vec![0;k_len as usize];
let mut sig_len = k_len; let mut sig_len = k_len;
unsafe { unsafe {
let result = 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); let result = 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); assert!(sig_len == k_len);
if result == 1 { if result == 1 {
Ok(sig) Ok(sig)
} else { } else {
@ -148,14 +163,19 @@ impl RSA {
} }
} }
} }
pub fn verify(&self, hash: hash::Type, message: &[u8], sig: &[u8]) -> Result<bool, SslError> { pub fn verify(&self, hash: hash::Type, message: &[u8], sig: &[u8]) -> Result<bool, SslError> {
unsafe { unsafe {
let result = 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); let result = 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(result == 1) Ok(result == 1)
} }
} }
pub fn as_ptr(&self) -> *mut ffi::RSA { pub fn as_ptr(&self) -> *mut ffi::RSA {
self.0 self.0
@ -163,45 +183,31 @@ impl RSA {
// The following getters are unsafe, since BigNum::new_from_ffi fails upon null pointers // The following getters are unsafe, since BigNum::new_from_ffi fails upon null pointers
pub fn n(&self) -> Result<BigNum, SslError> { pub fn n(&self) -> Result<BigNum, SslError> {
unsafe { unsafe { BigNum::new_from_ffi((*self.0).n) }
BigNum::new_from_ffi((*self.0).n)
}
} }
pub fn has_n(&self) -> bool { pub fn has_n(&self) -> bool {
unsafe { unsafe { !(*self.0).n.is_null() }
!(*self.0).n.is_null()
}
} }
pub fn d(&self) -> Result<BigNum, SslError> { pub fn d(&self) -> Result<BigNum, SslError> {
unsafe { unsafe { BigNum::new_from_ffi((*self.0).d) }
BigNum::new_from_ffi((*self.0).d)
}
} }
pub fn e(&self) -> Result<BigNum, SslError> { pub fn e(&self) -> Result<BigNum, SslError> {
unsafe { unsafe { BigNum::new_from_ffi((*self.0).e) }
BigNum::new_from_ffi((*self.0).e)
}
} }
pub fn has_e(&self) -> bool { pub fn has_e(&self) -> bool {
unsafe { unsafe { !(*self.0).e.is_null() }
!(*self.0).e.is_null()
}
} }
pub fn p(&self) -> Result<BigNum, SslError> { pub fn p(&self) -> Result<BigNum, SslError> {
unsafe { unsafe { BigNum::new_from_ffi((*self.0).p) }
BigNum::new_from_ffi((*self.0).p)
}
} }
pub fn q(&self) -> Result<BigNum, SslError> { pub fn q(&self) -> Result<BigNum, SslError> {
unsafe { unsafe { BigNum::new_from_ffi((*self.0).q) }
BigNum::new_from_ffi((*self.0).q)
}
} }
} }
@ -217,64 +223,58 @@ mod test {
use std::io::Write; use std::io::Write;
use super::*; use super::*;
use crypto::hash::*; use crypto::hash::*;
fn signing_input_rs256() -> Vec<u8> { fn signing_input_rs256() -> Vec<u8> {
vec![101, 121, 74, 104, 98, 71, 99, 105, 79, 105, 74, 83, 85, 122, 73, vec![101, 121, 74, 104, 98, 71, 99, 105, 79, 105, 74, 83, 85, 122, 73, 49, 78, 105, 74, 57,
49, 78, 105, 74, 57, 46, 101, 121, 74, 112, 99, 51, 77, 105, 79, 105, 46, 101, 121, 74, 112, 99, 51, 77, 105, 79, 105, 74, 113, 98, 50, 85, 105, 76, 65, 48,
74, 113, 98, 50, 85, 105, 76, 65, 48, 75, 73, 67, 74, 108, 101, 72, 75, 73, 67, 74, 108, 101, 72, 65, 105, 79, 106, 69, 122, 77, 68, 65, 52, 77, 84, 107,
65, 105, 79, 106, 69, 122, 77, 68, 65, 52, 77, 84, 107, 122, 79, 68, 122, 79, 68, 65, 115, 68, 81, 111, 103, 73, 109, 104, 48, 100, 72, 65, 54, 76, 121,
65, 115, 68, 81, 111, 103, 73, 109, 104, 48, 100, 72, 65, 54, 76, 57, 108, 101, 71, 70, 116, 99, 71, 120, 108, 76, 109, 78, 118, 98, 83, 57, 112, 99,
121, 57, 108, 101, 71, 70, 116, 99, 71, 120, 108, 76, 109, 78, 118, 49, 57, 121, 98, 50, 57, 48, 73, 106, 112, 48, 99, 110, 86, 108, 102, 81]
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<u8> { fn signature_rs256() -> Vec<u8> {
vec![112, 46, 33, 137, 67, 232, 143, 209, 30, 181, 216, 45, 191, 120, 69, vec![112, 46, 33, 137, 67, 232, 143, 209, 30, 181, 216, 45, 191, 120, 69, 243, 65, 6, 174,
243, 65, 6, 174, 27, 129, 255, 247, 115, 17, 22, 173, 209, 113, 125, 27, 129, 255, 247, 115, 17, 22, 173, 209, 113, 125, 131, 101, 109, 66, 10, 253, 60,
131, 101, 109, 66, 10, 253, 60, 150, 238, 221, 115, 162, 102, 62, 81, 150, 238, 221, 115, 162, 102, 62, 81, 102, 104, 123, 0, 11, 135, 34, 110, 1, 135, 237,
102, 104, 123, 0, 11, 135, 34, 110, 1, 135, 237, 16, 115, 249, 69, 16, 115, 249, 69, 229, 130, 173, 252, 239, 22, 216, 90, 121, 142, 232, 198, 109, 219,
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,
61, 184, 151, 91, 23, 208, 148, 2, 190, 237, 213, 217, 217, 112, 7, 96, 213, 248, 4, 12, 167, 68, 87, 98, 184, 31, 190, 127, 249, 217, 46, 10, 231, 111,
16, 141, 178, 129, 96, 213, 248, 4, 12, 167, 68, 87, 98, 184, 31, 36, 242, 91, 51, 187, 230, 244, 74, 230, 30, 177, 4, 10, 203, 32, 4, 77, 62, 249, 18,
190, 127, 249, 217, 46, 10, 231, 111, 36, 242, 91, 51, 187, 230, 244, 142, 212, 1, 48, 121, 91, 212, 189, 59, 65, 238, 202, 208, 102, 171, 101, 25, 129,
74, 230, 30, 177, 4, 10, 203, 32, 4, 77, 62, 249, 18, 142, 212, 1, 253, 228, 141, 247, 127, 55, 45, 195, 139, 159, 175, 221, 59, 239, 177, 139, 93, 163,
48, 121, 91, 212, 189, 59, 65, 238, 202, 208, 102, 171, 101, 25, 129, 204, 60, 46, 176, 47, 158, 58, 65, 214, 18, 202, 173, 21, 145, 18, 115, 160, 95, 35,
253, 228, 141, 247, 127, 55, 45, 195, 139, 159, 175, 221, 59, 239, 185, 232, 56, 250, 175, 132, 157, 105, 132, 41, 239, 90, 30, 136, 121, 130, 54, 195,
177, 139, 93, 163, 204, 60, 46, 176, 47, 158, 58, 65, 214, 18, 202, 212, 14, 96, 69, 34, 165, 68, 200, 242, 122, 122, 45, 184, 6, 99, 209, 108, 247, 202,
173, 21, 145, 18, 115, 160, 95, 35, 185, 232, 56, 250, 175, 132, 157, 234, 86, 222, 64, 92, 178, 33, 90, 69, 178, 194, 85, 102, 181, 90, 193, 167, 72, 160,
105, 132, 41, 239, 90, 30, 136, 121, 130, 54, 195, 212, 14, 96, 69, 112, 223, 200, 163, 42, 70, 149, 67, 208, 25, 238, 251, 71]
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] #[test]
pub fn test_sign() { pub fn test_sign() {
let mut buffer = File::open("test/rsa.pem").unwrap(); let mut buffer = File::open("test/rsa.pem").unwrap();
let private_key = RSA::private_key_from_pem(&mut buffer).unwrap(); let private_key = RSA::private_key_from_pem(&mut buffer).unwrap();
let mut sha = Hasher::new(Type::SHA256); let mut sha = Hasher::new(Type::SHA256);
sha.write_all(&signing_input_rs256()).unwrap(); sha.write_all(&signing_input_rs256()).unwrap();
let digest = sha.finish(); let digest = sha.finish();
let result = private_key.sign(Type::SHA256, &digest).unwrap(); let result = private_key.sign(Type::SHA256, &digest).unwrap();
assert_eq!(result, signature_rs256()); assert_eq!(result, signature_rs256());
} }
#[test] #[test]
pub fn test_verify() { pub fn test_verify() {
let mut buffer = File::open("test/rsa.pem.pub").unwrap(); let mut buffer = File::open("test/rsa.pem.pub").unwrap();
let public_key = RSA::public_key_from_pem(&mut buffer).unwrap(); let public_key = RSA::public_key_from_pem(&mut buffer).unwrap();
let mut sha = Hasher::new(Type::SHA256); let mut sha = Hasher::new(Type::SHA256);
sha.write_all(&signing_input_rs256()).unwrap(); sha.write_all(&signing_input_rs256()).unwrap();
let digest = sha.finish(); let digest = sha.finish();
let result = public_key.verify(Type::SHA256, &digest, &signature_rs256()).unwrap(); let result = public_key.verify(Type::SHA256, &digest, &signature_rs256()).unwrap();
assert!(result); assert!(result);
} }
} }

View File

@ -184,14 +184,11 @@ pub enum Nid {
OCSP, OCSP,
CaIssuers, CaIssuers,
OCSPSigning, // 180 OCSPSigning, // 180
// 181 and up are from openssl's obj_mac.h // 181 and up are from openssl's obj_mac.h
/// Shown as UID in cert subject /// Shown as UID in cert subject
UserId = 458, UserId = 458,
SHA256 = 672, SHA256 = 672,
SHA384, SHA384,
SHA512, SHA512,

View File

@ -23,16 +23,16 @@ pub struct BioMethod(ffi::BIO_METHOD);
impl BioMethod { impl BioMethod {
pub fn new<S: Read + Write>() -> BioMethod { pub fn new<S: Read + Write>() -> BioMethod {
BioMethod(ffi::BIO_METHOD { BioMethod(ffi::BIO_METHOD {
type_: BIO_TYPE_NONE, type_: BIO_TYPE_NONE,
name: b"rust\0".as_ptr() as *const _, name: b"rust\0".as_ptr() as *const _,
bwrite: Some(bwrite::<S>), bwrite: Some(bwrite::<S>),
bread: Some(bread::<S>), bread: Some(bread::<S>),
bputs: Some(bputs::<S>), bputs: Some(bputs::<S>),
bgets: None, bgets: None,
ctrl: Some(ctrl::<S>), ctrl: Some(ctrl::<S>),
create: Some(create), create: Some(create),
destroy: Some(destroy::<S>), destroy: Some(destroy::<S>),
callback_ctrl: None, callback_ctrl: None,
}) })
} }
} }
@ -82,12 +82,16 @@ unsafe fn state<'a, S: 'a>(bio: *mut BIO) -> &'a mut StreamState<S> {
} }
#[cfg(feature = "nightly")] #[cfg(feature = "nightly")]
fn catch_unwind<F, T>(f: F) -> Result<T, Box<Any + Send>> where F: FnOnce() -> T { fn catch_unwind<F, T>(f: F) -> Result<T, Box<Any + Send>>
where F: FnOnce() -> T
{
::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(f)) ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(f))
} }
#[cfg(not(feature = "nightly"))] #[cfg(not(feature = "nightly"))]
fn catch_unwind<F, T>(f: F) -> Result<T, Box<Any + Send>> where F: FnOnce() -> T { fn catch_unwind<F, T>(f: F) -> Result<T, Box<Any + Send>>
where F: FnOnce() -> T
{
Ok(f()) Ok(f())
} }
@ -137,7 +141,8 @@ unsafe extern "C" fn bread<S: Read>(bio: *mut BIO, buf: *mut c_char, len: c_int)
fn retriable_error(err: &io::Error) -> bool { fn retriable_error(err: &io::Error) -> bool {
match err.kind() { match err.kind() {
io::ErrorKind::WouldBlock | io::ErrorKind::NotConnected => true, io::ErrorKind::WouldBlock |
io::ErrorKind::NotConnected => true,
_ => false, _ => false,
} }
} }

View File

@ -850,7 +850,7 @@ pub struct SslCipher<'a> {
ph: PhantomData<&'a ()>, ph: PhantomData<&'a ()>,
} }
impl <'a> SslCipher<'a> { impl<'a> SslCipher<'a> {
/// Returns the name of cipher. /// Returns the name of cipher.
pub fn name(&self) -> &'static str { pub fn name(&self) -> &'static str {
let name = unsafe { let name = unsafe {
@ -874,12 +874,18 @@ impl <'a> SslCipher<'a> {
/// Returns the number of bits used for the cipher. /// Returns the number of bits used for the cipher.
pub fn bits(&self) -> CipherBits { pub fn bits(&self) -> CipherBits {
unsafe { unsafe {
let algo_bits : *mut c_int = ptr::null_mut(); let algo_bits: *mut c_int = ptr::null_mut();
let secret_bits = ffi::SSL_CIPHER_get_bits(self.cipher, algo_bits); let secret_bits = ffi::SSL_CIPHER_get_bits(self.cipher, algo_bits);
if !algo_bits.is_null() { if !algo_bits.is_null() {
CipherBits { secret: secret_bits, algorithm: Some(*algo_bits) } CipherBits {
secret: secret_bits,
algorithm: Some(*algo_bits),
}
} else { } else {
CipherBits { secret: secret_bits, algorithm: None } CipherBits {
secret: secret_bits,
algorithm: None,
}
} }
} }
} }
@ -987,7 +993,9 @@ impl Ssl {
{ {
unsafe { unsafe {
let verify = Box::new(verify); let verify = Box::new(verify);
ffi::SSL_set_ex_data(self.ssl, get_ssl_verify_data_idx::<F>(), mem::transmute(verify)); ffi::SSL_set_ex_data(self.ssl,
get_ssl_verify_data_idx::<F>(),
mem::transmute(verify));
ffi::SSL_set_verify(self.ssl, mode.bits as c_int, Some(ssl_raw_verify::<F>)); ffi::SSL_set_verify(self.ssl, mode.bits as c_int, Some(ssl_raw_verify::<F>));
} }
} }
@ -999,7 +1007,10 @@ impl Ssl {
if ptr.is_null() { if ptr.is_null() {
None None
} else { } else {
Some(SslCipher{ cipher: ptr, ph: PhantomData }) Some(SslCipher {
cipher: ptr,
ph: PhantomData,
})
} }
} }
} }
@ -1052,8 +1063,8 @@ impl Ssl {
/// Returns the name of the protocol used for the connection, e.g. "TLSv1.2", "SSLv3", etc. /// Returns the name of the protocol used for the connection, e.g. "TLSv1.2", "SSLv3", etc.
pub fn version(&self) -> &'static str { pub fn version(&self) -> &'static str {
let version = unsafe { let version = unsafe {
let ptr = ffi::SSL_get_version(self.ssl); let ptr = ffi::SSL_get_version(self.ssl);
CStr::from_ptr(ptr as *const _) CStr::from_ptr(ptr as *const _)
}; };
str::from_utf8(version.to_bytes()).unwrap() str::from_utf8(version.to_bytes()).unwrap()
@ -1224,7 +1235,8 @@ impl<S: Clone + Read + Write> Clone for SslStream<S> {
} }
} }
impl<S> fmt::Debug for SslStream<S> where S: fmt::Debug impl<S> fmt::Debug for SslStream<S>
where S: fmt::Debug
{ {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("SslStream") fmt.debug_struct("SslStream")
@ -1385,7 +1397,8 @@ impl<S> SslStream<S> {
} }
} }
LibSslError::ErrorZeroReturn => Some(SslError::SslSessionClosed), LibSslError::ErrorZeroReturn => Some(SslError::SslSessionClosed),
LibSslError::ErrorWantWrite | LibSslError::ErrorWantRead => None, LibSslError::ErrorWantWrite |
LibSslError::ErrorWantRead => None,
err => { err => {
Some(SslError::StreamError(io::Error::new(io::ErrorKind::Other, Some(SslError::StreamError(io::Error::new(io::ErrorKind::Other,
format!("unexpected error {:?}", err)))) format!("unexpected error {:?}", err))))
@ -1401,8 +1414,7 @@ impl<S> SslStream<S> {
} }
#[cfg(not(feature = "nightly"))] #[cfg(not(feature = "nightly"))]
fn check_panic(&mut self) { fn check_panic(&mut self) {}
}
fn get_bio_error(&mut self) -> io::Error { fn get_bio_error(&mut self) -> io::Error {
let error = unsafe { bio::take_error::<S>(self.ssl.get_raw_rbio()) }; let error = unsafe { bio::take_error::<S>(self.ssl.get_raw_rbio()) };
@ -1513,7 +1525,8 @@ pub enum MaybeSslStream<S>
Normal(S), Normal(S),
} }
impl<S> Read for MaybeSslStream<S> where S: Read + Write impl<S> Read for MaybeSslStream<S>
where S: Read + Write
{ {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match *self { match *self {
@ -1523,7 +1536,8 @@ impl<S> Read for MaybeSslStream<S> where S: Read + Write
} }
} }
impl<S> Write for MaybeSslStream<S> where S: Read + Write impl<S> Write for MaybeSslStream<S>
where S: Read + Write
{ {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match *self { match *self {
@ -1540,7 +1554,8 @@ impl<S> Write for MaybeSslStream<S> where S: Read + Write
} }
} }
impl<S> MaybeSslStream<S> where S: Read + Write impl<S> MaybeSslStream<S>
where S: Read + Write
{ {
/// Returns a reference to the underlying stream. /// Returns a reference to the underlying stream.
pub fn get_ref(&self) -> &S { pub fn get_ref(&self) -> &S {

View File

@ -236,7 +236,7 @@ run_test!(verify_untrusted, |method, stream| {
match SslStream::connect_generic(&ctx, stream) { match SslStream::connect_generic(&ctx, stream) {
Ok(_) => panic!("expected failure"), Ok(_) => panic!("expected failure"),
Err(err) => println!("error {:?}", err) Err(err) => println!("error {:?}", err),
} }
}); });
@ -246,11 +246,11 @@ run_test!(verify_trusted, |method, stream| {
match ctx.set_CA_file(&Path::new("test/cert.pem")) { match ctx.set_CA_file(&Path::new("test/cert.pem")) {
Ok(_) => {} Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err) Err(err) => panic!("Unexpected error {:?}", err),
} }
match SslStream::connect_generic(&ctx, stream) { match SslStream::connect_generic(&ctx, stream) {
Ok(_) => (), Ok(_) => (),
Err(err) => panic!("Expected success, got {:?}", err) Err(err) => panic!("Expected success, got {:?}", err),
} }
}); });
@ -264,7 +264,7 @@ run_test!(verify_untrusted_callback_override_ok, |method, stream| {
match SslStream::connect_generic(&ctx, stream) { match SslStream::connect_generic(&ctx, stream) {
Ok(_) => (), Ok(_) => (),
Err(err) => panic!("Expected success, got {:?}", err) Err(err) => panic!("Expected success, got {:?}", err),
} }
}); });
@ -289,11 +289,11 @@ run_test!(verify_trusted_callback_override_ok, |method, stream| {
match ctx.set_CA_file(&Path::new("test/cert.pem")) { match ctx.set_CA_file(&Path::new("test/cert.pem")) {
Ok(_) => {} Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err) Err(err) => panic!("Unexpected error {:?}", err),
} }
match SslStream::connect_generic(&ctx, stream) { match SslStream::connect_generic(&ctx, stream) {
Ok(_) => (), Ok(_) => (),
Err(err) => panic!("Expected success, got {:?}", err) Err(err) => panic!("Expected success, got {:?}", err),
} }
}); });
@ -307,7 +307,7 @@ run_test!(verify_trusted_callback_override_bad, |method, stream| {
match ctx.set_CA_file(&Path::new("test/cert.pem")) { match ctx.set_CA_file(&Path::new("test/cert.pem")) {
Ok(_) => {} Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err) Err(err) => panic!("Unexpected error {:?}", err),
} }
assert!(SslStream::connect_generic(&ctx, stream).is_err()); assert!(SslStream::connect_generic(&ctx, stream).is_err());
}); });
@ -335,7 +335,7 @@ run_test!(verify_trusted_get_error_ok, |method, stream| {
match ctx.set_CA_file(&Path::new("test/cert.pem")) { match ctx.set_CA_file(&Path::new("test/cert.pem")) {
Ok(_) => {} Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err) Err(err) => panic!("Unexpected error {:?}", err),
} }
assert!(SslStream::connect_generic(&ctx, stream).is_ok()); assert!(SslStream::connect_generic(&ctx, stream).is_ok());
}); });
@ -353,8 +353,7 @@ run_test!(verify_trusted_get_error_err, |method, stream| {
}); });
run_test!(verify_callback_data, |method, stream| { run_test!(verify_callback_data, |method, stream| {
fn callback(_preverify_ok: bool, x509_ctx: &X509StoreContext, fn callback(_preverify_ok: bool, x509_ctx: &X509StoreContext, node_id: &Vec<u8>) -> bool {
node_id: &Vec<u8>) -> bool {
let cert = x509_ctx.get_current_cert(); let cert = x509_ctx.get_current_cert();
match cert { match cert {
None => false, None => false,
@ -377,7 +376,7 @@ run_test!(verify_callback_data, |method, stream| {
match SslStream::connect_generic(&ctx, stream) { match SslStream::connect_generic(&ctx, stream) {
Ok(_) => (), Ok(_) => (),
Err(err) => panic!("Expected success, got {:?}", err) Err(err) => panic!("Expected success, got {:?}", err),
} }
}); });
@ -405,7 +404,7 @@ run_test!(ssl_verify_callback, |method, stream| {
match SslStream::connect_generic(ssl, stream) { match SslStream::connect_generic(ssl, stream) {
Ok(_) => (), Ok(_) => (),
Err(err) => panic!("Expected success, got {:?}", err) Err(err) => panic!("Expected success, got {:?}", err),
} }
assert_eq!(CHECKED.load(Ordering::SeqCst), 1); assert_eq!(CHECKED.load(Ordering::SeqCst), 1);
@ -499,8 +498,7 @@ fn test_write_direct() {
} }
run_test!(get_peer_certificate, |method, stream| { run_test!(get_peer_certificate, |method, stream| {
let stream = SslStream::connect_generic(&SslContext::new(method).unwrap(), let stream = SslStream::connect_generic(&SslContext::new(method).unwrap(), stream).unwrap();
stream).unwrap();
let cert = stream.ssl().peer_certificate().unwrap(); let cert = stream.ssl().peer_certificate().unwrap();
let fingerprint = cert.fingerprint(SHA1).unwrap(); let fingerprint = cert.fingerprint(SHA1).unwrap();
let node_hash_str = "E19427DAC79FBE758394945276A6E4F15F0BEBE6"; let node_hash_str = "E19427DAC79FBE758394945276A6E4F15F0BEBE6";

View File

@ -1,4 +1,3 @@
//
// Licensed under the Apache License, Version 2.0 (the "License"); // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. // you may not use this file except in compliance with the License.
// You may obtain a copy of the License at // You may obtain a copy of the License at
@ -86,4 +85,4 @@ fn test_versions() {
assert!(c_flags().starts_with("compiler:")); assert!(c_flags().starts_with("compiler:"));
assert!(built_on().starts_with("built on:")); assert!(built_on().starts_with("built on:"));
assert!(dir().starts_with("OPENSSLDIR:")); assert!(dir().starts_with("OPENSSLDIR:"));
} }

View File

@ -379,7 +379,9 @@ impl X509Generator {
ffi::X509_set_issuer_name(x509.handle, name); ffi::X509_set_issuer_name(x509.handle, name);
for (exttype, ext) in self.extensions.iter() { for (exttype, ext) in self.extensions.iter() {
try!(X509Generator::add_extension_internal(x509.handle, &exttype, &ext.to_string())); try!(X509Generator::add_extension_internal(x509.handle,
&exttype,
&ext.to_string()));
} }
let hash_fn = self.hash_type.evp_md(); let hash_fn = self.hash_type.evp_md();
@ -539,9 +541,9 @@ extern "C" {
impl<'ctx> Clone for X509<'ctx> { impl<'ctx> Clone for X509<'ctx> {
fn clone(&self) -> X509<'ctx> { fn clone(&self) -> X509<'ctx> {
unsafe { rust_X509_clone(self.handle) } unsafe { rust_X509_clone(self.handle) }
/* FIXME: given that we now have refcounting control, 'owned' should be uneeded, the 'ctx // FIXME: given that we now have refcounting control, 'owned' should be uneeded, the 'ctx
* is probably also uneeded. We can remove both to condense the x509 api quite a bit // is probably also uneeded. We can remove both to condense the x509 api quite a bit
*/ //
X509::new(self.handle, true) X509::new(self.handle, true)
} }
} }
@ -671,7 +673,7 @@ impl Extensions {
pub fn add(&mut self, ext: Extension) { pub fn add(&mut self, ext: Extension) {
let ext_type = ext.get_type(); let ext_type = ext.get_type();
if let Some(index) = self.indexes.get(&ext_type) { if let Some(index) = self.indexes.get(&ext_type) {
self.extensions[*index] = ext; self.extensions[*index] = ext;
return; return;
} }
@ -693,7 +695,7 @@ impl Extensions {
/// extension in the collection. /// extension in the collection.
struct ExtensionsIter<'a> { struct ExtensionsIter<'a> {
current: usize, current: usize,
extensions: &'a Vec<Extension> extensions: &'a Vec<Extension>,
} }
impl<'a> Iterator for ExtensionsIter<'a> { impl<'a> Iterator for ExtensionsIter<'a> {
@ -798,9 +800,7 @@ pub struct GeneralNames<'a> {
impl<'a> GeneralNames<'a> { impl<'a> GeneralNames<'a> {
/// Returns the number of `GeneralName`s in this structure. /// Returns the number of `GeneralName`s in this structure.
pub fn len(&self) -> usize { pub fn len(&self) -> usize {
unsafe { unsafe { (*self.stack).stack.num as usize }
(*self.stack).stack.num as usize
}
} }
/// Returns the specified `GeneralName`. /// Returns the specified `GeneralName`.
@ -823,7 +823,7 @@ impl<'a> GeneralNames<'a> {
pub fn iter(&self) -> GeneralNamesIter { pub fn iter(&self) -> GeneralNamesIter {
GeneralNamesIter { GeneralNamesIter {
names: self, names: self,
idx: 0 idx: 0,
} }
} }
} }

View File

@ -56,9 +56,10 @@ fn test_cert_gen_extension_ordering() {
#[test] #[test]
fn test_cert_gen_extension_bad_ordering() { fn test_cert_gen_extension_bad_ordering() {
let result = get_generator() let result = get_generator()
.add_extension(OtherNid(Nid::AuthorityKeyIdentifier, "keyid:always".to_owned())) .add_extension(OtherNid(Nid::AuthorityKeyIdentifier,
.add_extension(OtherNid(Nid::SubjectKeyIdentifier, "hash".to_owned())) "keyid:always".to_owned()))
.generate(); .add_extension(OtherNid(Nid::SubjectKeyIdentifier, "hash".to_owned()))
.generate();
assert!(result.is_err()); assert!(result.is_err());
} }
@ -162,7 +163,8 @@ fn test_subject_alt_name() {
let subject_alt_names = cert.subject_alt_names().unwrap(); let subject_alt_names = cert.subject_alt_names().unwrap();
assert_eq!(3, subject_alt_names.len()); assert_eq!(3, subject_alt_names.len());
assert_eq!(Some("foobar.com"), subject_alt_names.get(0).dnsname()); assert_eq!(Some("foobar.com"), subject_alt_names.get(0).dnsname());
assert_eq!(subject_alt_names.get(1).ipaddress(), Some(&[127, 0, 0, 1][..])); assert_eq!(subject_alt_names.get(1).ipaddress(),
Some(&[127, 0, 0, 1][..]));
assert_eq!(subject_alt_names.get(2).ipaddress(), assert_eq!(subject_alt_names.get(2).ipaddress(),
Some(&b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01"[..])); Some(&b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01"[..]));
} }
@ -174,8 +176,10 @@ fn test_subject_alt_name_iter() {
let subject_alt_names = cert.subject_alt_names().unwrap(); let subject_alt_names = cert.subject_alt_names().unwrap();
let mut subject_alt_names_iter = subject_alt_names.iter(); let mut subject_alt_names_iter = subject_alt_names.iter();
assert_eq!(subject_alt_names_iter.next().unwrap().dnsname(), Some("foobar.com")); assert_eq!(subject_alt_names_iter.next().unwrap().dnsname(),
assert_eq!(subject_alt_names_iter.next().unwrap().ipaddress(), Some(&[127, 0, 0, 1][..])); Some("foobar.com"));
assert_eq!(subject_alt_names_iter.next().unwrap().ipaddress(),
Some(&[127, 0, 0, 1][..]));
assert_eq!(subject_alt_names_iter.next().unwrap().ipaddress(), assert_eq!(subject_alt_names_iter.next().unwrap().ipaddress(),
Some(&b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01"[..])); Some(&b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01"[..]));
assert!(subject_alt_names_iter.next().is_none()); assert!(subject_alt_names_iter.next().is_none());