diff options
| author | Steven Fackler <[email protected]> | 2016-07-31 15:15:47 -0700 |
|---|---|---|
| committer | Steven Fackler <[email protected]> | 2016-07-31 15:15:47 -0700 |
| commit | f0ffa246b83102d70bc59f76d136981efdafb1e7 (patch) | |
| tree | 0f6036a20ba4eb7b333986206962abeb4bab6c2f /openssl/src/crypto | |
| parent | Revert "Add a new trait based Nid setup" (diff) | |
| parent | Merge pull request #402 from bbatha/feat/dsa-ffi (diff) | |
| download | rust-openssl-f0ffa246b83102d70bc59f76d136981efdafb1e7.tar.xz rust-openssl-f0ffa246b83102d70bc59f76d136981efdafb1e7.zip | |
Merge remote-tracking branch 'origin/master' into breaks
Diffstat (limited to 'openssl/src/crypto')
| -rw-r--r-- | openssl/src/crypto/dsa.rs | 351 | ||||
| -rw-r--r-- | openssl/src/crypto/hash.rs | 48 | ||||
| -rw-r--r-- | openssl/src/crypto/hmac.rs | 3 | ||||
| -rw-r--r-- | openssl/src/crypto/mod.rs | 9 | ||||
| -rw-r--r-- | openssl/src/crypto/pkey.rs | 73 | ||||
| -rw-r--r-- | openssl/src/crypto/rsa.rs | 220 | ||||
| -rw-r--r-- | openssl/src/crypto/util.rs | 58 |
7 files changed, 709 insertions, 53 deletions
diff --git a/openssl/src/crypto/dsa.rs b/openssl/src/crypto/dsa.rs new file mode 100644 index 00000000..36806a48 --- /dev/null +++ b/openssl/src/crypto/dsa.rs @@ -0,0 +1,351 @@ +use ffi; +use std::fmt; +use error::ErrorStack; +use std::ptr; +use std::io::{self, Read, Write}; +use libc::{c_uint, c_int}; + +use bn::BigNum; +use bio::MemBio; +use crypto::hash; +use crypto::HashTypeInternals; + +#[cfg(feature = "catch_unwind")] +use libc::{c_char, c_void}; +#[cfg(feature = "catch_unwind")] +use crypto::util::{CallbackState, invoke_passwd_cb}; + +/// Builder for upfront DSA parameter generateration +pub struct DSAParams(*mut ffi::DSA); + +impl DSAParams { + pub fn with_size(size: usize) -> Result<DSAParams, ErrorStack> { + 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())); + Ok(dsa) + } + } + + /// Generate a key pair from the initialized parameters + pub fn generate(self) -> Result<DSA, ErrorStack> { + unsafe { + try_ssl!(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 DSA(*mut ffi::DSA); + +impl Drop for DSA { + fn drop(&mut self) { + unsafe { + ffi::DSA_free(self.0); + } + } +} + +impl DSA { + /// the caller should assert that the dsa pointer is valid. + pub unsafe fn from_raw(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: usize) -> Result<DSA, ErrorStack> { + let params = try!(DSAParams::with_size(size)); + params.generate() + } + + /// Reads a DSA private key from PEM formatted data. + pub fn private_key_from_pem<R>(reader: &mut R) -> io::Result<DSA> + where R: Read + { + let mut mem_bio = try!(MemBio::new()); + try!(io::copy(reader, &mut mem_bio)); + + unsafe { + let dsa = try_ssl_null!(ffi::PEM_read_bio_DSAPrivateKey(mem_bio.get_handle(), + ptr::null_mut(), + None, + ptr::null_mut())); + let dsa = DSA(dsa); + assert!(dsa.has_private_key()); + Ok(dsa) + } + } + + /// Read a private key from PEM supplying a password callback to be invoked if the private key + /// is encrypted. + /// + /// The callback will be passed the password buffer and should return the number of characters + /// placed into the buffer. + /// + /// Requires the `catch_unwind` feature. + #[cfg(feature = "catch_unwind")] + pub fn private_key_from_pem_cb<R, F>(reader: &mut R, pass_cb: F) -> Result<DSA, ErrorStack> + where R: Read, F: FnOnce(&mut [c_char]) -> usize + { + let mut cb = CallbackState::new(pass_cb); + let mut mem_bio = try!(MemBio::new()); + try!(io::copy(reader, &mut mem_bio).map_err(StreamError)); + + unsafe { + let cb_ptr = &mut cb as *mut _ as *mut c_void; + let dsa = try_ssl_null!(ffi::PEM_read_bio_DSAPrivateKey(mem_bio.get_handle(), + ptr::null_mut(), + Some(invoke_passwd_cb::<F>), + cb_ptr)); + let dsa = DSA(dsa); + assert!(dsa.has_private_key()); + Ok(dsa) + } + } + + /// Writes an DSA private key as unencrypted PEM formatted data + pub fn private_key_to_pem<W>(&self, writer: &mut W) -> io::Result<()> + where W: Write + { + assert!(self.has_private_key()); + let mut mem_bio = try!(MemBio::new()); + + unsafe { + try_ssl!(ffi::PEM_write_bio_DSAPrivateKey(mem_bio.get_handle(), self.0, + ptr::null(), ptr::null_mut(), 0, + None, ptr::null_mut())) + }; + + + try!(io::copy(&mut mem_bio, writer)); + Ok(()) + } + + /// Reads an DSA public key from PEM formatted data. + pub fn public_key_from_pem<R>(reader: &mut R) -> io::Result<DSA> + where R: Read + { + let mut mem_bio = try!(MemBio::new()); + try!(io::copy(reader, &mut mem_bio)); + + unsafe { + let dsa = try_ssl_null!(ffi::PEM_read_bio_DSA_PUBKEY(mem_bio.get_handle(), + ptr::null_mut(), + None, + ptr::null_mut())); + Ok(DSA(dsa)) + } + } + + /// Writes an DSA public key as PEM formatted data + pub fn public_key_to_pem<W>(&self, writer: &mut W) -> io::Result<()> + where W: Write + { + let mut mem_bio = try!(MemBio::new()); + + unsafe { try_ssl!(ffi::PEM_write_bio_DSA_PUBKEY(mem_bio.get_handle(), self.0)) }; + + try!(io::copy(&mut mem_bio, writer)); + Ok(()) + } + + pub fn size(&self) -> Option<u32> { + if self.has_q() { + unsafe { Some(ffi::DSA_size(self.0) as u32) } + } else { + None + } + } + + pub fn sign(&self, hash: hash::Type, message: &[u8]) -> Result<Vec<u8>, 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<bool, ErrorStack> { + 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 + } + + // The following getters are unsafe, since BigNum::new_from_ffi fails upon null pointers + pub fn p(&self) -> Result<BigNum, ErrorStack> { + unsafe { BigNum::new_from_ffi((*self.0).p) } + } + + pub fn has_p(&self) -> bool { + unsafe { !(*self.0).p.is_null() } + } + + pub fn q(&self) -> Result<BigNum, ErrorStack> { + unsafe { BigNum::new_from_ffi((*self.0).q) } + } + + pub fn has_q(&self) -> bool { + unsafe { !(*self.0).q.is_null() } + } + + pub fn g(&self) -> Result<BigNum, ErrorStack> { + unsafe { BigNum::new_from_ffi((*self.0).g) } + } + + pub fn has_g(&self) -> bool { + unsafe { !(*self.0).q.is_null() } + } + + pub fn has_public_key(&self) -> bool { + unsafe { !(*self.0).pub_key.is_null() } + } + + pub fn has_private_key(&self) -> bool { + unsafe { !(*self.0).priv_key.is_null() } + } +} + +impl fmt::Debug for DSA { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "DSA") + } +} + +#[cfg(test)] +mod test { + use std::fs::File; + use std::io::{Write, Cursor}; + use super::*; + use crypto::hash::*; + + #[test] + pub fn test_generate() { + let key = DSA::generate(1024).unwrap(); + let mut priv_buf = Cursor::new(vec![]); + let mut pub_buf = Cursor::new(vec![]); + + key.public_key_to_pem(&mut pub_buf).unwrap(); + key.private_key_to_pem(&mut priv_buf).unwrap(); + + let input: Vec<u8> = (0..25).cycle().take(1024).collect(); + + let digest = { + let mut sha = Hasher::new(Type::SHA1); + sha.write_all(&input).unwrap(); + sha.finish() + }; + + 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<u8> = (0..25).cycle().take(1024).collect(); + + let private_key = { + let mut buffer = File::open("test/dsa.pem").unwrap(); + DSA::private_key_from_pem(&mut buffer).unwrap() + }; + + let public_key = { + let mut buffer = File::open("test/dsa.pem.pub").unwrap(); + DSA::public_key_from_pem(&mut buffer).unwrap() + }; + + let digest = { + let mut sha = Hasher::new(Type::SHA1); + sha.write_all(&input).unwrap(); + sha.finish() + }; + + 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<u8> = (0..25).cycle().take(128).collect(); + let private_key = { + let mut buffer = File::open("test/dsa.pem").unwrap(); + DSA::private_key_from_pem(&mut buffer).unwrap() + }; + + let public_key = { + let mut buffer = File::open("test/dsa.pem.pub").unwrap(); + DSA::public_key_from_pem(&mut buffer).unwrap() + }; + + let digest = { + let mut sha = Hasher::new(Type::SHA1); + sha.write_all(&input).unwrap(); + sha.finish() + }; + + 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!"); + } + } + + #[test] + #[cfg(feature = "catch_unwind")] + pub fn test_password() { + let mut password_queried = false; + let mut buffer = File::open("test/dsa-encrypted.pem").unwrap(); + DSA::private_key_from_pem_cb(&mut buffer, |password| { + password_queried = true; + password[0] = b'm' as _; + password[1] = b'y' as _; + password[2] = b'p' as _; + password[3] = b'a' as _; + password[4] = b's' as _; + password[5] = b's' as _; + 6 + }).unwrap(); + + assert!(password_queried); + } +} diff --git a/openssl/src/crypto/hash.rs b/openssl/src/crypto/hash.rs index 78465851..69d3a350 100644 --- a/openssl/src/crypto/hash.rs +++ b/openssl/src/crypto/hash.rs @@ -2,9 +2,11 @@ use libc::c_uint; use std::iter::repeat; use std::io::prelude::*; use std::io; - use ffi; +use crypto::HashTypeInternals; +use nid::Nid; + /// Message digest (hash) type. #[derive(Copy, Clone)] pub enum Type { @@ -17,19 +19,32 @@ pub enum Type { RIPEMD160, } +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 Type { /// Returns the length of the message digest. #[inline] pub fn md_len(&self) -> usize { - use self::Type::*; match *self { - MD5 => 16, - SHA1 => 20, - SHA224 => 28, - SHA256 => 32, - SHA384 => 48, - SHA512 => 64, - RIPEMD160 => 20, + Type::MD5 => 16, + Type::SHA1 => 20, + Type::SHA224 => 28, + Type::SHA256 => 32, + Type::SHA384 => 48, + Type::SHA512 => 64, + Type::RIPEMD160 => 20, } } @@ -37,15 +52,14 @@ impl Type { #[inline] pub fn evp_md(&self) -> *const ffi::EVP_MD { unsafe { - use self::Type::*; match *self { - MD5 => ffi::EVP_md5(), - SHA1 => ffi::EVP_sha1(), - SHA224 => ffi::EVP_sha224(), - SHA256 => ffi::EVP_sha256(), - SHA384 => ffi::EVP_sha384(), - SHA512 => ffi::EVP_sha512(), - RIPEMD160 => ffi::EVP_ripemd160(), + 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(), } } } diff --git a/openssl/src/crypto/hmac.rs b/openssl/src/crypto/hmac.rs index 866087b0..143c7b75 100644 --- a/openssl/src/crypto/hmac.rs +++ b/openssl/src/crypto/hmac.rs @@ -387,8 +387,7 @@ mod tests { let tests: [(Vec<u8>, Vec<u8>); 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()), + (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(), diff --git a/openssl/src/crypto/mod.rs b/openssl/src/crypto/mod.rs index bb77453f..6a34bd59 100644 --- a/openssl/src/crypto/mod.rs +++ b/openssl/src/crypto/mod.rs @@ -14,6 +14,8 @@ // limitations under the License. // +use nid::Nid; + pub mod hash; pub mod hmac; pub mod pkcs5; @@ -22,5 +24,12 @@ pub mod rand; pub mod symm; pub mod memcmp; pub mod rsa; +pub mod dsa; +#[cfg(feature = "catch_unwind")] +mod util; mod symm_internal; + +trait HashTypeInternals { + fn as_nid(&self) -> Nid; +} diff --git a/openssl/src/crypto/pkey.rs b/openssl/src/crypto/pkey.rs index 1020a82e..0231cc95 100644 --- a/openssl/src/crypto/pkey.rs +++ b/openssl/src/crypto/pkey.rs @@ -5,12 +5,19 @@ use std::iter::repeat; use std::mem; use std::ptr; use bio::MemBio; + +use crypto::HashTypeInternals; use crypto::hash; use crypto::hash::Type as HashType; use ffi; use crypto::rsa::RSA; use error::ErrorStack; +#[cfg(feature = "catch_unwind")] +use libc::{c_void, c_char}; +#[cfg(feature = "catch_unwind")] +use crypto::util::{CallbackState, invoke_passwd_cb}; + #[derive(Copy, Clone)] pub enum Parts { Neither, @@ -41,18 +48,6 @@ fn openssl_padding_code(padding: EncryptionPadding) -> c_int { } } -fn openssl_hash_nid(hash: HashType) -> c_int { - match hash { - HashType::MD5 => 4, // NID_md5, - HashType::SHA1 => 64, // NID_sha1 - HashType::SHA224 => 675, // NID_sha224 - HashType::SHA256 => 672, // NID_sha256 - HashType::SHA384 => 673, // NID_sha384 - HashType::SHA512 => 674, // NID_sha512 - HashType::RIPEMD160 => 117, // NID_ripemd160 - } -} - pub struct PKey { evp: *mut ffi::EVP_PKEY, parts: Parts, @@ -104,6 +99,35 @@ impl PKey { } } + /// Read a private key from PEM, supplying a password callback to be invoked if the private key + /// is encrypted. + /// + /// The callback will be passed the password buffer and should return the number of characters + /// placed into the buffer. + /// + /// Requires the `catch_unwind` feature. + #[cfg(feature = "catch_unwind")] + pub fn private_key_from_pem_cb<R, F>(reader: &mut R, pass_cb: F) -> Result<PKey, SslError> + where R: Read, F: FnOnce(&mut [c_char]) -> usize + { + let mut cb = CallbackState::new(pass_cb); + + let mut mem_bio = try!(MemBio::new()); + try!(io::copy(reader, &mut mem_bio).map_err(StreamError)); + + unsafe { + let evp = try_ssl_null!(ffi::PEM_read_bio_PrivateKey(mem_bio.get_handle(), + ptr::null_mut(), + Some(invoke_passwd_cb::<F>), + &mut cb as *mut _ as *mut c_void)); + + Ok(PKey { + evp: evp as *mut ffi::EVP_PKEY, + parts: Parts::Both, + }) + } + } + /// Reads public key from PEM, takes ownership of handle pub fn public_key_from_pem<R>(reader: &mut R) -> io::Result<PKey> where R: Read @@ -125,7 +149,7 @@ impl PKey { /// Reads an RSA private key from PEM, takes ownership of handle pub fn private_rsa_key_from_pem<R>(reader: &mut R) -> io::Result<PKey> - where R: Read + where R: Read { let rsa = try!(RSA::private_key_from_pem(reader)); unsafe { @@ -143,7 +167,7 @@ impl PKey { /// Reads an RSA public key from PEM, takes ownership of handle pub fn public_rsa_key_from_pem<R>(reader: &mut R) -> io::Result<PKey> - where R: Read + where R: Read { let rsa = try!(RSA::public_key_from_pem(reader)); unsafe { @@ -561,7 +585,7 @@ impl PKey { let mut r = repeat(0u8).take(len as usize + 1).collect::<Vec<_>>(); let mut len = 0; - let rv = ffi::RSA_sign(openssl_hash_nid(hash), + let rv = ffi::RSA_sign(hash.as_nid() as c_int, s.as_ptr(), s.len() as c_uint, r.as_mut_ptr(), @@ -584,7 +608,7 @@ impl PKey { panic!("Could not get RSA key for verification"); } - let rv = ffi::RSA_verify(openssl_hash_nid(hash), + let rv = ffi::RSA_verify(hash.as_nid() as c_int, h.as_ptr(), h.len() as c_uint, s.as_ptr(), @@ -615,16 +639,15 @@ impl Drop for PKey { impl Clone for PKey { fn clone(&self) -> Self { 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 { Parts::Public => { pkey.load_pub(&self.save_pub()[..]); - }, + } Parts::Both => { pkey.load_priv(&self.save_priv()[..]); - }, - Parts::Neither => { - }, + } + Parts::Neither => {} } pkey } @@ -699,8 +722,8 @@ mod tests { fn test_private_rsa_key_from_pem() { let key_path = Path::new("test/key.pem"); let mut file = File::open(&key_path) - .ok() - .expect("Failed to open `test/key.pem`"); + .ok() + .expect("Failed to open `test/key.pem`"); super::PKey::private_rsa_key_from_pem(&mut file).unwrap(); } @@ -709,8 +732,8 @@ mod tests { fn test_public_rsa_key_from_pem() { let key_path = Path::new("test/key.pem.pub"); let mut file = File::open(&key_path) - .ok() - .expect("Failed to open `test/key.pem.pub`"); + .ok() + .expect("Failed to open `test/key.pem.pub`"); super::PKey::public_rsa_key_from_pem(&mut file).unwrap(); } diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index 11970933..b403eab5 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -1,11 +1,19 @@ use ffi; use std::fmt; use std::ptr; -use std::io::{self, Read}; +use std::io::{self, Read, Write}; +use libc::c_int; use bn::BigNum; use bio::MemBio; use error::ErrorStack; +use crypto::HashTypeInternals; +use crypto::hash; + +#[cfg(feature = "catch_unwind")] +use libc::{c_void, c_char}; +#[cfg(feature = "catch_unwind")] +use crypto::util::{CallbackState, invoke_passwd_cb}; pub struct RSA(*mut ffi::RSA); @@ -29,6 +37,29 @@ impl RSA { } } + pub fn from_private_components(n: BigNum, + e: BigNum, + d: BigNum, + p: BigNum, + q: BigNum, + dp: BigNum, + dq: BigNum, + qi: BigNum) + -> Result<RSA, ErrorStack> { + unsafe { + let rsa = try_ssl_null!(ffi::RSA_new()); + (*rsa).n = n.into_raw(); + (*rsa).e = e.into_raw(); + (*rsa).d = d.into_raw(); + (*rsa).p = p.into_raw(); + (*rsa).q = q.into_raw(); + (*rsa).dmp1 = dp.into_raw(); + (*rsa).dmq1 = dq.into_raw(); + (*rsa).iqmp = qi.into_raw(); + Ok(RSA(rsa)) + } + } + /// the caller should assert that the rsa pointer is valid. pub unsafe fn from_raw(rsa: *mut ffi::RSA) -> RSA { RSA(rsa) @@ -36,7 +67,7 @@ impl RSA { /// Reads an RSA private key from PEM formatted data. pub fn private_key_from_pem<R>(reader: &mut R) -> io::Result<RSA> - where R: Read + where R: Read { let mut mem_bio = try!(MemBio::new()); try!(io::copy(reader, &mut mem_bio)); @@ -50,9 +81,51 @@ impl RSA { } } + /// Reads an RSA private key from PEM formatted data and supplies a password callback. + /// + /// Requires the `catch_unwind` feature. + #[cfg(feature = "catch_unwind")] + pub fn private_key_from_pem_cb<R, F>(reader: &mut R, pass_cb: F) -> Result<RSA, ErrorStack> + where R: Read, F: FnOnce(&mut [c_char]) -> usize + { + let mut cb = CallbackState::new(pass_cb); + + let mut mem_bio = try!(MemBio::new()); + try!(io::copy(reader, &mut mem_bio).map_err(StreamError)); + + unsafe { + let cb_ptr = &mut cb as *mut _ as *mut c_void; + let rsa = try_ssl_null!(ffi::PEM_read_bio_RSAPrivateKey(mem_bio.get_handle(), + ptr::null_mut(), + Some(invoke_passwd_cb::<F>), + cb_ptr)); + + Ok(RSA(rsa)) + } + } + + /// Writes an RSA private key as unencrypted PEM formatted data + pub fn private_key_to_pem<W>(&self, writer: &mut W) -> io::Result<()> + where W: Write + { + let mut mem_bio = try!(MemBio::new()); + + unsafe { + try_ssl!(ffi::PEM_write_bio_RSAPrivateKey(mem_bio.get_handle(), + self.0, + ptr::null(), + ptr::null_mut(), + 0, + None, + ptr::null_mut())); + } + try!(io::copy(&mut mem_bio, writer)); + Ok(()) + } + /// Reads an RSA public key from PEM formatted data. pub fn public_key_from_pem<R>(reader: &mut R) -> io::Result<RSA> - where R: Read + where R: Read { let mut mem_bio = try!(MemBio::new()); try!(io::copy(reader, &mut mem_bio)); @@ -66,6 +139,58 @@ impl RSA { } } + /// Writes an RSA public key as PEM formatted data + pub fn public_key_to_pem<W>(&self, writer: &mut W) -> io::Result<()> + where W: Write + { + let mut mem_bio = try!(MemBio::new()); + + unsafe { + try_ssl!(ffi::PEM_write_bio_RSA_PUBKEY(mem_bio.get_handle(), self.0)) + }; + + try!(io::copy(&mut mem_bio, writer)); + Ok(()) + } + + pub fn size(&self) -> Option<u32> { + if self.has_n() { + unsafe { Some(ffi::RSA_size(self.0) as u32) } + } else { + None + } + } + + pub fn sign(&self, hash: hash::Type, message: &[u8]) -> Result<Vec<u8>, ErrorStack> { + 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<bool, ErrorStack> { + 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); + try_ssl_if!(result == -1); + Ok(result == 1) + } + } + pub fn as_ptr(&self) -> *mut ffi::RSA { self.0 } @@ -78,9 +203,7 @@ impl RSA { } pub fn has_n(&self) -> bool { - unsafe { - !(*self.0).n.is_null() - } + unsafe { !(*self.0).n.is_null() } } pub fn d(&self) -> Result<BigNum, ErrorStack> { @@ -96,9 +219,7 @@ impl RSA { } pub fn has_e(&self) -> bool { - unsafe { - !(*self.0).e.is_null() - } + unsafe { !(*self.0).e.is_null() } } pub fn p(&self) -> Result<BigNum, ErrorStack> { @@ -119,3 +240,84 @@ impl fmt::Debug for RSA { write!(f, "RSA") } } + +#[cfg(test)] +mod test { + use std::fs::File; + use std::io::Write; + use super::*; + use crypto::hash::*; + + fn signing_input_rs256() -> Vec<u8> { + 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<u8> { + 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 mut buffer = File::open("test/rsa.pem").unwrap(); + let private_key = RSA::private_key_from_pem(&mut buffer).unwrap(); + + let mut sha = Hasher::new(Type::SHA256); + sha.write_all(&signing_input_rs256()).unwrap(); + let digest = sha.finish(); + + let result = private_key.sign(Type::SHA256, &digest).unwrap(); + + assert_eq!(result, signature_rs256()); + } + + #[test] + pub fn test_verify() { + let mut buffer = File::open("test/rsa.pem.pub").unwrap(); + let public_key = RSA::public_key_from_pem(&mut buffer).unwrap(); + + let mut sha = Hasher::new(Type::SHA256); + sha.write_all(&signing_input_rs256()).unwrap(); + let digest = sha.finish(); + + let result = public_key.verify(Type::SHA256, &digest, &signature_rs256()).unwrap(); + + assert!(result); + } + + #[test] + #[cfg(feature = "catch_unwind")] + pub fn test_password() { + let mut password_queried = false; + let mut buffer = File::open("test/rsa-encrypted.pem").unwrap(); + RSA::private_key_from_pem_cb(&mut buffer, |password| { + password_queried = true; + password[0] = b'm' as _; + password[1] = b'y' as _; + password[2] = b'p' as _; + password[3] = b'a' as _; + password[4] = b's' as _; + password[5] = b's' as _; + 6 + }).unwrap(); + + assert!(password_queried); + } +} diff --git a/openssl/src/crypto/util.rs b/openssl/src/crypto/util.rs new file mode 100644 index 00000000..be72aa59 --- /dev/null +++ b/openssl/src/crypto/util.rs @@ -0,0 +1,58 @@ +use libc::{c_int, c_char, c_void}; + +use std::any::Any; +use std::panic; +use std::slice; + +/// Wraps a user-supplied callback and a slot for panics thrown inside the callback (while FFI +/// frames are on the stack). +/// +/// When dropped, checks if the callback has panicked, and resumes unwinding if so. +pub struct CallbackState<F> { + /// The user callback. Taken out of the `Option` when called. + cb: Option<F>, + /// If the callback panics, we place the panic object here, to be re-thrown once OpenSSL + /// returns. + panic: Option<Box<Any + Send + 'static>>, +} + +impl<F> CallbackState<F> { + pub fn new(callback: F) -> Self { + CallbackState { + cb: Some(callback), + panic: None, + } + } +} + +impl<F> Drop for CallbackState<F> { + fn drop(&mut self) { + if let Some(panic) = self.panic.take() { + panic::resume_unwind(panic); + } + } +} + +/// 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<F>(buf: *mut c_char, + size: c_int, + _rwflag: c_int, + cb_state: *mut c_void) + -> c_int + where F: FnOnce(&mut [i8]) -> 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<F>) }; + + callback.cb.take().unwrap()(pass_slice) + }); + + if let Ok(len) = result { + return len as c_int; + } else { + return 0; + } +} |