From 6bbb21779b2665d91ddb8457894945913c189085 Mon Sep 17 00:00:00 2001 From: Chris Dawes Date: Tue, 3 May 2016 19:45:30 +0100 Subject: add constructor for private keys from bignums --- openssl/src/crypto/rsa.rs | 52 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) (limited to 'openssl/src') diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index 6fcb5b07..974f9ad9 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -28,6 +28,21 @@ impl 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 { + 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 { @@ -65,6 +80,43 @@ impl RSA { Ok(RSA(rsa)) } } + + pub fn size(&self) -> Result { + if self.has_n() { + unsafe { + Ok(ffi::RSA_size(self.0) as u32) + } + } else { + Err(SslError::OpenSslErrors(vec![])) + } + } + + pub fn sign(&self, hash_id: i32, message: &[u8]) -> Result, SslError> { + // RSA_sign(t: c_int, m: *const u8, mlen: c_uint, sig: *mut u8, siglen: *mut c_uint, k: *mut RSA) -> c_int + + let k_len = try!(self.size()); + let mut sig = vec![0;k_len as usize]; + let mut sig_len = k_len; + + unsafe { + let result = ffi::RSA_sign(hash_id, message.as_ptr(), message.len() as u32, sig.as_mut_ptr(), &mut sig_len, self.0); + assert!(sig_len == k_len); + + if result == 1 { + Ok(sig) + } else { + Err(SslError::OpenSslErrors(vec![])) + } + } + } + + pub fn verify(&self, hash_id: i32, message: &[u8], sig: &[u8]) -> Result { + unsafe { + let result = ffi::RSA_verify(hash_id, message.as_ptr(), message.len() as u32, sig.as_ptr(), sig.len() as u32, self.0); + + Ok(result == 1) + } + } pub fn as_ptr(&self) -> *mut ffi::RSA { self.0 -- cgit v1.2.3 From 6f410a25b2179b11183a56ca0d476a744bff91cd Mon Sep 17 00:00:00 2001 From: Chris Dawes Date: Tue, 3 May 2016 22:17:07 +0100 Subject: take enum instead of ints from openssl header file --- openssl/src/crypto/rsa.rs | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) (limited to 'openssl/src') diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index 974f9ad9..ada5f1c1 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -7,6 +7,24 @@ use std::io::{self, Read}; use bn::BigNum; use bio::MemBio; +#[derive(Copy, Clone, Debug)] +pub enum PKCSHashType { + SHA256, + SHA384, + SHA512 +} + +/// https://github.com/openssl/openssl/blob/master/include/openssl/obj_mac.h#L2790 +impl Into for PKCSHashType { + fn into(self) -> i32 { + match self { + PKCSHashType::SHA256 => 672, + PKCSHashType::SHA384 => 673, + PKCSHashType::SHA512 => 674 + } + } +} + pub struct RSA(*mut ffi::RSA); impl Drop for RSA { @@ -91,15 +109,13 @@ impl RSA { } } - pub fn sign(&self, hash_id: i32, message: &[u8]) -> Result, SslError> { - // 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 sign(&self, hash_id: PKCSHashType, message: &[u8]) -> Result, SslError> { let k_len = try!(self.size()); let mut sig = vec![0;k_len as usize]; let mut sig_len = k_len; unsafe { - let result = ffi::RSA_sign(hash_id, message.as_ptr(), message.len() as u32, sig.as_mut_ptr(), &mut sig_len, self.0); + let result = ffi::RSA_sign(hash_id.into(), message.as_ptr(), message.len() as u32, sig.as_mut_ptr(), &mut sig_len, self.0); assert!(sig_len == k_len); if result == 1 { @@ -110,9 +126,9 @@ impl RSA { } } - pub fn verify(&self, hash_id: i32, message: &[u8], sig: &[u8]) -> Result { + pub fn verify(&self, hash_id: PKCSHashType, message: &[u8], sig: &[u8]) -> Result { unsafe { - let result = ffi::RSA_verify(hash_id, message.as_ptr(), message.len() as u32, sig.as_ptr(), sig.len() as u32, self.0); + let result = ffi::RSA_verify(hash_id.into(), message.as_ptr(), message.len() as u32, sig.as_ptr(), sig.len() as u32, self.0); Ok(result == 1) } -- cgit v1.2.3 From a5ede6a85101f294333ce7f102cb98d718b53638 Mon Sep 17 00:00:00 2001 From: Chris Dawes Date: Wed, 4 May 2016 09:00:05 +0100 Subject: add missing NIDs and use Nid as input to signing --- openssl/src/crypto/rsa.rs | 27 ++++------------------ openssl/src/nid.rs | 58 ++++++++++++++++++++++++++++++++--------------- 2 files changed, 45 insertions(+), 40 deletions(-) (limited to 'openssl/src') diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index ada5f1c1..f9d1dece 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -6,24 +6,7 @@ use std::io::{self, Read}; use bn::BigNum; use bio::MemBio; - -#[derive(Copy, Clone, Debug)] -pub enum PKCSHashType { - SHA256, - SHA384, - SHA512 -} - -/// https://github.com/openssl/openssl/blob/master/include/openssl/obj_mac.h#L2790 -impl Into for PKCSHashType { - fn into(self) -> i32 { - match self { - PKCSHashType::SHA256 => 672, - PKCSHashType::SHA384 => 673, - PKCSHashType::SHA512 => 674 - } - } -} +use nid::Nid; pub struct RSA(*mut ffi::RSA); @@ -109,13 +92,13 @@ impl RSA { } } - pub fn sign(&self, hash_id: PKCSHashType, message: &[u8]) -> Result, SslError> { + pub fn sign(&self, hash_id: Nid, message: &[u8]) -> Result, SslError> { let k_len = try!(self.size()); let mut sig = vec![0;k_len as usize]; let mut sig_len = k_len; unsafe { - let result = ffi::RSA_sign(hash_id.into(), message.as_ptr(), message.len() as u32, sig.as_mut_ptr(), &mut sig_len, self.0); + let result = ffi::RSA_sign(hash_id as i32, message.as_ptr(), message.len() as u32, sig.as_mut_ptr(), &mut sig_len, self.0); assert!(sig_len == k_len); if result == 1 { @@ -126,9 +109,9 @@ impl RSA { } } - pub fn verify(&self, hash_id: PKCSHashType, message: &[u8], sig: &[u8]) -> Result { + pub fn verify(&self, hash_id: Nid, message: &[u8], sig: &[u8]) -> Result { unsafe { - let result = ffi::RSA_verify(hash_id.into(), message.as_ptr(), message.len() as u32, sig.as_ptr(), sig.len() as u32, self.0); + let result = ffi::RSA_verify(hash_id as i32, message.as_ptr(), message.len() as u32, sig.as_ptr(), sig.len() as u32, self.0); Ok(result == 1) } diff --git a/openssl/src/nid.rs b/openssl/src/nid.rs index bfcae15a..21ef18e0 100644 --- a/openssl/src/nid.rs +++ b/openssl/src/nid.rs @@ -2,7 +2,7 @@ #[derive(Copy, Clone, Hash, PartialEq, Eq)] #[repr(usize)] pub enum Nid { - Undefined, + Undefined, // 0 Rsadsi, Pkcs, MD2, @@ -12,7 +12,7 @@ pub enum Nid { RsaEncryption, RSA_MD2, RSA_MD5, - PBE_MD2_DES, + PBE_MD2_DES, // 10 X500, x509, CN, @@ -22,7 +22,7 @@ pub enum Nid { O, OU, RSA, - Pkcs7, + Pkcs7, // 20 Pkcs7_data, Pkcs7_signedData, Pkcs7_envelopedData, @@ -32,7 +32,7 @@ pub enum Nid { Pkcs3, DhKeyAgreement, DES_ECB, - DES_CFB, + DES_CFB, // 30 DES_CBC, DES_EDE, DES_EDE3, @@ -42,7 +42,7 @@ pub enum Nid { RC2_CBC, RC2_ECB, RC2_CFB, - RC2_OFB, + RC2_OFB, // 40 SHA, RSA_SHA, DES_EDE_CBC, @@ -52,7 +52,7 @@ pub enum Nid { Pkcs9, Email, UnstructuredName, - ContentType, + ContentType, // 50 MessageDigest, SigningTime, CounterSignature, @@ -62,7 +62,7 @@ pub enum Nid { Netscape, NetscapeCertExtention, NetscapeDatatype, - DES_EDE_CFB64, + DES_EDE_CFB64, // 60 DES_EDE3_CFB64, DES_EDE_OFB64, DES_EDE3_OFB64, @@ -72,7 +72,7 @@ pub enum Nid { DSA_OLD, PBE_SHA1_RC2_64, PBKDF2, - DSA_SHA1_OLD, + DSA_SHA1_OLD, // 70 NetscapeCertType, NetscapeBaseUrl, NetscapeRevocationUrl, @@ -82,7 +82,7 @@ pub enum Nid { NetscapeSSLServerName, NetscapeComment, NetscapeCertSequence, - DESX_CBC, + DESX_CBC, // 80 ID_CE, SubjectKeyIdentifier, KeyUsage, @@ -92,7 +92,7 @@ pub enum Nid { BasicConstraints, CrlNumber, CertificatePolicies, - AuthorityKeyIdentifier, + AuthorityKeyIdentifier, // 90 BF_CBC, BF_ECB, BF_CFB, @@ -102,7 +102,7 @@ pub enum Nid { RC4_40, RC2_40_CBC, G, - S, + S, // 100 I, /// uniqueIdentifier UID, @@ -113,7 +113,7 @@ pub enum Nid { D, CAST5_CBC, CAST5_ECB, - CAST5_CFB, + CAST5_CFB, // 110 CAST5_OFB, PbeWithMD5AndCast5CBC, DSA_SHA1, @@ -123,7 +123,7 @@ pub enum Nid { RIPEMD160, // 118 missing RSA_RIPEMD160 = 119, - RC5_CBC, + RC5_CBC, // 120 RC5_ECB, RC5_CFB, RC5_OFB, @@ -133,7 +133,7 @@ pub enum Nid { PKIX, ID_KP, ServerAuth, - ClientAuth, + ClientAuth, // 130 CodeSigning, EmailProtection, TimeStamping, @@ -143,7 +143,7 @@ pub enum Nid { MsSGC, MsEFS, NsSGC, - DeltaCRL, + DeltaCRL, // 140 CRLReason, InvalidityDate, SXNetID, @@ -153,7 +153,7 @@ pub enum Nid { PBE_SHA1_2DES, PBE_SHA1_RC2_128, PBE_SHA1_RC2_40, - KeyBag, + KeyBag, // 150 Pkcs8ShroudedKeyBag, CertBag, CrlBag, @@ -163,7 +163,7 @@ pub enum Nid { LocalKeyID, X509Certificate, SdsiCertificate, - X509Crl, + X509Crl, // 160 PBES2, PBMAC1, HmacWithSha1, @@ -171,6 +171,28 @@ pub enum Nid { 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 + + // 181 and up are from openssl's obj_mac.h + + /// Shown as UID in cert subject - UserId = 458 + UserId = 458, + + + SHA256 = 672, + SHA384, + SHA512, } -- cgit v1.2.3 From 78122a9d686e23c8d5cab21a26fb3061c550bcec Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Thu, 5 May 2016 13:32:27 -0700 Subject: Release v0.7.11 --- openssl/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'openssl/src') diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index 63926615..f3be24b1 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.7.10")] +#![doc(html_root_url="https://sfackler.github.io/rust-openssl/doc/v0.7.11")] #![cfg_attr(feature = "nightly", feature(const_fn))] #[macro_use] -- cgit v1.2.3 From f82a1c4f75208c414a24deb2a6d90e0fc3981637 Mon Sep 17 00:00:00 2001 From: Chris Dawes Date: Thu, 5 May 2016 23:41:55 +0100 Subject: add rsa signature tests --- openssl/src/crypto/rsa.rs | 109 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 108 insertions(+), 1 deletion(-) (limited to 'openssl/src') diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index f9d1dece..021d450b 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -2,7 +2,7 @@ use ffi; use std::fmt; use ssl::error::{SslError, StreamError}; use std::ptr; -use std::io::{self, Read}; +use std::io::{self, Read, Write}; use bn::BigNum; use bio::MemBio; @@ -65,6 +65,25 @@ impl RSA { Ok(RSA(rsa)) } } + + /// Writes an RSA private key as unencrypted PEM formatted data + pub fn private_key_to_pem(&self, writer: &mut W) -> Result<(), SslError> + where W: Write + { + let mut mem_bio = try!(MemBio::new()); + + let result = unsafe { + ffi::PEM_write_bio_RSAPrivateKey(mem_bio.get_handle(), self.0, ptr::null(), ptr::null_mut(), 0, None, ptr::null_mut()) + }; + + 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. pub fn public_key_from_pem(reader: &mut R) -> Result @@ -82,6 +101,25 @@ impl RSA { } } + /// Writes an RSA public key as PEM formatted data + pub fn public_key_to_pem(&self, writer: &mut W) -> Result<(), SslError> + where W: Write + { + let mut mem_bio = try!(MemBio::new()); + + let result = unsafe { + 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)); + + Ok(()) + } else { + Err(SslError::OpenSslErrors(vec![])) + } + } + pub fn size(&self) -> Result { if self.has_n() { unsafe { @@ -170,3 +208,72 @@ impl fmt::Debug for RSA { write!(f, "RSA") } } + +#[cfg(test)] +mod test { + use nid; + use std::fs::File; + use std::io::Write; + 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 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(nid::Nid::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(nid::Nid::SHA256, &digest, &signature_rs256()).unwrap(); + + assert!(result); + } +} \ No newline at end of file -- cgit v1.2.3 From 62c29b54c1723d19627082df52b451986a130b79 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 15 May 2016 22:11:10 -0700 Subject: Update cert Now with a 10 year expriation --- openssl/src/ssl/tests/mod.rs | 14 +++++++------- openssl/src/x509/tests.rs | 14 +++++--------- 2 files changed, 12 insertions(+), 16 deletions(-) (limited to 'openssl/src') diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index c3e7a363..ccdc44e4 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -196,7 +196,7 @@ macro_rules! run_test( use ssl::SslMethod; use ssl::{SslContext, Ssl, SslStream, VerifyCallback}; use ssl::SSL_VERIFY_PEER; - use crypto::hash::Type::SHA256; + use crypto::hash::Type::SHA1; use x509::X509StoreContext; use serialize::hex::FromHex; use super::Server; @@ -359,7 +359,7 @@ run_test!(verify_callback_data, |method, stream| { match cert { None => false, Some(cert) => { - let fingerprint = cert.fingerprint(SHA256).unwrap(); + let fingerprint = cert.fingerprint(SHA1).unwrap(); &fingerprint == node_id } } @@ -370,7 +370,7 @@ run_test!(verify_callback_data, |method, stream| { // 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 = "db400bb62f1b1f29c3b8f323b8f7d9dea724fdcd67104ef549c772ae3749655b"; + let node_hash_str = "E19427DAC79FBE758394945276A6E4F15F0BEBE6"; let node_id = node_hash_str.from_hex().unwrap(); ctx.set_verify_with_data(SSL_VERIFY_PEER, callback, node_id); ctx.set_verify_depth(1); @@ -390,14 +390,14 @@ run_test!(ssl_verify_callback, |method, stream| { let ctx = SslContext::new(method).unwrap(); let mut ssl = ctx.into_ssl().unwrap(); - let node_hash_str = "db400bb62f1b1f29c3b8f323b8f7d9dea724fdcd67104ef549c772ae3749655b"; + let node_hash_str = "E19427DAC79FBE758394945276A6E4F15F0BEBE6"; let node_id = node_hash_str.from_hex().unwrap(); ssl.set_verify_callback(SSL_VERIFY_PEER, move |_, x509| { CHECKED.store(1, Ordering::SeqCst); match x509.get_current_cert() { None => false, Some(cert) => { - let fingerprint = cert.fingerprint(SHA256).unwrap(); + let fingerprint = cert.fingerprint(SHA1).unwrap(); fingerprint == node_id } } @@ -502,8 +502,8 @@ run_test!(get_peer_certificate, |method, stream| { let stream = SslStream::connect_generic(&SslContext::new(method).unwrap(), stream).unwrap(); let cert = stream.ssl().peer_certificate().unwrap(); - let fingerprint = cert.fingerprint(SHA256).unwrap(); - let node_hash_str = "db400bb62f1b1f29c3b8f323b8f7d9dea724fdcd67104ef549c772ae3749655b"; + let fingerprint = cert.fingerprint(SHA1).unwrap(); + let node_hash_str = "E19427DAC79FBE758394945276A6E4F15F0BEBE6"; let node_id = node_hash_str.from_hex().unwrap(); assert_eq!(node_id, fingerprint) }); diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index 0032d108..744aba9e 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -3,7 +3,7 @@ use std::io; use std::path::Path; use std::fs::File; -use crypto::hash::Type::SHA256; +use crypto::hash::Type::SHA1; use crypto::pkey::PKey; use x509::{X509, X509Generator}; use x509::extension::Extension::{KeyUsage, ExtKeyUsage, SubjectAltName, OtherNid, OtherStr}; @@ -17,7 +17,7 @@ fn get_generator() -> X509Generator { .set_bitlength(2048) .set_valid_period(365 * 2) .add_name("CN".to_string(), "test_me".to_string()) - .set_sign_hash(SHA256) + .set_sign_hash(SHA1) .add_extension(KeyUsage(vec![DigitalSignature, KeyEncipherment])) .add_extension(ExtKeyUsage(vec![ClientAuth, ServerAuth, @@ -83,13 +83,9 @@ fn test_cert_loading() { .expect("Failed to open `test/cert.pem`"); let cert = X509::from_pem(&mut file).ok().expect("Failed to load PEM"); - let fingerprint = cert.fingerprint(SHA256).unwrap(); + let fingerprint = cert.fingerprint(SHA1).unwrap(); - // Hash 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 hash_str = "db400bb62f1b1f29c3b8f323b8f7d9dea724fdcd67104ef549c772ae3749655b"; + let hash_str = "E19427DAC79FBE758394945276A6E4F15F0BEBE6"; let hash_vec = hash_str.from_hex().unwrap(); assert_eq!(fingerprint, hash_vec); @@ -109,7 +105,7 @@ fn test_subject_read_cn() { None => panic!("Failed to read CN from cert"), }; - assert_eq!(&cn as &str, "test_cert") + assert_eq!(&cn as &str, "foobar.com") } #[test] -- cgit v1.2.3 From 2077449bc87b87f96c8ec6248c5c7060d4bc58bf Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 16 May 2016 23:02:02 -0700 Subject: Clean up RSA signature API --- openssl/src/crypto/hash.rs | 48 ++++++++++++++++++++++++++++++---------------- openssl/src/crypto/mod.rs | 6 ++++++ openssl/src/crypto/pkey.rs | 18 ++++------------- openssl/src/crypto/rsa.rs | 19 +++++++++--------- openssl/src/nid.rs | 1 + 5 files changed, 52 insertions(+), 40 deletions(-) (limited to 'openssl/src') 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/mod.rs b/openssl/src/crypto/mod.rs index bb77453f..95b27022 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; @@ -24,3 +26,7 @@ pub mod memcmp; pub mod rsa; 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 ba0a16b6..a97da55b 100644 --- a/openssl/src/crypto/pkey.rs +++ b/openssl/src/crypto/pkey.rs @@ -5,6 +5,8 @@ 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; @@ -41,18 +43,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, @@ -556,7 +546,7 @@ impl PKey { let mut r = repeat(0u8).take(len as usize + 1).collect::>(); 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(), @@ -579,7 +569,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(), diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index 021d450b..33385687 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -3,10 +3,12 @@ use std::fmt; use ssl::error::{SslError, StreamError}; use std::ptr; use std::io::{self, Read, Write}; +use libc::c_int; use bn::BigNum; use bio::MemBio; -use nid::Nid; +use crypto::HashTypeInternals; +use crypto::hash; pub struct RSA(*mut ffi::RSA); @@ -130,13 +132,13 @@ impl RSA { } } - pub fn sign(&self, hash_id: Nid, message: &[u8]) -> Result, SslError> { + pub fn sign(&self, hash: hash::Type, message: &[u8]) -> Result, SslError> { let k_len = try!(self.size()); let mut sig = vec![0;k_len as usize]; let mut sig_len = k_len; unsafe { - let result = ffi::RSA_sign(hash_id as i32, 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); if result == 1 { @@ -147,9 +149,9 @@ impl RSA { } } - pub fn verify(&self, hash_id: Nid, message: &[u8], sig: &[u8]) -> Result { + pub fn verify(&self, hash: hash::Type, message: &[u8], sig: &[u8]) -> Result { unsafe { - let result = ffi::RSA_verify(hash_id as i32, 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) } @@ -211,7 +213,6 @@ impl fmt::Debug for RSA { #[cfg(test)] mod test { - use nid; use std::fs::File; use std::io::Write; use super::*; @@ -258,7 +259,7 @@ mod test { sha.write_all(&signing_input_rs256()).unwrap(); let digest = sha.finish(); - let result = private_key.sign(nid::Nid::SHA256, &digest).unwrap(); + let result = private_key.sign(Type::SHA256, &digest).unwrap(); assert_eq!(result, signature_rs256()); } @@ -272,8 +273,8 @@ mod test { sha.write_all(&signing_input_rs256()).unwrap(); let digest = sha.finish(); - let result = public_key.verify(nid::Nid::SHA256, &digest, &signature_rs256()).unwrap(); + let result = public_key.verify(Type::SHA256, &digest, &signature_rs256()).unwrap(); assert!(result); } -} \ No newline at end of file +} diff --git a/openssl/src/nid.rs b/openssl/src/nid.rs index 21ef18e0..780b8a00 100644 --- a/openssl/src/nid.rs +++ b/openssl/src/nid.rs @@ -195,4 +195,5 @@ pub enum Nid { SHA256 = 672, SHA384, SHA512, + SHA224, } -- cgit v1.2.3 From 1b0757409d634f67b37d4c35af8fec878c2ecc27 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 16 May 2016 23:03:00 -0700 Subject: Rustfmt --- openssl/src/crypto/hmac.rs | 3 +- openssl/src/crypto/pkey.rs | 21 +++-- openssl/src/crypto/rsa.rs | 210 +++++++++++++++++++++---------------------- openssl/src/nid.rs | 5 +- openssl/src/ssl/bio.rs | 31 ++++--- openssl/src/ssl/mod.rs | 45 ++++++---- openssl/src/ssl/tests/mod.rs | 26 +++--- openssl/src/version.rs | 3 +- openssl/src/x509/mod.rs | 20 ++--- openssl/src/x509/tests.rs | 16 ++-- 10 files changed, 198 insertions(+), 182 deletions(-) (limited to 'openssl/src') 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, 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()), + (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/pkey.rs b/openssl/src/crypto/pkey.rs index a97da55b..c4111860 100644 --- a/openssl/src/crypto/pkey.rs +++ b/openssl/src/crypto/pkey.rs @@ -114,7 +114,7 @@ impl PKey { /// Reads an RSA private key from PEM, takes ownership of handle pub fn private_rsa_key_from_pem(reader: &mut R) -> Result - where R: Read + where R: Read { let rsa = try!(RSA::private_key_from_pem(reader)); unsafe { @@ -130,7 +130,7 @@ impl PKey { /// Reads an RSA public key from PEM, takes ownership of handle pub fn public_rsa_key_from_pem(reader: &mut R) -> Result - where R: Read + where R: Read { let rsa = try!(RSA::public_key_from_pem(reader)); unsafe { @@ -600,16 +600,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 } @@ -684,8 +683,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(); } @@ -694,8 +693,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 33385687..52b8590e 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -31,8 +31,16 @@ impl 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 { + + pub fn from_private_components(n: BigNum, + e: BigNum, + d: BigNum, + p: BigNum, + q: BigNum, + dp: BigNum, + dq: BigNum, + qi: BigNum) + -> Result { unsafe { let rsa = try_ssl_null!(ffi::RSA_new()); (*rsa).n = n.into_raw(); @@ -54,7 +62,7 @@ impl RSA { /// Reads an RSA private key from PEM formatted data. pub fn private_key_from_pem(reader: &mut R) -> Result - where R: Read + where R: Read { let mut mem_bio = try!(MemBio::new()); try!(io::copy(reader, &mut mem_bio).map_err(StreamError)); @@ -67,29 +75,35 @@ impl RSA { Ok(RSA(rsa)) } } - + /// Writes an RSA private key as unencrypted PEM formatted data pub fn private_key_to_pem(&self, writer: &mut W) -> Result<(), SslError> - where W: Write + where W: Write { - let mut mem_bio = try!(MemBio::new()); - - let result = unsafe { - ffi::PEM_write_bio_RSAPrivateKey(mem_bio.get_handle(), self.0, ptr::null(), ptr::null_mut(), 0, None, ptr::null_mut()) - }; - - if result == 1 { - try!(io::copy(&mut mem_bio, writer).map_err(StreamError)); - - Ok(()) - } else { - Err(SslError::OpenSslErrors(vec![])) - } + let mut mem_bio = try!(MemBio::new()); + + let result = unsafe { + ffi::PEM_write_bio_RSAPrivateKey(mem_bio.get_handle(), + self.0, + ptr::null(), + ptr::null_mut(), + 0, + None, + ptr::null_mut()) + }; + + 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. pub fn public_key_from_pem(reader: &mut R) -> Result - where R: Read + where R: Read { let mut mem_bio = try!(MemBio::new()); try!(io::copy(reader, &mut mem_bio).map_err(StreamError)); @@ -102,45 +116,46 @@ impl RSA { Ok(RSA(rsa)) } } - + /// Writes an RSA public key as PEM formatted data pub fn public_key_to_pem(&self, writer: &mut W) -> Result<(), SslError> - where W: Write + where W: Write { - let mut mem_bio = try!(MemBio::new()); - - let result = unsafe { - 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)); - - Ok(()) - } else { - Err(SslError::OpenSslErrors(vec![])) - } + let mut mem_bio = try!(MemBio::new()); + + let result = unsafe { 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)); + + Ok(()) + } else { + Err(SslError::OpenSslErrors(vec![])) + } } - + pub fn size(&self) -> Result { if self.has_n() { - unsafe { - Ok(ffi::RSA_size(self.0) as u32) - } + unsafe { Ok(ffi::RSA_size(self.0) as u32) } } else { Err(SslError::OpenSslErrors(vec![])) } } - + pub fn sign(&self, hash: hash::Type, message: &[u8]) -> Result, SslError> { let k_len = try!(self.size()); let mut sig = vec![0;k_len as usize]; let mut sig_len = k_len; - + 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); - + if result == 1 { Ok(sig) } else { @@ -148,14 +163,19 @@ impl RSA { } } } - + pub fn verify(&self, hash: hash::Type, message: &[u8], sig: &[u8]) -> Result { 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) } - } + } pub fn as_ptr(&self) -> *mut ffi::RSA { self.0 @@ -163,45 +183,31 @@ impl RSA { // The following getters are unsafe, since BigNum::new_from_ffi fails upon null pointers pub fn n(&self) -> Result { - unsafe { - BigNum::new_from_ffi((*self.0).n) - } + unsafe { BigNum::new_from_ffi((*self.0).n) } } pub fn has_n(&self) -> bool { - unsafe { - !(*self.0).n.is_null() - } + unsafe { !(*self.0).n.is_null() } } pub fn d(&self) -> Result { - unsafe { - BigNum::new_from_ffi((*self.0).d) - } + unsafe { BigNum::new_from_ffi((*self.0).d) } } pub fn e(&self) -> Result { - unsafe { - BigNum::new_from_ffi((*self.0).e) - } + unsafe { BigNum::new_from_ffi((*self.0).e) } } pub fn has_e(&self) -> bool { - unsafe { - !(*self.0).e.is_null() - } + unsafe { !(*self.0).e.is_null() } } pub fn p(&self) -> Result { - unsafe { - BigNum::new_from_ffi((*self.0).p) - } + unsafe { BigNum::new_from_ffi((*self.0).p) } } pub fn q(&self) -> Result { - unsafe { - BigNum::new_from_ffi((*self.0).q) - } + unsafe { BigNum::new_from_ffi((*self.0).q) } } } @@ -217,64 +223,58 @@ mod test { use std::io::Write; 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] + 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] - } - + 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() { + 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); } } diff --git a/openssl/src/nid.rs b/openssl/src/nid.rs index 780b8a00..874d4a6f 100644 --- a/openssl/src/nid.rs +++ b/openssl/src/nid.rs @@ -184,14 +184,11 @@ pub enum Nid { OCSP, CaIssuers, 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 UserId = 458, - SHA256 = 672, SHA384, SHA512, diff --git a/openssl/src/ssl/bio.rs b/openssl/src/ssl/bio.rs index e53545d7..b6f20cf2 100644 --- a/openssl/src/ssl/bio.rs +++ b/openssl/src/ssl/bio.rs @@ -23,16 +23,16 @@ pub struct BioMethod(ffi::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, + 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, }) } } @@ -82,12 +82,16 @@ unsafe fn state<'a, S: 'a>(bio: *mut BIO) -> &'a mut StreamState { } #[cfg(feature = "nightly")] -fn catch_unwind(f: F) -> Result> where F: FnOnce() -> T { +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 { +fn catch_unwind(f: F) -> Result> + where F: FnOnce() -> T +{ Ok(f()) } @@ -137,7 +141,8 @@ unsafe extern "C" fn bread(bio: *mut BIO, buf: *mut c_char, len: c_int) fn retriable_error(err: &io::Error) -> bool { match err.kind() { - io::ErrorKind::WouldBlock | io::ErrorKind::NotConnected => true, + io::ErrorKind::WouldBlock | + io::ErrorKind::NotConnected => true, _ => false, } } diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index aa785142..f207416f 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -850,7 +850,7 @@ pub struct SslCipher<'a> { ph: PhantomData<&'a ()>, } -impl <'a> SslCipher<'a> { +impl<'a> SslCipher<'a> { /// Returns the name of cipher. pub fn name(&self) -> &'static str { let name = unsafe { @@ -874,12 +874,18 @@ 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 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) } + CipherBits { + secret: secret_bits, + algorithm: Some(*algo_bits), + } } else { - CipherBits { secret: secret_bits, algorithm: None } + CipherBits { + secret: secret_bits, + algorithm: None, + } } } } @@ -987,7 +993,9 @@ impl Ssl { { unsafe { let verify = Box::new(verify); - ffi::SSL_set_ex_data(self.ssl, get_ssl_verify_data_idx::(), mem::transmute(verify)); + ffi::SSL_set_ex_data(self.ssl, + get_ssl_verify_data_idx::(), + mem::transmute(verify)); ffi::SSL_set_verify(self.ssl, mode.bits as c_int, Some(ssl_raw_verify::)); } } @@ -999,7 +1007,10 @@ impl Ssl { if ptr.is_null() { None } 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. pub fn version(&self) -> &'static str { let version = unsafe { - let ptr = ffi::SSL_get_version(self.ssl); - CStr::from_ptr(ptr as *const _) + let ptr = ffi::SSL_get_version(self.ssl); + CStr::from_ptr(ptr as *const _) }; str::from_utf8(version.to_bytes()).unwrap() @@ -1224,7 +1235,8 @@ impl Clone for SslStream { } } -impl fmt::Debug for SslStream where S: fmt::Debug +impl fmt::Debug for SslStream + where S: fmt::Debug { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("SslStream") @@ -1385,7 +1397,8 @@ impl SslStream { } } LibSslError::ErrorZeroReturn => Some(SslError::SslSessionClosed), - LibSslError::ErrorWantWrite | LibSslError::ErrorWantRead => None, + LibSslError::ErrorWantWrite | + LibSslError::ErrorWantRead => None, err => { Some(SslError::StreamError(io::Error::new(io::ErrorKind::Other, format!("unexpected error {:?}", err)))) @@ -1401,8 +1414,7 @@ impl SslStream { } #[cfg(not(feature = "nightly"))] - fn check_panic(&mut self) { - } + fn check_panic(&mut self) {} fn get_bio_error(&mut self) -> io::Error { let error = unsafe { bio::take_error::(self.ssl.get_raw_rbio()) }; @@ -1513,7 +1525,8 @@ pub enum MaybeSslStream Normal(S), } -impl Read for MaybeSslStream where S: Read + Write +impl Read for MaybeSslStream + where S: Read + Write { fn read(&mut self, buf: &mut [u8]) -> io::Result { match *self { @@ -1523,7 +1536,8 @@ impl Read for MaybeSslStream where S: Read + Write } } -impl Write for MaybeSslStream where S: Read + Write +impl Write for MaybeSslStream + where S: Read + Write { fn write(&mut self, buf: &[u8]) -> io::Result { match *self { @@ -1540,7 +1554,8 @@ impl Write for MaybeSslStream where S: Read + Write } } -impl MaybeSslStream where S: Read + Write +impl MaybeSslStream + where S: Read + Write { /// Returns a reference to the underlying stream. pub fn get_ref(&self) -> &S { diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index ccdc44e4..5339f27e 100644 --- a/openssl/src/ssl/tests/mod.rs +++ b/openssl/src/ssl/tests/mod.rs @@ -236,7 +236,7 @@ run_test!(verify_untrusted, |method, stream| { match SslStream::connect_generic(&ctx, stream) { 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")) { Ok(_) => {} - Err(err) => panic!("Unexpected error {:?}", err) + Err(err) => panic!("Unexpected error {:?}", err), } match SslStream::connect_generic(&ctx, stream) { 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) { 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")) { Ok(_) => {} - Err(err) => panic!("Unexpected error {:?}", err) + Err(err) => panic!("Unexpected error {:?}", err), } match SslStream::connect_generic(&ctx, stream) { 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")) { Ok(_) => {} - Err(err) => panic!("Unexpected error {:?}", err) + Err(err) => panic!("Unexpected error {:?}", 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")) { Ok(_) => {} - Err(err) => panic!("Unexpected error {:?}", err) + Err(err) => panic!("Unexpected error {:?}", err), } 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| { - fn callback(_preverify_ok: bool, x509_ctx: &X509StoreContext, - node_id: &Vec) -> bool { + fn callback(_preverify_ok: bool, x509_ctx: &X509StoreContext, node_id: &Vec) -> bool { let cert = x509_ctx.get_current_cert(); match cert { None => false, @@ -377,7 +376,7 @@ run_test!(verify_callback_data, |method, stream| { match SslStream::connect_generic(&ctx, stream) { 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) { Ok(_) => (), - Err(err) => panic!("Expected success, got {:?}", err) + Err(err) => panic!("Expected success, got {:?}", err), } assert_eq!(CHECKED.load(Ordering::SeqCst), 1); @@ -499,8 +498,7 @@ fn test_write_direct() { } run_test!(get_peer_certificate, |method, stream| { - let stream = SslStream::connect_generic(&SslContext::new(method).unwrap(), - stream).unwrap(); + let stream = SslStream::connect_generic(&SslContext::new(method).unwrap(), stream).unwrap(); let cert = stream.ssl().peer_certificate().unwrap(); let fingerprint = cert.fingerprint(SHA1).unwrap(); let node_hash_str = "E19427DAC79FBE758394945276A6E4F15F0BEBE6"; diff --git a/openssl/src/version.rs b/openssl/src/version.rs index 323cf1e2..0e9f61d8 100644 --- a/openssl/src/version.rs +++ b/openssl/src/version.rs @@ -1,4 +1,3 @@ -// // 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 @@ -86,4 +85,4 @@ fn test_versions() { assert!(c_flags().starts_with("compiler:")); assert!(built_on().starts_with("built on:")); assert!(dir().starts_with("OPENSSLDIR:")); -} \ No newline at end of file +} diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 0a242a15..3150cc6e 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -379,7 +379,9 @@ impl X509Generator { ffi::X509_set_issuer_name(x509.handle, name); 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(); @@ -539,9 +541,9 @@ extern "C" { impl<'ctx> Clone for X509<'ctx> { fn clone(&self) -> X509<'ctx> { unsafe { rust_X509_clone(self.handle) } - /* 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 - */ + // 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 + // X509::new(self.handle, true) } } @@ -671,7 +673,7 @@ impl Extensions { pub fn add(&mut self, ext: Extension) { 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; return; } @@ -693,7 +695,7 @@ impl Extensions { /// extension in the collection. struct ExtensionsIter<'a> { current: usize, - extensions: &'a Vec + extensions: &'a Vec, } impl<'a> Iterator for ExtensionsIter<'a> { @@ -798,9 +800,7 @@ pub struct GeneralNames<'a> { impl<'a> GeneralNames<'a> { /// Returns the number of `GeneralName`s in this structure. pub fn len(&self) -> usize { - unsafe { - (*self.stack).stack.num as usize - } + unsafe { (*self.stack).stack.num as usize } } /// Returns the specified `GeneralName`. @@ -823,7 +823,7 @@ impl<'a> GeneralNames<'a> { pub fn iter(&self) -> GeneralNamesIter { GeneralNamesIter { names: self, - idx: 0 + idx: 0, } } } diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index 744aba9e..f547a982 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -56,9 +56,10 @@ fn test_cert_gen_extension_ordering() { #[test] fn test_cert_gen_extension_bad_ordering() { let result = get_generator() - .add_extension(OtherNid(Nid::AuthorityKeyIdentifier, "keyid:always".to_owned())) - .add_extension(OtherNid(Nid::SubjectKeyIdentifier, "hash".to_owned())) - .generate(); + .add_extension(OtherNid(Nid::AuthorityKeyIdentifier, + "keyid:always".to_owned())) + .add_extension(OtherNid(Nid::SubjectKeyIdentifier, "hash".to_owned())) + .generate(); assert!(result.is_err()); } @@ -162,7 +163,8 @@ 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(), 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(), 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 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().ipaddress(), Some(&[127, 0, 0, 1][..])); + assert_eq!(subject_alt_names_iter.next().unwrap().dnsname(), + 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(), 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()); -- cgit v1.2.3 From 95051b060d5701d5c2282d92a7d9d955852e1e30 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 16 May 2016 23:04:03 -0700 Subject: Release v0.7.12 --- openssl/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'openssl/src') diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index f3be24b1..474e0b9a 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.7.11")] +#![doc(html_root_url="https://sfackler.github.io/rust-openssl/doc/v0.7.12")] #![cfg_attr(feature = "nightly", feature(const_fn))] #[macro_use] -- cgit v1.2.3 From f6b612df5f32088b16d1252822f4cd7d4596c71c Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 20 May 2016 15:57:57 -0700 Subject: Release v0.7.13 --- openssl/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'openssl/src') diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index 474e0b9a..91477303 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.7.12")] +#![doc(html_root_url="https://sfackler.github.io/rust-openssl/doc/v0.7.13")] #![cfg_attr(feature = "nightly", feature(const_fn))] #[macro_use] -- cgit v1.2.3 From f134b94729770d5338689642d0e6f72a630aa397 Mon Sep 17 00:00:00 2001 From: Jonas Schievink Date: Mon, 13 Jun 2016 16:56:48 +0200 Subject: Document BigNum --- openssl/src/bn/mod.rs | 169 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 169 insertions(+) (limited to 'openssl/src') diff --git a/openssl/src/bn/mod.rs b/openssl/src/bn/mod.rs index d548e9ef..5054f0ab 100644 --- a/openssl/src/bn/mod.rs +++ b/openssl/src/bn/mod.rs @@ -6,13 +6,23 @@ use std::{fmt, ptr, mem}; use ffi; use ssl::error::SslError; +/// A 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); +/// 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, } @@ -70,6 +80,7 @@ macro_rules! with_bn_in_ctx( ); impl BigNum { + /// Creates a new `BigNum` with the value 0. pub fn new() -> Result { unsafe { ffi::init(); @@ -79,6 +90,7 @@ impl BigNum { } } + /// Creates a new `BigNum` with the given value. pub fn new_from(n: u64) -> Result { BigNum::new().and_then(|v| unsafe { try_ssl!(ffi::BN_set_word(v.raw(), n as c_ulong)); @@ -86,6 +98,7 @@ impl BigNum { }) } + /// Creates a `BigNum` from a decimal string. pub fn from_dec_str(s: &str) -> Result { BigNum::new().and_then(|v| unsafe { let c_str = CString::new(s.as_bytes()).unwrap(); @@ -94,6 +107,7 @@ impl BigNum { }) } + /// Creates a `BigNum` from a hexadecimal string. pub fn from_hex_str(s: &str) -> Result { BigNum::new().and_then(|v| unsafe { let c_str = CString::new(s.as_bytes()).unwrap(); @@ -114,6 +128,14 @@ impl BigNum { } } + /// Creates a new `BigNum` from an unsigned, big-endian encoded number of arbitrary length. + /// + /// ``` + /// # use openssl::bn::BigNum; + /// let bignum = BigNum::new_from_slice(&[0x12, 0x00, 0x34]).unwrap(); + /// + /// 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.raw())); @@ -121,6 +143,16 @@ impl BigNum { }) } + /// 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 { unsafe { with_bn_in_ctx!(r, ctx, { @@ -129,6 +161,7 @@ impl BigNum { } } + /// Returns the unsigned remainder of the division `self / n`. pub fn checked_nnmod(&self, n: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { @@ -137,6 +170,17 @@ impl BigNum { } } + /// 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: &BigNum, n: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { @@ -145,6 +189,7 @@ impl BigNum { } } + /// Equivalent to `(self - a) mod n`. pub fn checked_mod_sub(&self, a: &BigNum, n: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { @@ -153,6 +198,7 @@ impl BigNum { } } + /// Equivalent to `(self * a) mod n`. pub fn checked_mod_mul(&self, a: &BigNum, n: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { @@ -161,6 +207,7 @@ impl BigNum { } } + /// Equivalent to `self² mod n`. pub fn checked_mod_sqr(&self, n: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { @@ -169,6 +216,7 @@ impl BigNum { } } + /// Raises `self` to the `p`th power. pub fn checked_exp(&self, p: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { @@ -177,6 +225,7 @@ impl BigNum { } } + /// Equivalent to `self.checked_exp(p) mod n`. pub fn checked_mod_exp(&self, p: &BigNum, n: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { @@ -185,6 +234,8 @@ impl BigNum { } } + /// 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: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { @@ -193,6 +244,7 @@ impl BigNum { } } + /// Add an `unsigned long` to `self`. This is more efficient than adding a `BigNum`. pub fn add_word(&mut self, w: c_ulong) -> Result<(), SslError> { unsafe { if ffi::BN_add_word(self.raw(), w) == 1 { @@ -245,6 +297,7 @@ impl BigNum { } } + /// Computes the greatest common denominator of `self` and `a`. pub fn checked_gcd(&self, a: &BigNum) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { @@ -253,6 +306,14 @@ impl BigNum { } } + /// Generates a prime number. + /// + /// # 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 checked_generate_prime(bits: i32, safe: bool, add: Option<&BigNum>, @@ -273,6 +334,13 @@ impl BigNum { } } + /// Checks whether `self` 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 { unsafe { with_ctx!(ctx, { @@ -281,6 +349,15 @@ impl BigNum { } } + /// 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_fast(&self, checks: i32, do_trial_division: bool) -> Result { unsafe { with_ctx!(ctx, { @@ -293,6 +370,13 @@ impl BigNum { } } + /// 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, { @@ -301,6 +385,7 @@ impl BigNum { } } + /// The cryptographically weak counterpart to `checked_new_random`. pub fn checked_new_pseudo_random(bits: i32, prop: RNGProperty, odd: bool) @@ -312,6 +397,8 @@ impl BigNum { } } + /// Generates a cryptographically strong pseudo-random `BigNum` `r` in the range + /// `0 <= r < self`. pub fn checked_rand_in_range(&self) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { @@ -320,6 +407,7 @@ impl BigNum { } } + /// The cryptographically weak counterpart to `checked_rand_in_range`. pub fn checked_pseudo_rand_in_range(&self) -> Result { unsafe { with_bn_in_ctx!(r, ctx, { @@ -328,6 +416,9 @@ impl BigNum { } } + /// 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<(), SslError> { unsafe { if ffi::BN_set_bit(self.raw(), n as c_int) == 1 { @@ -338,6 +429,9 @@ impl BigNum { } } + /// 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<(), SslError> { unsafe { if ffi::BN_clear_bit(self.raw(), n as c_int) == 1 { @@ -348,10 +442,14 @@ impl BigNum { } } + /// 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.raw(), n as c_int) == 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<(), SslError> { unsafe { if ffi::BN_mask_bits(self.raw(), n as c_int) == 1 { @@ -362,6 +460,24 @@ impl BigNum { } } + /// 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 { unsafe { with_bn!(r, { @@ -370,6 +486,7 @@ impl BigNum { } } + /// Returns `self`, shifted right by 1 bit. `self` may be negative. pub fn checked_shr1(&self) -> Result { unsafe { with_bn!(r, { @@ -434,10 +551,31 @@ impl BigNum { } } + /// 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.raw(), !self.is_negative() as c_int) } } + /// Compare the absolute values of `self` and `oth`. + /// + /// ``` + /// # use openssl::bn::BigNum; + /// # use std::cmp::Ordering; + /// let s = -BigNum::new_from(8).unwrap(); + /// let o = BigNum::new_from(8).unwrap(); + /// + /// assert_eq!(s.abs_cmp(o), Ordering::Equal); + /// ``` pub fn abs_cmp(&self, oth: BigNum) -> Ordering { unsafe { let res = ffi::BN_ucmp(self.raw(), oth.raw()) as i32; @@ -455,10 +593,12 @@ impl BigNum { unsafe { (*self.raw()).neg == 1 } } + /// Returns the number of significant bits in `self`. pub fn num_bits(&self) -> i32 { unsafe { ffi::BN_num_bits(self.raw()) as i32 } } + /// Returns the size of `self` in bytes. pub fn num_bytes(&self) -> i32 { (self.num_bits() + 7) / 8 } @@ -478,6 +618,18 @@ impl BigNum { mem::replace(&mut me.0, ptr::null_mut()) } + /// Returns a big-endian byte vector representation of the absolute value of `self`. + /// + /// `self` can be recreated by using `new_from_slice`. + /// + /// ``` + /// # use openssl::bn::BigNum; + /// let s = -BigNum::new_from(4543).unwrap(); + /// let r = BigNum::new_from(4543).unwrap(); + /// + /// let s_vec = s.to_vec(); + /// assert_eq!(BigNum::new_from_slice(&s_vec).unwrap(), r); + /// ``` pub fn to_vec(&self) -> Vec { let size = self.num_bytes() as usize; let mut v = Vec::with_capacity(size); @@ -488,6 +640,14 @@ impl BigNum { v } + /// Returns a decimal string representation of `self`. + /// + /// ``` + /// # use openssl::bn::BigNum; + /// let s = -BigNum::new_from(12345).unwrap(); + /// + /// assert_eq!(s.to_dec_str(), "-12345"); + /// ``` pub fn to_dec_str(&self) -> String { unsafe { let buf = ffi::BN_bn2dec(self.raw()); @@ -499,6 +659,14 @@ impl BigNum { } } + /// Returns a hexadecimal string representation of `self`. + /// + /// ``` + /// # use openssl::bn::BigNum; + /// let s = -BigNum::new_from(0x99ff).unwrap(); + /// + /// assert_eq!(s.to_hex_str(), "-99FF"); + /// ``` pub fn to_hex_str(&self) -> String { unsafe { let buf = ffi::BN_bn2hex(self.raw()); @@ -556,6 +724,7 @@ impl Drop for BigNum { } } +#[doc(hidden)] // This module only contains impls, so it's empty when generating docs pub mod unchecked { use std::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub}; use ffi; -- cgit v1.2.3 From 311af7c3be6eac14b257a695f3c3c428ca177b08 Mon Sep 17 00:00:00 2001 From: Jonas Schievink Date: Mon, 13 Jun 2016 21:17:20 +0200 Subject: Add PKey::private_key_from_pem_cb --- openssl/src/crypto/pkey.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) (limited to 'openssl/src') diff --git a/openssl/src/crypto/pkey.rs b/openssl/src/crypto/pkey.rs index c4111860..f59ee40a 100644 --- a/openssl/src/crypto/pkey.rs +++ b/openssl/src/crypto/pkey.rs @@ -1,9 +1,11 @@ -use libc::{c_int, c_uint, c_ulong}; +use libc::{c_int, c_uint, c_ulong, c_char, c_void}; use std::io; use std::io::prelude::*; use std::iter::repeat; use std::mem; +use std::panic::catch_unwind; use std::ptr; +use std::slice; use bio::MemBio; use crypto::HashTypeInternals; @@ -93,6 +95,51 @@ 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. + pub fn private_key_from_pem_cb(reader: &mut R, mut pass_cb: F) -> Result + where R: Read, F: FnMut(&mut [i8]) -> usize + { + extern "C" fn user_cb_wrapper(buf: *mut c_char, + size: c_int, + _rwflag: c_int, + user_cb: *mut c_void) + -> c_int + where F: FnMut(&mut [i8]) -> usize { + let result = 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 *(user_cb as *mut F) }; + + callback(pass_slice) + }); + + if let Ok(len) = result { + return len as c_int; + } else { + return 0; + } + } + + 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(user_cb_wrapper::), + &mut pass_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(reader: &mut R) -> Result where R: Read -- cgit v1.2.3 From f0b4a032d5a6cdf3928318e113dcfd7e0ecf03f9 Mon Sep 17 00:00:00 2001 From: Jonas Schievink Date: Mon, 13 Jun 2016 21:47:02 +0200 Subject: Try to propagate callback panics --- openssl/src/crypto/pkey.rs | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) (limited to 'openssl/src') diff --git a/openssl/src/crypto/pkey.rs b/openssl/src/crypto/pkey.rs index f59ee40a..8ae9aa20 100644 --- a/openssl/src/crypto/pkey.rs +++ b/openssl/src/crypto/pkey.rs @@ -1,9 +1,10 @@ use libc::{c_int, c_uint, c_ulong, c_char, c_void}; +use std::any::Any; use std::io; use std::io::prelude::*; use std::iter::repeat; use std::mem; -use std::panic::catch_unwind; +use std::panic; use std::ptr; use std::slice; use bio::MemBio; @@ -100,21 +101,26 @@ impl PKey { /// /// 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(reader: &mut R, mut pass_cb: F) -> Result + pub fn private_key_from_pem_cb(reader: &mut R, pass_cb: F) -> Result where R: Read, F: FnMut(&mut [i8]) -> usize { + struct CallbackState usize> { + cb: F, + panic: Option>, + } + extern "C" fn user_cb_wrapper(buf: *mut c_char, size: c_int, _rwflag: c_int, user_cb: *mut c_void) -> c_int where F: FnMut(&mut [i8]) -> usize { - let result = catch_unwind(|| { + 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 *(user_cb as *mut F) }; + let callback = unsafe { &mut *(user_cb as *mut CallbackState) }; - callback(pass_slice) + (callback.cb)(pass_slice) }); if let Ok(len) = result { @@ -124,6 +130,11 @@ impl PKey { } } + let mut cb = CallbackState { + cb: pass_cb, + panic: None, + }; + let mut mem_bio = try!(MemBio::new()); try!(io::copy(reader, &mut mem_bio).map_err(StreamError)); @@ -131,7 +142,11 @@ impl PKey { let evp = try_ssl_null!(ffi::PEM_read_bio_PrivateKey(mem_bio.get_handle(), ptr::null_mut(), Some(user_cb_wrapper::), - &mut pass_cb as *mut _ as *mut c_void)); + &mut cb as *mut _ as *mut c_void)); + + if let Some(panic) = cb.panic { + panic::resume_unwind(panic); + } Ok(PKey { evp: evp as *mut ffi::EVP_PKEY, -- cgit v1.2.3 From 8119f06ca5ca50a677cf584cbe816500153ce783 Mon Sep 17 00:00:00 2001 From: Jonas Schievink Date: Tue, 14 Jun 2016 18:12:50 +0200 Subject: Move into utility module --- openssl/src/crypto/mod.rs | 1 + openssl/src/crypto/pkey.rs | 43 ++++------------------------------ openssl/src/crypto/util.rs | 58 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 39 deletions(-) create mode 100644 openssl/src/crypto/util.rs (limited to 'openssl/src') diff --git a/openssl/src/crypto/mod.rs b/openssl/src/crypto/mod.rs index 95b27022..9d79b8b0 100644 --- a/openssl/src/crypto/mod.rs +++ b/openssl/src/crypto/mod.rs @@ -24,6 +24,7 @@ pub mod rand; pub mod symm; pub mod memcmp; pub mod rsa; +mod util; mod symm_internal; diff --git a/openssl/src/crypto/pkey.rs b/openssl/src/crypto/pkey.rs index 8ae9aa20..605aed42 100644 --- a/openssl/src/crypto/pkey.rs +++ b/openssl/src/crypto/pkey.rs @@ -1,12 +1,9 @@ -use libc::{c_int, c_uint, c_ulong, c_char, c_void}; -use std::any::Any; +use libc::{c_int, c_uint, c_ulong, c_void}; use std::io; use std::io::prelude::*; use std::iter::repeat; use std::mem; -use std::panic; use std::ptr; -use std::slice; use bio::MemBio; use crypto::HashTypeInternals; @@ -15,6 +12,7 @@ use crypto::hash::Type as HashType; use ffi; use ssl::error::{SslError, StreamError}; use crypto::rsa::RSA; +use crypto::util::{CallbackState, invoke_passwd_cb}; #[derive(Copy, Clone)] pub enum Parts { @@ -104,36 +102,7 @@ impl PKey { pub fn private_key_from_pem_cb(reader: &mut R, pass_cb: F) -> Result where R: Read, F: FnMut(&mut [i8]) -> usize { - struct CallbackState usize> { - cb: F, - panic: Option>, - } - - extern "C" fn user_cb_wrapper(buf: *mut c_char, - size: c_int, - _rwflag: c_int, - user_cb: *mut c_void) - -> c_int - where F: FnMut(&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 *(user_cb as *mut CallbackState) }; - - (callback.cb)(pass_slice) - }); - - if let Ok(len) = result { - return len as c_int; - } else { - return 0; - } - } - - let mut cb = CallbackState { - cb: pass_cb, - panic: None, - }; + let mut cb = CallbackState::new(pass_cb); let mut mem_bio = try!(MemBio::new()); try!(io::copy(reader, &mut mem_bio).map_err(StreamError)); @@ -141,13 +110,9 @@ impl PKey { unsafe { let evp = try_ssl_null!(ffi::PEM_read_bio_PrivateKey(mem_bio.get_handle(), ptr::null_mut(), - Some(user_cb_wrapper::), + Some(invoke_passwd_cb::), &mut cb as *mut _ as *mut c_void)); - if let Some(panic) = cb.panic { - panic::resume_unwind(panic); - } - Ok(PKey { evp: evp as *mut ffi::EVP_PKEY, parts: Parts::Both, diff --git a/openssl/src/crypto/util.rs b/openssl/src/crypto/util.rs new file mode 100644 index 00000000..85df86b7 --- /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 { + /// The user callback. Taken out of the `Option` when called. + cb: Option, + /// If the callback panics, we place the panic object here, to be re-thrown once OpenSSL + /// returns. + panic: Option>, +} + +impl CallbackState { + pub fn new(callback: F) -> Self { + CallbackState { + cb: Some(callback), + panic: None, + } + } +} + +impl Drop for CallbackState { + 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(buf: *mut c_char, + size: c_int, + _rwflag: c_int, + cb_state: *mut c_void) + -> c_int + where F: FnMut(&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) }; + + callback.cb.take().unwrap()(pass_slice) + }); + + if let Ok(len) = result { + return len as c_int; + } else { + return 0; + } +} -- cgit v1.2.3 From c399c2475d71c313970dc4e3b271f0086e90b013 Mon Sep 17 00:00:00 2001 From: Jonas Schievink Date: Tue, 14 Jun 2016 18:17:25 +0200 Subject: Add RSA::private_key_from_pem_cb --- openssl/src/crypto/rsa.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) (limited to 'openssl/src') diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index 52b8590e..d451aab6 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -3,12 +3,13 @@ use std::fmt; use ssl::error::{SslError, StreamError}; use std::ptr; use std::io::{self, Read, Write}; -use libc::c_int; +use libc::{c_int, c_void}; use bn::BigNum; use bio::MemBio; use crypto::HashTypeInternals; use crypto::hash; +use crypto::util::{CallbackState, invoke_passwd_cb}; pub struct RSA(*mut ffi::RSA); @@ -76,6 +77,26 @@ impl RSA { } } + /// Reads an RSA private key from PEM formatted data and supplies a password callback. + pub fn private_key_from_pem_cb(reader: &mut R, pass_cb: F) -> Result + where R: Read, F: FnMut(&mut [i8]) -> 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::), + cb_ptr)); + + Ok(RSA(rsa)) + } + } + /// Writes an RSA private key as unencrypted PEM formatted data pub fn private_key_to_pem(&self, writer: &mut W) -> Result<(), SslError> where W: Write -- cgit v1.2.3 From c1b7cd2420c679b611c7ff28024db10cb0ffb8b5 Mon Sep 17 00:00:00 2001 From: Jonas Schievink Date: Wed, 22 Jun 2016 21:51:43 +0200 Subject: Make the callback take a `&mut [c_char]` --- openssl/src/crypto/pkey.rs | 4 ++-- openssl/src/crypto/rsa.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'openssl/src') diff --git a/openssl/src/crypto/pkey.rs b/openssl/src/crypto/pkey.rs index 605aed42..238c1b9e 100644 --- a/openssl/src/crypto/pkey.rs +++ b/openssl/src/crypto/pkey.rs @@ -1,4 +1,4 @@ -use libc::{c_int, c_uint, c_ulong, c_void}; +use libc::{c_int, c_uint, c_ulong, c_void, c_char}; use std::io; use std::io::prelude::*; use std::iter::repeat; @@ -100,7 +100,7 @@ impl PKey { /// 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(reader: &mut R, pass_cb: F) -> Result - where R: Read, F: FnMut(&mut [i8]) -> usize + where R: Read, F: FnMut(&mut [c_char]) -> usize { let mut cb = CallbackState::new(pass_cb); diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index d451aab6..c7f5cfaf 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -3,7 +3,7 @@ use std::fmt; use ssl::error::{SslError, StreamError}; use std::ptr; use std::io::{self, Read, Write}; -use libc::{c_int, c_void}; +use libc::{c_int, c_void, c_char}; use bn::BigNum; use bio::MemBio; @@ -79,7 +79,7 @@ impl RSA { /// Reads an RSA private key from PEM formatted data and supplies a password callback. pub fn private_key_from_pem_cb(reader: &mut R, pass_cb: F) -> Result - where R: Read, F: FnMut(&mut [i8]) -> usize + where R: Read, F: FnMut(&mut [c_char]) -> usize { let mut cb = CallbackState::new(pass_cb); -- cgit v1.2.3 From 41b78547ad0357d3e86462f72c0cff333096d59f Mon Sep 17 00:00:00 2001 From: Jonas Schievink Date: Wed, 22 Jun 2016 22:05:03 +0200 Subject: Put password callbacks behind a cargo feature --- openssl/src/crypto/mod.rs | 1 + openssl/src/crypto/pkey.rs | 7 ++++++- openssl/src/crypto/rsa.rs | 7 ++++++- 3 files changed, 13 insertions(+), 2 deletions(-) (limited to 'openssl/src') diff --git a/openssl/src/crypto/mod.rs b/openssl/src/crypto/mod.rs index 9d79b8b0..481eb05c 100644 --- a/openssl/src/crypto/mod.rs +++ b/openssl/src/crypto/mod.rs @@ -24,6 +24,7 @@ pub mod rand; pub mod symm; pub mod memcmp; pub mod rsa; +#[cfg(feature = "catch_unwind")] mod util; mod symm_internal; diff --git a/openssl/src/crypto/pkey.rs b/openssl/src/crypto/pkey.rs index 238c1b9e..bbb8427d 100644 --- a/openssl/src/crypto/pkey.rs +++ b/openssl/src/crypto/pkey.rs @@ -1,4 +1,4 @@ -use libc::{c_int, c_uint, c_ulong, c_void, c_char}; +use libc::{c_int, c_uint, c_ulong}; use std::io; use std::io::prelude::*; use std::iter::repeat; @@ -12,6 +12,10 @@ use crypto::hash::Type as HashType; use ffi; use ssl::error::{SslError, StreamError}; use crypto::rsa::RSA; + +#[cfg(feature = "catch_unwind")] +use libc::{c_void, c_char}; +#[cfg(feature = "catch_unwind")] use crypto::util::{CallbackState, invoke_passwd_cb}; #[derive(Copy, Clone)] @@ -99,6 +103,7 @@ impl PKey { /// /// The callback will be passed the password buffer and should return the number of characters /// placed into the buffer. + #[cfg(feature = "catch_unwind")] pub fn private_key_from_pem_cb(reader: &mut R, pass_cb: F) -> Result where R: Read, F: FnMut(&mut [c_char]) -> usize { diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index c7f5cfaf..a67fe38e 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -3,12 +3,16 @@ use std::fmt; use ssl::error::{SslError, StreamError}; use std::ptr; use std::io::{self, Read, Write}; -use libc::{c_int, c_void, c_char}; +use libc::c_int; use bn::BigNum; use bio::MemBio; 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); @@ -78,6 +82,7 @@ impl RSA { } /// Reads an RSA private key from PEM formatted data and supplies a password callback. + #[cfg(feature = "catch_unwind")] pub fn private_key_from_pem_cb(reader: &mut R, pass_cb: F) -> Result where R: Read, F: FnMut(&mut [c_char]) -> usize { -- cgit v1.2.3 From d176ea1c6e7aaa4e96d27eb0c62dc11fdb990aca Mon Sep 17 00:00:00 2001 From: Jonas Schievink Date: Wed, 22 Jun 2016 22:27:53 +0200 Subject: Add an RSA key decryption test --- openssl/src/crypto/rsa.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'openssl/src') diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index a67fe38e..d0303283 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -303,4 +303,22 @@ mod test { assert!(result); } + + #[test] + pub fn test_password() { + let mut password_queried = false; + let mut buffer = File::open("test/rsa-encrypted.pem").unwrap(); + let rsa = 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); + } } -- cgit v1.2.3 From 351bc569a46ab1590736114a50179351de8719d7 Mon Sep 17 00:00:00 2001 From: Jonas Schievink Date: Sun, 26 Jun 2016 18:24:47 +0200 Subject: Put the test behind the catch_unwind feature And fix an unused variable warning --- openssl/src/crypto/rsa.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'openssl/src') diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index d0303283..9a04bf7f 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -305,10 +305,11 @@ mod test { } #[test] + #[cfg(feature = "catch_unwind")] pub fn test_password() { let mut password_queried = false; let mut buffer = File::open("test/rsa-encrypted.pem").unwrap(); - let rsa = RSA::private_key_from_pem_cb(&mut buffer, |password| { + RSA::private_key_from_pem_cb(&mut buffer, |password| { password_queried = true; password[0] = b'm' as _; password[1] = b'y' as _; -- cgit v1.2.3 From f24ab2693636f16ce71a171a4d4d63bd0f5bbea0 Mon Sep 17 00:00:00 2001 From: Jonas Schievink Date: Sun, 26 Jun 2016 19:44:53 +0200 Subject: FnMut -> FnOnce, update docs --- openssl/src/crypto/pkey.rs | 4 +++- openssl/src/crypto/rsa.rs | 4 +++- openssl/src/crypto/util.rs | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) (limited to 'openssl/src') diff --git a/openssl/src/crypto/pkey.rs b/openssl/src/crypto/pkey.rs index bbb8427d..15744047 100644 --- a/openssl/src/crypto/pkey.rs +++ b/openssl/src/crypto/pkey.rs @@ -103,9 +103,11 @@ impl PKey { /// /// 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(reader: &mut R, pass_cb: F) -> Result - where R: Read, F: FnMut(&mut [c_char]) -> usize + where R: Read, F: FnOnce(&mut [c_char]) -> usize { let mut cb = CallbackState::new(pass_cb); diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index 9a04bf7f..3b420fbc 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -82,9 +82,11 @@ 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(reader: &mut R, pass_cb: F) -> Result - where R: Read, F: FnMut(&mut [c_char]) -> usize + where R: Read, F: FnOnce(&mut [c_char]) -> usize { let mut cb = CallbackState::new(pass_cb); diff --git a/openssl/src/crypto/util.rs b/openssl/src/crypto/util.rs index 85df86b7..be72aa59 100644 --- a/openssl/src/crypto/util.rs +++ b/openssl/src/crypto/util.rs @@ -41,7 +41,7 @@ pub extern "C" fn invoke_passwd_cb(buf: *mut c_char, _rwflag: c_int, cb_state: *mut c_void) -> c_int - where F: FnMut(&mut [i8]) -> usize { + 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) }; -- cgit v1.2.3 From 121169c1f57bf0b1130b400d9ed6431855fb2e73 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 1 Jul 2016 18:31:47 -0400 Subject: Set auto retry SSL_read returns a WANT_READ after a renegotiation by default which ends up bubbling up as a weird BUG error. Tell OpenSSL to just do the read again. --- openssl/src/ssl/mod.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'openssl/src') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index f207416f..d0954bc7 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -566,6 +566,9 @@ impl SslContext { let ctx = SslContext { ctx: ctx }; + // this is a bit dubious (?) + try!(ctx.set_mode(ffi::SSL_MODE_AUTO_RETRY)); + if method.is_dtls() { ctx.set_read_ahead(1); } @@ -648,8 +651,12 @@ impl SslContext { } } + fn set_mode(&self, mode: c_long) -> Result<(), SslError> { + wrap_ssl_result(unsafe { ffi_extras::SSL_CTX_set_mode(self.ctx, mode) as c_int }) + } + pub fn set_tmp_dh(&self, dh: DH) -> Result<(), SslError> { - wrap_ssl_result(unsafe { ffi_extras::SSL_CTX_set_tmp_dh(self.ctx, dh.raw()) as i32 }) + wrap_ssl_result(unsafe { ffi_extras::SSL_CTX_set_tmp_dh(self.ctx, dh.raw()) as c_int }) } /// Use the default locations of trusted certificates for verification. -- cgit v1.2.3 From 5135fca87f1bbdb7bfd128fcc92781448c8da798 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Fri, 1 Jul 2016 18:43:39 -0400 Subject: Release v0.7.14 --- openssl/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'openssl/src') diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index 91477303..690ab32b 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.7.13")] +#![doc(html_root_url="https://sfackler.github.io/rust-openssl/doc/v0.7.14")] #![cfg_attr(feature = "nightly", feature(const_fn))] #[macro_use] -- cgit v1.2.3 From 722a2bd673bac57faf450d5548a057481fa98cf0 Mon Sep 17 00:00:00 2001 From: Shaun Taheri Date: Fri, 22 Jul 2016 18:16:55 +0200 Subject: Set SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER flag --- openssl/src/ssl/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'openssl/src') diff --git a/openssl/src/ssl/mod.rs b/openssl/src/ssl/mod.rs index d0954bc7..0252b114 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -567,7 +567,7 @@ impl SslContext { let ctx = SslContext { ctx: ctx }; // this is a bit dubious (?) - try!(ctx.set_mode(ffi::SSL_MODE_AUTO_RETRY)); + try!(ctx.set_mode(ffi::SSL_MODE_AUTO_RETRY | ffi::SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)); if method.is_dtls() { ctx.set_read_ahead(1); -- cgit v1.2.3 From 5ed77df197afc33c04569edcd3db5993a695fbae Mon Sep 17 00:00:00 2001 From: Onur Aslan Date: Fri, 29 Jul 2016 12:11:53 +0300 Subject: Implement save_der for X509 and X509Req --- openssl/src/x509/mod.rs | 22 ++++++++++++++++++++++ openssl/src/x509/tests.rs | 13 +++++++++++++ 2 files changed, 35 insertions(+) (limited to 'openssl/src') diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 3150cc6e..396d50df 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -532,6 +532,17 @@ impl<'ctx> X509<'ctx> { } io::copy(&mut mem_bio, writer).map_err(StreamError).map(|_| ()) } + + /// Returns a DER serialized form of the certificate + pub fn save_der(&self) -> Result, SslError> { + let mut mem_bio = try!(MemBio::new()); + unsafe { + ffi::i2d_X509_bio(mem_bio.get_handle(), self.handle); + } + let mut v = Vec::new(); + try!(io::copy(&mut mem_bio, &mut v).map_err(StreamError)); + Ok(v) + } } extern "C" { @@ -637,6 +648,17 @@ impl X509Req { } io::copy(&mut mem_bio, writer).map_err(StreamError).map(|_| ()) } + + /// Returns a DER serialized form of the CSR + pub fn save_der(&self) -> Result, SslError> { + let mut mem_bio = try!(MemBio::new()); + unsafe { + ffi::i2d_X509_REQ_bio(mem_bio.get_handle(), self.handle); + } + let mut v = Vec::new(); + try!(io::copy(&mut mem_bio, &mut v).map_err(StreamError)); + Ok(v) + } } impl Drop for X509Req { diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index f547a982..5d9b30ab 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -92,6 +92,19 @@ fn test_cert_loading() { assert_eq!(fingerprint, hash_vec); } +#[test] +fn test_save_der() { + let cert_path = Path::new("test/cert.pem"); + let mut file = File::open(&cert_path) + .ok() + .expect("Failed to open `test/cert.pem`"); + + let cert = X509::from_pem(&mut file).ok().expect("Failed to load PEM"); + + let der = cert.save_der().unwrap(); + assert!(!der.is_empty()); +} + #[test] fn test_subject_read_cn() { let cert_path = Path::new("test/cert.pem"); -- cgit v1.2.3 From 7c082904fcfbce919396b372f4e236a0828fd7a0 Mon Sep 17 00:00:00 2001 From: Onur Aslan Date: Fri, 29 Jul 2016 16:30:24 +0300 Subject: Implement get_handle for X509Req --- openssl/src/x509/mod.rs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'openssl/src') diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 3150cc6e..daeb9283 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -611,6 +611,10 @@ impl X509Req { X509Req { handle: handle } } + pub fn get_handle(&self) -> *mut ffi::X509_REQ { + self.handle + } + /// Reads CSR from PEM pub fn from_pem(reader: &mut R) -> Result where R: Read -- cgit v1.2.3 From a3a602be515cfc8fdd44a11b89fee012baec0e0b Mon Sep 17 00:00:00 2001 From: Ben Batha Date: Tue, 17 May 2016 18:10:06 -0400 Subject: add low level dsa primitives --- openssl/src/crypto/dsa.rs | 351 ++++++++++++++++++++++++++++++++++++++++++++++ openssl/src/crypto/mod.rs | 1 + 2 files changed, 352 insertions(+) create mode 100644 openssl/src/crypto/dsa.rs (limited to 'openssl/src') diff --git a/openssl/src/crypto/dsa.rs b/openssl/src/crypto/dsa.rs new file mode 100644 index 00000000..7e384ae3 --- /dev/null +++ b/openssl/src/crypto/dsa.rs @@ -0,0 +1,351 @@ +use ffi; +use std::fmt; +use ssl::error::{SslError, StreamError}; +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 { + 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 { + 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 { + let params = try!(DSAParams::with_size(size)); + params.generate() + } + + /// Reads a DSA private key from PEM formatted data. + pub fn private_key_from_pem(reader: &mut R) -> Result + where R: Read + { + let mut mem_bio = try!(MemBio::new()); + try!(io::copy(reader, &mut mem_bio).map_err(StreamError)); + + 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(reader: &mut R, pass_cb: F) -> Result + 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::), + 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(&self, writer: &mut W) -> Result<(), SslError> + 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).map_err(StreamError)); + Ok(()) + } + + /// Reads an DSA public key from PEM formatted data. + pub fn public_key_from_pem(reader: &mut R) -> Result + where R: Read + { + let mut mem_bio = try!(MemBio::new()); + try!(io::copy(reader, &mut mem_bio).map_err(StreamError)); + + 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(&self, writer: &mut W) -> Result<(), SslError> + 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).map_err(StreamError)); + Ok(()) + } + + pub fn size(&self) -> Result { + if self.has_q() { + unsafe { Ok(ffi::DSA_size(self.0) as isize) } + } else { + Err(SslError::OpenSslErrors(vec![])) + } + } + + pub fn sign(&self, hash: hash::Type, message: &[u8]) -> Result, SslError> { + let k_len = try!(self.size()) 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 + } + + // The following getters are unsafe, since BigNum::new_from_ffi fails upon null pointers + pub fn p(&self) -> Result { + 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 { + 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 { + 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 = (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 = (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 = (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/mod.rs b/openssl/src/crypto/mod.rs index 481eb05c..6a34bd59 100644 --- a/openssl/src/crypto/mod.rs +++ b/openssl/src/crypto/mod.rs @@ -24,6 +24,7 @@ pub mod rand; pub mod symm; pub mod memcmp; pub mod rsa; +pub mod dsa; #[cfg(feature = "catch_unwind")] mod util; -- cgit v1.2.3 From 67d3067dbf152c2431e002cbe39ee13286d6d503 Mon Sep 17 00:00:00 2001 From: Ben Batha Date: Fri, 29 Jul 2016 20:01:54 -0400 Subject: improve error handling in rsa --- openssl/src/crypto/rsa.rs | 42 ++++++++++++++---------------------------- 1 file changed, 14 insertions(+), 28 deletions(-) (limited to 'openssl/src') diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index 3b420fbc..2b563a7a 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -110,23 +110,17 @@ impl RSA { { let mut mem_bio = try!(MemBio::new()); - let result = unsafe { - ffi::PEM_write_bio_RSAPrivateKey(mem_bio.get_handle(), + unsafe { + try_ssl!(ffi::PEM_write_bio_RSAPrivateKey(mem_bio.get_handle(), self.0, ptr::null(), ptr::null_mut(), 0, None, - ptr::null_mut()) - }; - - if result == 1 { - try!(io::copy(&mut mem_bio, writer).map_err(StreamError)); - - Ok(()) - } else { - Err(SslError::OpenSslErrors(vec![])) + ptr::null_mut())); } + try!(io::copy(&mut mem_bio, writer).map_err(StreamError)); + Ok(()) } /// Reads an RSA public key from PEM formatted data. @@ -151,15 +145,12 @@ impl RSA { { let mut mem_bio = try!(MemBio::new()); - let result = unsafe { 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)); + unsafe { + try_ssl!(ffi::PEM_write_bio_RSA_PUBKEY(mem_bio.get_handle(), self.0)) + }; - Ok(()) - } else { - Err(SslError::OpenSslErrors(vec![])) - } + try!(io::copy(&mut mem_bio, writer).map_err(StreamError)); + Ok(()) } pub fn size(&self) -> Result { @@ -176,19 +167,14 @@ impl RSA { let mut sig_len = k_len; unsafe { - let result = ffi::RSA_sign(hash.as_nid() as c_int, + 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); + self.0)); assert!(sig_len == k_len); - - if result == 1 { - Ok(sig) - } else { - Err(SslError::OpenSslErrors(vec![])) - } + Ok(sig) } } @@ -200,7 +186,7 @@ impl RSA { sig.as_ptr(), sig.len() as u32, self.0); - + try_ssl_if!(result == -1); Ok(result == 1) } } -- cgit v1.2.3