diff options
| author | Steven Fackler <[email protected]> | 2014-08-03 19:16:09 -0700 |
|---|---|---|
| committer | Steven Fackler <[email protected]> | 2014-08-03 19:16:09 -0700 |
| commit | 203bdd076ec744a1794a7b151efb6b9247d43455 (patch) | |
| tree | 8b4e69b8bdfd834648b73243519f4eeca301bb90 /src | |
| parent | Remove Makefile infrastructure (diff) | |
| download | rust-openssl-203bdd076ec744a1794a7b151efb6b9247d43455.tar.xz rust-openssl-203bdd076ec744a1794a7b151efb6b9247d43455.zip | |
Shift directory structure
Diffstat (limited to 'src')
| -rw-r--r-- | src/bn/mod.rs | 569 | ||||
| -rw-r--r-- | src/crypto/hash.rs | 187 | ||||
| -rw-r--r-- | src/crypto/hmac.rs | 259 | ||||
| -rw-r--r-- | src/crypto/mod.rs | 23 | ||||
| -rw-r--r-- | src/crypto/pkcs5.rs | 124 | ||||
| -rw-r--r-- | src/crypto/pkey.rs | 425 | ||||
| -rw-r--r-- | src/crypto/rand.rs | 30 | ||||
| -rw-r--r-- | src/crypto/symm.rs | 276 | ||||
| -rw-r--r-- | src/lib.rs | 14 | ||||
| -rw-r--r-- | src/ssl/error.rs | 60 | ||||
| -rw-r--r-- | src/ssl/ffi.rs | 159 | ||||
| -rw-r--r-- | src/ssl/mod.rs | 541 | ||||
| -rw-r--r-- | src/ssl/tests.rs | 160 |
13 files changed, 2827 insertions, 0 deletions
diff --git a/src/bn/mod.rs b/src/bn/mod.rs new file mode 100644 index 00000000..ac4fff7b --- /dev/null +++ b/src/bn/mod.rs @@ -0,0 +1,569 @@ + +use libc::{c_void, c_int, c_ulong}; +use std::ptr; + +use ssl::error::SslError; + +#[allow(dead_code)] +struct BIGNUM { + d: *mut c_void, + top: c_int, + dmax: c_int, + neg: c_int, + flags: c_int, +} + +#[allow(non_camel_case_types)] +type BN_CTX = *mut c_void; + +#[link(name = "crypto")] +extern { + fn BN_new() -> *mut BIGNUM; + fn BN_clear_free(bn: *mut BIGNUM); + + fn BN_CTX_new() -> *mut BN_CTX; + fn BN_CTX_free(ctx: *mut BN_CTX); + + fn BN_set_word(bn: *mut BIGNUM, n: c_ulong) -> c_int; + fn BN_set_negative(bn: *mut BIGNUM, n: c_int); + fn BN_num_bits(bn: *mut BIGNUM) -> c_int; + + /* Arithmetic operations on BIGNUMs */ + fn BN_add(r: *mut BIGNUM, a: *mut BIGNUM, b: *mut BIGNUM) -> c_int; + fn BN_sub(r: *mut BIGNUM, a: *mut BIGNUM, b: *mut BIGNUM) -> c_int; + fn BN_mul(r: *mut BIGNUM, a: *mut BIGNUM, b: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; + fn BN_sqr(r: *mut BIGNUM, a: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; + fn BN_div(dv: *mut BIGNUM, rem: *mut BIGNUM, a: *mut BIGNUM, b: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; + fn BN_mod(rem: *mut BIGNUM, a: *mut BIGNUM, m: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; + fn BN_nnmod(rem: *mut BIGNUM, a: *mut BIGNUM, m: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; + fn BN_mod_add(r: *mut BIGNUM, a: *mut BIGNUM, b: *mut BIGNUM, m: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; + fn BN_mod_sub(r: *mut BIGNUM, a: *mut BIGNUM, b: *mut BIGNUM, m: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; + fn BN_mod_mul(r: *mut BIGNUM, a: *mut BIGNUM, b: *mut BIGNUM, m: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; + fn BN_mod_sqr(r: *mut BIGNUM, a: *mut BIGNUM, m: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; + fn BN_exp(r: *mut BIGNUM, a: *mut BIGNUM, p: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; + fn BN_mod_exp(r: *mut BIGNUM, a: *mut BIGNUM, p: *mut BIGNUM, m: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; + fn BN_mod_inverse(r: *mut BIGNUM, a: *mut BIGNUM, n: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; + fn BN_gcd(r: *mut BIGNUM, a: *mut BIGNUM, b: *mut BIGNUM, ctx: *mut BN_CTX) -> c_int; + + /* Bit operations on BIGNUMs */ + fn BN_set_bit(a: *mut BIGNUM, n: c_int) -> c_int; + fn BN_clear_bit(a: *mut BIGNUM, n: c_int) -> c_int; + fn BN_is_bit_set(a: *mut BIGNUM, n: c_int) -> c_int; + fn BN_mask_bits(a: *mut BIGNUM, n: c_int) -> c_int; + fn BN_lshift(r: *mut BIGNUM, a: *mut BIGNUM, n: c_int) -> c_int; + fn BN_lshift1(r: *mut BIGNUM, a: *mut BIGNUM) -> c_int; + fn BN_rshift(r: *mut BIGNUM, a: *mut BIGNUM, n: c_int) -> c_int; + fn BN_rshift1(r: *mut BIGNUM, a: *mut BIGNUM) -> c_int; + + /* Comparisons on BIGNUMs */ + fn BN_cmp(a: *mut BIGNUM, b: *mut BIGNUM) -> c_int; + fn BN_ucmp(a: *mut BIGNUM, b: *mut BIGNUM) -> c_int; + + /* Prime handling */ + fn BN_generate_prime_ex(r: *mut BIGNUM, bits: c_int, safe: c_int, add: *mut BIGNUM, rem: *mut BIGNUM, cb: *const c_void) -> c_int; + fn BN_is_prime_ex(p: *mut BIGNUM, checks: c_int, ctx: *mut BN_CTX, cb: *const c_void) -> c_int; + fn BN_is_prime_fasttest_ex(p: *mut BIGNUM, checks: c_int, ctx: *mut BN_CTX, do_trial_division: c_int, cb: *const c_void) -> c_int; + + /* Random number handling */ + fn BN_rand(r: *mut BIGNUM, bits: c_int, top: c_int, bottom: c_int) -> c_int; + fn BN_pseudo_rand(r: *mut BIGNUM, bits: c_int, top: c_int, bottom: c_int) -> c_int; + fn BN_rand_range(r: *mut BIGNUM, range: *mut BIGNUM) -> c_int; + fn BN_pseudo_rand_range(r: *mut BIGNUM, range: *mut BIGNUM) -> c_int; + + /* Conversion from/to binary representation */ + fn BN_bn2bin(a: *mut BIGNUM, to: *mut u8) -> c_int; + fn BN_bin2bn(s: *const u8, size: c_int, ret: *mut BIGNUM) -> *mut BIGNUM; +} + +pub struct BigNum(*mut BIGNUM); + +#[repr(C)] +pub enum RNGProperty { + MsbMaybeZero = -1, + MsbOne = 0, + TwoMsbOne = 1, +} + +macro_rules! with_ctx( + ($name:ident, $action:block) => ({ + let $name = BN_CTX_new(); + if ($name).is_null() { + Err(SslError::get()) + } else { + let r = $action; + BN_CTX_free($name); + r + } + }); +) + +macro_rules! with_bn( + ($name:ident, $action:block) => ({ + let tmp = BigNum::new(); + match tmp { + Ok($name) => { + if $action { + Ok($name) + } else { + Err(SslError::get()) + } + }, + Err(err) => Err(err), + } + }); +) + +macro_rules! with_bn_in_ctx( + ($name:ident, $ctx_name:ident, $action:block) => ({ + let tmp = BigNum::new(); + match tmp { + Ok($name) => { + let $ctx_name = BN_CTX_new(); + if ($ctx_name).is_null() { + Err(SslError::get()) + } else { + let r = + if $action { + Ok($name) + } else { + Err(SslError::get()) + }; + BN_CTX_free($ctx_name); + r + } + }, + Err(err) => Err(err), + } + }); +) + +impl BigNum { + pub fn new() -> Result<BigNum, SslError> { + unsafe { + let v = BN_new(); + if v.is_null() { + Err(SslError::get()) + } else { + Ok(BigNum(v)) + } + } + } + + pub fn new_from(n: u64) -> Result<BigNum, SslError> { + unsafe { + let bn = BN_new(); + if bn.is_null() || BN_set_word(bn, n as c_ulong) == 0 { + Err(SslError::get()) + } else { + Ok(BigNum(bn)) + } + } + } + + pub fn new_from_slice(n: &[u8]) -> Result<BigNum, SslError> { + unsafe { + let bn = BN_new(); + if bn.is_null() || BN_bin2bn(n.as_ptr(), n.len() as c_int, bn).is_null() { + Err(SslError::get()) + } else { + Ok(BigNum(bn)) + } + } + } + + pub fn checked_sqr(&self) -> Result<BigNum, SslError> { + unsafe { + with_bn_in_ctx!(r, ctx, { BN_sqr(r.raw(), self.raw(), ctx) == 1 }) + } + } + + pub fn checked_nnmod(&self, n: &BigNum) -> Result<BigNum, SslError> { + unsafe { + with_bn_in_ctx!(r, ctx, { BN_nnmod(r.raw(), self.raw(), n.raw(), ctx) == 1 }) + } + } + + pub fn checked_mod_add(&self, a: &BigNum, n: &BigNum) -> Result<BigNum, SslError> { + unsafe { + with_bn_in_ctx!(r, ctx, { BN_mod_add(r.raw(), self.raw(), a.raw(), n.raw(), ctx) == 1 }) + } + } + + pub fn checked_mod_sub(&self, a: &BigNum, n: &BigNum) -> Result<BigNum, SslError> { + unsafe { + with_bn_in_ctx!(r, ctx, { BN_mod_sub(r.raw(), self.raw(), a.raw(), n.raw(), ctx) == 1 }) + } + } + + pub fn checked_mod_mul(&self, a: &BigNum, n: &BigNum) -> Result<BigNum, SslError> { + unsafe { + with_bn_in_ctx!(r, ctx, { BN_mod_mul(r.raw(), self.raw(), a.raw(), n.raw(), ctx) == 1 }) + } + } + + pub fn checked_mod_sqr(&self, n: &BigNum) -> Result<BigNum, SslError> { + unsafe { + with_bn_in_ctx!(r, ctx, { BN_mod_sqr(r.raw(), self.raw(), n.raw(), ctx) == 1 }) + } + } + + pub fn checked_exp(&self, p: &BigNum) -> Result<BigNum, SslError> { + unsafe { + with_bn_in_ctx!(r, ctx, { BN_exp(r.raw(), self.raw(), p.raw(), ctx) == 1 }) + } + } + + pub fn checked_mod_exp(&self, p: &BigNum, n: &BigNum) -> Result<BigNum, SslError> { + unsafe { + with_bn_in_ctx!(r, ctx, { BN_mod_exp(r.raw(), self.raw(), p.raw(), n.raw(), ctx) == 1 }) + } + } + + pub fn checked_mod_inv(&self, n: &BigNum) -> Result<BigNum, SslError> { + unsafe { + with_bn_in_ctx!(r, ctx, { BN_mod_inverse(r.raw(), self.raw(), n.raw(), ctx) == 1 }) + } + } + + pub fn checked_gcd(&self, a: &BigNum) -> Result<BigNum, SslError> { + unsafe { + with_bn_in_ctx!(r, ctx, { BN_gcd(r.raw(), self.raw(), a.raw(), ctx) == 1 }) + } + } + + pub fn checked_generate_prime(bits: i32, safe: bool, add: Option<&BigNum>, rem: Option<&BigNum>) -> Result<BigNum, SslError> { + unsafe { + with_bn_in_ctx!(r, ctx, { + let add_arg = add.map(|a| a.raw()).unwrap_or(ptr::mut_null()); + let rem_arg = rem.map(|r| r.raw()).unwrap_or(ptr::mut_null()); + + BN_generate_prime_ex(r.raw(), bits as c_int, safe as c_int, add_arg, rem_arg, ptr::null()) == 1 + }) + } + } + + pub fn is_prime(&self, checks: i32) -> Result<bool, SslError> { + unsafe { + with_ctx!(ctx, { + Ok(BN_is_prime_ex(self.raw(), checks as c_int, ctx, ptr::null()) == 1) + }) + } + } + + pub fn is_prime_fast(&self, checks: i32, do_trial_division: bool) -> Result<bool, SslError> { + unsafe { + with_ctx!(ctx, { + Ok(BN_is_prime_fasttest_ex(self.raw(), checks as c_int, ctx, do_trial_division as c_int, ptr::null()) == 1) + }) + } + } + + pub fn checked_new_random(bits: i32, prop: RNGProperty, odd: bool) -> Result<BigNum, SslError> { + unsafe { + with_bn_in_ctx!(r, ctx, { BN_rand(r.raw(), bits as c_int, prop as c_int, odd as c_int) == 1 }) + } + } + + pub fn checked_new_pseudo_random(bits: i32, prop: RNGProperty, odd: bool) -> Result<BigNum, SslError> { + unsafe { + with_bn_in_ctx!(r, ctx, { BN_pseudo_rand(r.raw(), bits as c_int, prop as c_int, odd as c_int) == 1 }) + } + } + + pub fn checked_rand_in_range(&self) -> Result<BigNum, SslError> { + unsafe { + with_bn_in_ctx!(r, ctx, { BN_rand_range(r.raw(), self.raw()) == 1 }) + } + } + + pub fn checked_pseudo_rand_in_range(&self) -> Result<BigNum, SslError> { + unsafe { + with_bn_in_ctx!(r, ctx, { BN_pseudo_rand_range(r.raw(), self.raw()) == 1 }) + } + } + + pub fn set_bit(&mut self, n: i32) -> Result<(), SslError> { + unsafe { + if BN_set_bit(self.raw(), n as c_int) == 1 { + Ok(()) + } else { + Err(SslError::get()) + } + } + } + + pub fn clear_bit(&mut self, n: i32) -> Result<(), SslError> { + unsafe { + if BN_clear_bit(self.raw(), n as c_int) == 1 { + Ok(()) + } else { + Err(SslError::get()) + } + } + } + + pub fn is_bit_set(&self, n: i32) -> bool { + unsafe { + BN_is_bit_set(self.raw(), n as c_int) == 1 + } + } + + pub fn mask_bits(&mut self, n: i32) -> Result<(), SslError> { + unsafe { + if BN_mask_bits(self.raw(), n as c_int) == 1 { + Ok(()) + } else { + Err(SslError::get()) + } + } + } + + pub fn checked_shl1(&self) -> Result<BigNum, SslError> { + unsafe { + with_bn!(r, { BN_lshift1(r.raw(), self.raw()) == 1 }) + } + } + + pub fn checked_shr1(&self) -> Result<BigNum, SslError> { + unsafe { + with_bn!(r, { BN_rshift1(r.raw(), self.raw()) == 1 }) + } + } + + pub fn checked_add(&self, a: &BigNum) -> Result<BigNum, SslError> { + unsafe { + with_bn!(r, { BN_add(r.raw(), self.raw(), a.raw()) == 1 }) + } + } + + pub fn checked_sub(&self, a: &BigNum) -> Result<BigNum, SslError> { + unsafe { + with_bn!(r, { BN_sub(r.raw(), self.raw(), a.raw()) == 1 }) + } + } + + pub fn checked_mul(&self, a: &BigNum) -> Result<BigNum, SslError> { + unsafe { + with_bn_in_ctx!(r, ctx, { BN_mul(r.raw(), self.raw(), a.raw(), ctx) == 1 }) + } + } + + pub fn checked_div(&self, a: &BigNum) -> Result<BigNum, SslError> { + unsafe { + with_bn_in_ctx!(r, ctx, { BN_div(r.raw(), ptr::mut_null(), self.raw(), a.raw(), ctx) == 1 }) + } + } + + pub fn checked_mod(&self, a: &BigNum) -> Result<BigNum, SslError> { + unsafe { + with_bn_in_ctx!(r, ctx, { BN_mod(r.raw(), self.raw(), a.raw(), ctx) == 1 }) + } + } + + pub fn checked_shl(&self, a: &i32) -> Result<BigNum, SslError> { + unsafe { + with_bn!(r, { BN_lshift(r.raw(), self.raw(), *a as c_int) == 1 }) + } + } + + pub fn checked_shr(&self, a: &i32) -> Result<BigNum, SslError> { + unsafe { + with_bn!(r, { BN_rshift(r.raw(), self.raw(), *a as c_int) == 1 }) + } + } + + pub fn negate(&mut self) { + unsafe { + BN_set_negative(self.raw(), !self.is_negative() as c_int) + } + } + + pub fn abs_cmp(&self, oth: BigNum) -> Ordering { + unsafe { + let res = BN_ucmp(self.raw(), oth.raw()) as i32; + if res < 0 { + Less + } else if res > 0 { + Greater + } else { + Equal + } + } + } + + pub fn is_negative(&self) -> bool { + unsafe { + (*self.raw()).neg == 1 + } + } + + pub fn num_bits(&self) -> i32 { + unsafe { + BN_num_bits(self.raw()) as i32 + } + } + + pub fn num_bytes(&self) -> i32 { + (self.num_bits() + 7) / 8 + } + + unsafe fn raw(&self) -> *mut BIGNUM { + let BigNum(n) = *self; + n + } + + pub fn to_vec(&self) -> Vec<u8> { + let size = self.num_bytes() as uint; + let mut v = Vec::with_capacity(size); + unsafe { + BN_bn2bin(self.raw(), v.as_mut_ptr()); + v.set_len(size); + } + v + } +} + +impl Eq for BigNum { } +impl PartialEq for BigNum { + fn eq(&self, oth: &BigNum) -> bool { + unsafe { + BN_cmp(self.raw(), oth.raw()) == 0 + } + } +} + +impl Ord for BigNum { + fn cmp(&self, oth: &BigNum) -> Ordering { + self.partial_cmp(oth).unwrap() + } +} + +impl PartialOrd for BigNum { + fn partial_cmp(&self, oth: &BigNum) -> Option<Ordering> { + unsafe { + let v = BN_cmp(self.raw(), oth.raw()); + let ret = + if v == 0 { + Equal + } else if v < 0 { + Less + } else { + Greater + }; + Some(ret) + } + } +} + +impl Drop for BigNum { + fn drop(&mut self) { + unsafe { + if !self.raw().is_null() { + BN_clear_free(self.raw()); + } + } + } +} + +pub mod unchecked { + use super::{BIGNUM, BigNum}; + + extern { + fn BN_dup(n: *mut BIGNUM) -> *mut BIGNUM; + } + + impl Add<BigNum, BigNum> for BigNum { + fn add(&self, oth: &BigNum) -> BigNum { + self.checked_add(oth).unwrap() + } + } + + impl Sub<BigNum, BigNum> for BigNum { + fn sub(&self, oth: &BigNum) -> BigNum { + self.checked_sub(oth).unwrap() + } + } + + impl Mul<BigNum, BigNum> for BigNum { + fn mul(&self, oth: &BigNum) -> BigNum { + self.checked_mul(oth).unwrap() + } + } + + impl Div<BigNum, BigNum> for BigNum { + fn div(&self, oth: &BigNum) -> BigNum { + self.checked_div(oth).unwrap() + } + } + + impl Rem<BigNum, BigNum> for BigNum { + fn rem(&self, oth: &BigNum) -> BigNum { + self.checked_mod(oth).unwrap() + } + } + + impl Shl<i32, BigNum> for BigNum { + fn shl(&self, n: &i32) -> BigNum { + self.checked_shl(n).unwrap() + } + } + + impl Shr<i32, BigNum> for BigNum { + fn shr(&self, n: &i32) -> BigNum { + self.checked_shr(n).unwrap() + } + } + + impl Clone for BigNum { + fn clone(&self) -> BigNum { + unsafe { + let r = BN_dup(self.raw()); + if r.is_null() { + fail!("Unexpected null pointer from BN_dup(..)") + } else { + BigNum(r) + } + } + } + } + + impl Neg<BigNum> for BigNum { + fn neg(&self) -> BigNum { + let mut n = self.clone(); + n.negate(); + n + } + } +} + +#[cfg(test)] +mod tests { + use bn::BigNum; + + #[test] + fn test_to_from_slice() { + let v0 = BigNum::new_from(10203004_u64).unwrap(); + let vec = v0.to_vec(); + let v1 = BigNum::new_from_slice(vec.as_slice()).unwrap(); + + assert!(v0 == v1); + } + + #[test] + fn test_negation() { + let a = BigNum::new_from(909829283_u64).unwrap(); + + assert!(!a.is_negative()); + assert!((-a).is_negative()); + } + + + #[test] + fn test_prime_numbers() { + let a = BigNum::new_from(19029017_u64).unwrap(); + let p = BigNum::checked_generate_prime(128, true, None, Some(&a)).unwrap(); + + assert!(p.is_prime(100).unwrap()); + assert!(p.is_prime_fast(100, true).unwrap()); + } +} diff --git a/src/crypto/hash.rs b/src/crypto/hash.rs new file mode 100644 index 00000000..1a1b6e8a --- /dev/null +++ b/src/crypto/hash.rs @@ -0,0 +1,187 @@ +use libc; +use libc::c_uint; +use std::ptr; + +pub enum HashType { + MD5, + SHA1, + SHA224, + SHA256, + SHA384, + SHA512 +} + +#[allow(dead_code)] +#[allow(non_camel_case_types)] +pub struct EVP_MD_CTX { + digest: *mut EVP_MD, + engine: *mut libc::c_void, + flags: libc::c_ulong, + md_data: *mut libc::c_void, + pctx: *mut EVP_PKEY_CTX, + update: *mut libc::c_void +} + +#[allow(non_camel_case_types)] +pub struct EVP_MD; + +#[allow(non_camel_case_types)] +pub struct EVP_PKEY_CTX; + +#[link(name = "crypto")] +extern { + fn EVP_MD_CTX_create() -> *mut EVP_MD_CTX; + fn EVP_MD_CTX_destroy(ctx: *mut EVP_MD_CTX); + + fn EVP_md5() -> *const EVP_MD; + fn EVP_sha1() -> *const EVP_MD; + fn EVP_sha224() -> *const EVP_MD; + fn EVP_sha256() -> *const EVP_MD; + fn EVP_sha384() -> *const EVP_MD; + fn EVP_sha512() -> *const EVP_MD; + + fn EVP_DigestInit(ctx: *mut EVP_MD_CTX, typ: *const EVP_MD); + fn EVP_DigestUpdate(ctx: *mut EVP_MD_CTX, data: *const u8, n: c_uint); + fn EVP_DigestFinal(ctx: *mut EVP_MD_CTX, res: *mut u8, n: *mut u32); +} + +pub fn evpmd(t: HashType) -> (*const EVP_MD, uint) { + unsafe { + match t { + MD5 => (EVP_md5(), 16u), + SHA1 => (EVP_sha1(), 20u), + SHA224 => (EVP_sha224(), 28u), + SHA256 => (EVP_sha256(), 32u), + SHA384 => (EVP_sha384(), 48u), + SHA512 => (EVP_sha512(), 64u), + } + } +} + +#[allow(dead_code)] +pub struct Hasher { + evp: *const EVP_MD, + ctx: *mut EVP_MD_CTX, + len: uint, +} + +impl Hasher { + pub fn new(ht: HashType) -> Hasher { + let ctx = unsafe { EVP_MD_CTX_create() }; + let (evp, mdlen) = evpmd(ht); + unsafe { + EVP_DigestInit(ctx, evp); + } + + Hasher { evp: evp, ctx: ctx, len: mdlen } + } + + /// Update this hasher with more input bytes + pub fn update(&self, data: &[u8]) { + unsafe { + EVP_DigestUpdate(self.ctx, data.as_ptr(), data.len() as c_uint) + } + } + + /** + * Return the digest of all bytes added to this hasher since its last + * initialization + */ + pub fn final(&self) -> Vec<u8> { + unsafe { + let mut res = Vec::from_elem(self.len, 0u8); + EVP_DigestFinal(self.ctx, res.as_mut_ptr(), ptr::mut_null()); + res + } + } +} + +impl Drop for Hasher { + fn drop(&mut self) { + unsafe { + EVP_MD_CTX_destroy(self.ctx); + } + } +} + +/** + * Hashes the supplied input data using hash t, returning the resulting hash + * value + */ +pub fn hash(t: HashType, data: &[u8]) -> Vec<u8> { + let h = Hasher::new(t); + h.update(data); + h.final() +} + +#[cfg(test)] +mod tests { + use serialize::hex::{FromHex, ToHex}; + + struct HashTest { + input: Vec<u8>, + expected_output: String + } + + fn HashTest(input: &str, output: &str) -> HashTest { + HashTest { input: input.from_hex().unwrap(), + expected_output: output.to_string() } + } + + fn hash_test(hashtype: super::HashType, hashtest: &HashTest) { + let calced_raw = super::hash(hashtype, hashtest.input.as_slice()); + + let calced = calced_raw.as_slice().to_hex().into_string(); + + if calced != hashtest.expected_output { + println!("Test failed - {} != {}", calced, hashtest.expected_output); + } + + assert!(calced == hashtest.expected_output); + } + + // Test vectors from http://www.nsrl.nist.gov/testdata/ + #[test] + fn test_md5() { + let tests = [ + HashTest("", "d41d8cd98f00b204e9800998ecf8427e"), + HashTest("7F", "83acb6e67e50e31db6ed341dd2de1595"), + HashTest("EC9C", "0b07f0d4ca797d8ac58874f887cb0b68"), + HashTest("FEE57A", "e0d583171eb06d56198fc0ef22173907"), + HashTest("42F497E0", "7c430f178aefdf1487fee7144e9641e2"), + HashTest("C53B777F1C", "75ef141d64cb37ec423da2d9d440c925"), + HashTest("89D5B576327B", "ebbaf15eb0ed784c6faa9dc32831bf33"), + HashTest("5D4CCE781EB190", "ce175c4b08172019f05e6b5279889f2c"), + HashTest("81901FE94932D7B9", "cd4d2f62b8cdb3a0cf968a735a239281"), + HashTest("C9FFDEE7788EFB4EC9", "e0841a231ab698db30c6c0f3f246c014"), + HashTest("66AC4B7EBA95E53DC10B", "a3b3cea71910d9af56742aa0bb2fe329"), + HashTest("A510CD18F7A56852EB0319", "577e216843dd11573574d3fb209b97d8"), + HashTest("AAED18DBE8938C19ED734A8D", "6f80fb775f27e0a4ce5c2f42fc72c5f1")]; + + for test in tests.iter() { + hash_test(super::MD5, test); + } + } + + #[test] + fn test_sha1() { + let tests = [ + HashTest("616263", "a9993e364706816aba3e25717850c26c9cd0d89d"), + ]; + + for test in tests.iter() { + hash_test(super::SHA1, test); + } + } + + #[test] + fn test_sha256() { + let tests = [ + HashTest("616263", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad") + ]; + + for test in tests.iter() { + hash_test(super::SHA256, test); + } + } +} diff --git a/src/crypto/hmac.rs b/src/crypto/hmac.rs new file mode 100644 index 00000000..16be0f29 --- /dev/null +++ b/src/crypto/hmac.rs @@ -0,0 +1,259 @@ +/* + * Copyright 2013 Jack Lloyd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +use libc::{c_uchar, c_int, c_uint}; +use crypto::hash; + +#[allow(dead_code)] +#[allow(non_camel_case_types)] +pub struct HMAC_CTX { + md: *mut hash::EVP_MD, + md_ctx: hash::EVP_MD_CTX, + i_ctx: hash::EVP_MD_CTX, + o_ctx: hash::EVP_MD_CTX, + key_length: c_uint, + key: [c_uchar, ..128] +} + +#[link(name = "crypto")] +extern { + fn HMAC_CTX_init(ctx: *mut HMAC_CTX); + fn HMAC_Init_ex(ctx: *mut HMAC_CTX, key: *const u8, keylen: c_int, md: *const hash::EVP_MD, imple: *const ENGINE); + fn HMAC_Update(ctx: *mut HMAC_CTX, input: *const u8, len: c_uint); + fn HMAC_Final(ctx: *mut HMAC_CTX, output: *mut u8, len: *mut c_uint); +} + +#[allow(non_camel_case_types)] +struct ENGINE; + +pub struct HMAC { + ctx: HMAC_CTX, + len: uint, +} + +#[allow(non_snake_case_functions)] +pub fn HMAC(ht: hash::HashType, key: &[u8]) -> HMAC { + unsafe { + let (evp, mdlen) = hash::evpmd(ht); + + let mut ctx : HMAC_CTX = ::std::mem::uninitialized(); + + HMAC_CTX_init(&mut ctx); + HMAC_Init_ex(&mut ctx, + key.as_ptr(), + key.len() as c_int, + evp, 0 as *const _); + + HMAC { ctx: ctx, len: mdlen } + } +} + +impl HMAC { + pub fn update(&mut self, data: &[u8]) { + unsafe { + HMAC_Update(&mut self.ctx, data.as_ptr(), data.len() as c_uint) + } + } + + pub fn final(&mut self) -> Vec<u8> { + unsafe { + let mut res = Vec::from_elem(self.len, 0u8); + let mut outlen = 0; + HMAC_Final(&mut self.ctx, res.as_mut_ptr(), &mut outlen); + assert!(self.len == outlen as uint) + res + } + } +} + +#[cfg(test)] +mod tests { + use serialize::hex::FromHex; + use crypto::hash::{HashType, MD5, SHA1, SHA224, SHA256, SHA384, SHA512}; + use super::HMAC; + + #[test] + fn test_hmac_md5() { + // test vectors from RFC 2202 + let tests: [(Vec<u8>, Vec<u8>, Vec<u8>), ..7] = [ + (Vec::from_elem(16, 0x0b_u8), Vec::from_slice(b"Hi There"), + "9294727a3638bb1c13f48ef8158bfc9d".from_hex().unwrap()), + (Vec::from_slice(b"Jefe"), + Vec::from_slice(b"what do ya want for nothing?"), + "750c783e6ab0b503eaa86e310a5db738".from_hex().unwrap()), + (Vec::from_elem(16, 0xaa_u8), Vec::from_elem(50, 0xdd_u8), + "56be34521d144c88dbb8c733f0e8b3f6".from_hex().unwrap()), + ("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(), + Vec::from_elem(50, 0xcd_u8), + "697eaf0aca3a3aea3a75164746ffaa79".from_hex().unwrap()), + (Vec::from_elem(16, 0x0c_u8), + Vec::from_slice(b"Test With Truncation"), + "56461ef2342edc00f9bab995690efd4c".from_hex().unwrap()), + (Vec::from_elem(80, 0xaa_u8), + Vec::from_slice(b"Test Using Larger Than Block-Size Key - Hash Key First"), + "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()), + (Vec::from_elem(80, 0xaa_u8), + Vec::from_slice(b"Test Using Larger Than Block-Size Key \ + and Larger Than One Block-Size Data"), + "6f630fad67cda0ee1fb1f562db3aa53e".from_hex().unwrap()) + ]; + + for &(ref key, ref data, ref res) in tests.iter() { + let mut hmac = HMAC(MD5, key.as_slice()); + hmac.update(data.as_slice()); + assert_eq!(hmac.final(), *res); + } + } + + #[test] + fn test_hmac_sha1() { + // test vectors from RFC 2202 + let tests: [(Vec<u8>, Vec<u8>, Vec<u8>), ..7] = [ + (Vec::from_elem(20, 0x0b_u8), Vec::from_slice(b"Hi There"), + "b617318655057264e28bc0b6fb378c8ef146be00".from_hex().unwrap()), + (Vec::from_slice(b"Jefe"), + Vec::from_slice(b"what do ya want for nothing?"), + "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79".from_hex().unwrap()), + (Vec::from_elem(20, 0xaa_u8), Vec::from_elem(50, 0xdd_u8), + "125d7342b9ac11cd91a39af48aa17b4f63f175d3".from_hex().unwrap()), + ("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(), + Vec::from_elem(50, 0xcd_u8), + "4c9007f4026250c6bc8414f9bf50c86c2d7235da".from_hex().unwrap()), + (Vec::from_elem(20, 0x0c_u8), + Vec::from_slice(b"Test With Truncation"), + "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04".from_hex().unwrap()), + (Vec::from_elem(80, 0xaa_u8), + Vec::from_slice(b"Test Using Larger Than Block-Size Key - Hash Key First"), + "aa4ae5e15272d00e95705637ce8a3b55ed402112".from_hex().unwrap()), + (Vec::from_elem(80, 0xaa_u8), + Vec::from_slice(b"Test Using Larger Than Block-Size Key \ + and Larger Than One Block-Size Data"), + "e8e99d0f45237d786d6bbaa7965c7808bbff1a91".from_hex().unwrap()) + ]; + + for &(ref key, ref data, ref res) in tests.iter() { + let mut hmac = HMAC(SHA1, key.as_slice()); + hmac.update(data.as_slice()); + assert_eq!(hmac.final(), *res); + } + } + + fn test_sha2(ty: HashType, results: &[Vec<u8>]) { + // test vectors from RFC 4231 + let tests: [(Vec<u8>, Vec<u8>), ..6] = [ + (Vec::from_elem(20, 0x0b_u8), Vec::from_slice(b"Hi There")), + (Vec::from_slice(b"Jefe"), + Vec::from_slice(b"what do ya want for nothing?")), + (Vec::from_elem(20, 0xaa_u8), Vec::from_elem(50, 0xdd_u8)), + ("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(), + Vec::from_elem(50, 0xcd_u8)), + (Vec::from_elem(131, 0xaa_u8), + Vec::from_slice(b"Test Using Larger Than Block-Size Key - Hash Key First")), + (Vec::from_elem(131, 0xaa_u8), + Vec::from_slice(b"This is a test using a larger than block-size key and a \ + larger than block-size data. The key needs to be hashed \ + before being used by the HMAC algorithm.")) + ]; + + for (&(ref key, ref data), res) in tests.iter().zip(results.iter()) { + let mut hmac = HMAC(ty, key.as_slice()); + hmac.update(data.as_slice()); + assert_eq!(hmac.final(), *res); + } + } + + #[test] + fn test_hmac_sha224() { + let results = [ + "896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22".from_hex().unwrap(), + "a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44".from_hex().unwrap(), + "7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea".from_hex().unwrap(), + "6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a".from_hex().unwrap(), + "95e9a0db962095adaebe9b2d6f0dbce2d499f112f2d2b7273fa6870e".from_hex().unwrap(), + "3a854166ac5d9f023f54d517d0b39dbd946770db9c2b95c9f6f565d1".from_hex().unwrap() + ]; + test_sha2(SHA224, results); + } + + #[test] + fn test_hmac_sha256() { + let results = [ + "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7".from_hex().unwrap(), + "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843".from_hex().unwrap(), + "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe".from_hex().unwrap(), + "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b".from_hex().unwrap(), + "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54".from_hex().unwrap(), + "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2".from_hex().unwrap() + ]; + test_sha2(SHA256, results); + } + + #[test] + fn test_hmac_sha384() { + let results = [ + "afd03944d84895626b0825f4ab46907f\ + 15f9dadbe4101ec682aa034c7cebc59c\ + faea9ea9076ede7f4af152e8b2fa9cb6".from_hex().unwrap(), + "af45d2e376484031617f78d2b58a6b1b\ + 9c7ef464f5a01b47e42ec3736322445e\ + 8e2240ca5e69e2c78b3239ecfab21649".from_hex().unwrap(), + "88062608d3e6ad8a0aa2ace014c8a86f\ + 0aa635d947ac9febe83ef4e55966144b\ + 2a5ab39dc13814b94e3ab6e101a34f27".from_hex().unwrap(), + "3e8a69b7783c25851933ab6290af6ca7\ + 7a9981480850009cc5577c6e1f573b4e\ + 6801dd23c4a7d679ccf8a386c674cffb".from_hex().unwrap(), + "4ece084485813e9088d2c63a041bc5b4\ + 4f9ef1012a2b588f3cd11f05033ac4c6\ + 0c2ef6ab4030fe8296248df163f44952".from_hex().unwrap(), + "6617178e941f020d351e2f254e8fd32c\ + 602420feb0b8fb9adccebb82461e99c5\ + a678cc31e799176d3860e6110c46523e".from_hex().unwrap() + ]; + test_sha2(SHA384, results); + } + + #[test] + fn test_hmac_sha512() { + let results = [ + "87aa7cdea5ef619d4ff0b4241a1d6cb0\ + 2379f4e2ce4ec2787ad0b30545e17cde\ + daa833b7d6b8a702038b274eaea3f4e4\ + be9d914eeb61f1702e696c203a126854".from_hex().unwrap(), + "164b7a7bfcf819e2e395fbe73b56e0a3\ + 87bd64222e831fd610270cd7ea250554\ + 9758bf75c05a994a6d034f65f8f0e6fd\ + caeab1a34d4a6b4b636e070a38bce737".from_hex().unwrap(), + "fa73b0089d56a284efb0f0756c890be9\ + b1b5dbdd8ee81a3655f83e33b2279d39\ + bf3e848279a722c806b485a47e67c807\ + b946a337bee8942674278859e13292fb".from_hex().unwrap(), + "b0ba465637458c6990e5a8c5f61d4af7\ + e576d97ff94b872de76f8050361ee3db\ + a91ca5c11aa25eb4d679275cc5788063\ + a5f19741120c4f2de2adebeb10a298dd".from_hex().unwrap(), + "80b24263c7c1a3ebb71493c1dd7be8b4\ + 9b46d1f41b4aeec1121b013783f8f352\ + 6b56d037e05f2598bd0fd2215d6a1e52\ + 95e64f73f63f0aec8b915a985d786598".from_hex().unwrap(), + "e37b6a775dc87dbaa4dfa9f96e5e3ffd\ + debd71f8867289865df5a32d20cdc944\ + b6022cac3c4982b10d5eeb55c3e4de15\ + 134676fb6de0446065c97440fa8c6a58".from_hex().unwrap() + ]; + test_sha2(SHA512, results); + } +} diff --git a/src/crypto/mod.rs b/src/crypto/mod.rs new file mode 100644 index 00000000..d7c62f98 --- /dev/null +++ b/src/crypto/mod.rs @@ -0,0 +1,23 @@ +/* + * Copyright 2011 Google Inc. + * 2013 Jack Lloyd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +pub mod hash; +pub mod hmac; +pub mod pkcs5; +pub mod pkey; +pub mod rand; +pub mod symm; diff --git a/src/crypto/pkcs5.rs b/src/crypto/pkcs5.rs new file mode 100644 index 00000000..b795d84a --- /dev/null +++ b/src/crypto/pkcs5.rs @@ -0,0 +1,124 @@ +use libc::c_int; + +#[link(name = "crypto")] +extern { + fn PKCS5_PBKDF2_HMAC_SHA1(pass: *const u8, passlen: c_int, + salt: *const u8, saltlen: c_int, + iter: c_int, keylen: c_int, + out: *mut u8) -> c_int; +} + +/// Derives a key from a password and salt using the PBKDF2-HMAC-SHA1 algorithm. +pub fn pbkdf2_hmac_sha1(pass: &str, salt: &[u8], iter: uint, keylen: uint) -> Vec<u8> { + unsafe { + assert!(iter >= 1); + assert!(keylen >= 1); + + let mut out = Vec::with_capacity(keylen); + + let r = PKCS5_PBKDF2_HMAC_SHA1( + pass.as_ptr(), pass.len() as c_int, + salt.as_ptr(), salt.len() as c_int, + iter as c_int, keylen as c_int, + out.as_mut_ptr()); + + if r != 1 { fail!(); } + + out.set_len(keylen); + + out + } +} + +#[cfg(test)] +mod tests { + // Test vectors from + // http://tools.ietf.org/html/draft-josefsson-pbkdf2-test-vectors-06 + #[test] + fn test_pbkdf2_hmac_sha1() { + assert_eq!( + super::pbkdf2_hmac_sha1( + "password", + "salt".as_bytes(), + 1u, + 20u + ), + vec!( + 0x0c_u8, 0x60_u8, 0xc8_u8, 0x0f_u8, 0x96_u8, 0x1f_u8, 0x0e_u8, + 0x71_u8, 0xf3_u8, 0xa9_u8, 0xb5_u8, 0x24_u8, 0xaf_u8, 0x60_u8, + 0x12_u8, 0x06_u8, 0x2f_u8, 0xe0_u8, 0x37_u8, 0xa6_u8 + ) + ); + + assert_eq!( + super::pbkdf2_hmac_sha1( + "password", + "salt".as_bytes(), + 2u, + 20u + ), + vec!( + 0xea_u8, 0x6c_u8, 0x01_u8, 0x4d_u8, 0xc7_u8, 0x2d_u8, 0x6f_u8, + 0x8c_u8, 0xcd_u8, 0x1e_u8, 0xd9_u8, 0x2a_u8, 0xce_u8, 0x1d_u8, + 0x41_u8, 0xf0_u8, 0xd8_u8, 0xde_u8, 0x89_u8, 0x57_u8 + ) + ); + + assert_eq!( + super::pbkdf2_hmac_sha1( + "password", + "salt".as_bytes(), + 4096u, + 20u + ), + vec!( + 0x4b_u8, 0x00_u8, 0x79_u8, 0x01_u8, 0xb7_u8, 0x65_u8, 0x48_u8, + 0x9a_u8, 0xbe_u8, 0xad_u8, 0x49_u8, 0xd9_u8, 0x26_u8, 0xf7_u8, + 0x21_u8, 0xd0_u8, 0x65_u8, 0xa4_u8, 0x29_u8, 0xc1_u8 + ) + ); + + assert_eq!( + super::pbkdf2_hmac_sha1( + "password", + "salt".as_bytes(), + 16777216u, + 20u + ), + vec!( + 0xee_u8, 0xfe_u8, 0x3d_u8, 0x61_u8, 0xcd_u8, 0x4d_u8, 0xa4_u8, + 0xe4_u8, 0xe9_u8, 0x94_u8, 0x5b_u8, 0x3d_u8, 0x6b_u8, 0xa2_u8, + 0x15_u8, 0x8c_u8, 0x26_u8, 0x34_u8, 0xe9_u8, 0x84_u8 + ) + ); + + assert_eq!( + super::pbkdf2_hmac_sha1( + "passwordPASSWORDpassword", + "saltSALTsaltSALTsaltSALTsaltSALTsalt".as_bytes(), + 4096u, + 25u + ), + vec!( + 0x3d_u8, 0x2e_u8, 0xec_u8, 0x4f_u8, 0xe4_u8, 0x1c_u8, 0x84_u8, + 0x9b_u8, 0x80_u8, 0xc8_u8, 0xd8_u8, 0x36_u8, 0x62_u8, 0xc0_u8, + 0xe4_u8, 0x4a_u8, 0x8b_u8, 0x29_u8, 0x1a_u8, 0x96_u8, 0x4c_u8, + 0xf2_u8, 0xf0_u8, 0x70_u8, 0x38_u8 + ) + ); + + assert_eq!( + super::pbkdf2_hmac_sha1( + "pass\x00word", + "sa\x00lt".as_bytes(), + 4096u, + 16u + ), + vec!( + 0x56_u8, 0xfa_u8, 0x6a_u8, 0xa7_u8, 0x55_u8, 0x48_u8, 0x09_u8, + 0x9d_u8, 0xcc_u8, 0x37_u8, 0xd7_u8, 0xf0_u8, 0x34_u8, 0x25_u8, + 0xe0_u8, 0xc3_u8 + ) + ); + } +} diff --git a/src/crypto/pkey.rs b/src/crypto/pkey.rs new file mode 100644 index 00000000..5f617fa7 --- /dev/null +++ b/src/crypto/pkey.rs @@ -0,0 +1,425 @@ +use libc::{c_char, c_int, c_uint}; +use libc; +use std::mem; +use std::ptr; +use crypto::hash::{HashType, MD5, SHA1, SHA224, SHA256, SHA384, SHA512}; + +#[allow(non_camel_case_types)] +pub type EVP_PKEY = *mut libc::c_void; + +#[allow(non_camel_case_types)] +pub type RSA = *mut libc::c_void; + +#[link(name = "crypto")] +extern { + fn EVP_PKEY_new() -> *mut EVP_PKEY; + fn EVP_PKEY_free(k: *mut EVP_PKEY); + fn EVP_PKEY_assign(pkey: *mut EVP_PKEY, typ: c_int, key: *const c_char) -> c_int; + fn EVP_PKEY_get1_RSA(k: *mut EVP_PKEY) -> *mut RSA; + + fn i2d_PublicKey(k: *mut EVP_PKEY, buf: *const *mut u8) -> c_int; + fn d2i_PublicKey(t: c_int, k: *const *mut EVP_PKEY, buf: *const *const u8, len: c_uint) -> *mut EVP_PKEY; + fn i2d_PrivateKey(k: *mut EVP_PKEY, buf: *const *mut u8) -> c_int; + fn d2i_PrivateKey(t: c_int, k: *const *mut EVP_PKEY, buf: *const *const u8, len: c_uint) -> *mut EVP_PKEY; + + fn RSA_generate_key(modsz: c_uint, e: c_uint, cb: *const u8, cbarg: *const u8) -> *mut RSA; + fn RSA_size(k: *mut RSA) -> c_uint; + + fn RSA_public_encrypt(flen: c_uint, from: *const u8, to: *mut u8, k: *mut RSA, + pad: c_int) -> c_int; + fn RSA_private_decrypt(flen: c_uint, from: *const u8, to: *mut u8, k: *mut RSA, + pad: c_int) -> c_int; + fn RSA_sign(t: c_int, m: *const u8, mlen: c_uint, sig: *mut u8, siglen: *mut c_uint, + k: *mut RSA) -> c_int; + fn RSA_verify(t: c_int, m: *const u8, mlen: c_uint, sig: *const u8, siglen: c_uint, + k: *mut RSA) -> c_int; +} + +enum Parts { + Neither, + Public, + Both +} + +/// Represents a role an asymmetric key might be appropriate for. +pub enum Role { + Encrypt, + Decrypt, + Sign, + Verify +} + +/// Type of encryption padding to use. +pub enum EncryptionPadding { + OAEP, + PKCS1v15 +} + +fn openssl_padding_code(padding: EncryptionPadding) -> c_int { + match padding { + OAEP => 4, + PKCS1v15 => 1 + } +} + +fn openssl_hash_nid(hash: HashType) -> c_int { + match hash { + MD5 => 4, // NID_md5, + SHA1 => 64, // NID_sha1 + SHA224 => 675, // NID_sha224 + SHA256 => 672, // NID_sha256 + SHA384 => 673, // NID_sha384 + SHA512 => 674, // NID_sha512 + } +} + +pub struct PKey { + evp: *mut EVP_PKEY, + parts: Parts, +} + +/// Represents a public key, optionally with a private key attached. +impl PKey { + pub fn new() -> PKey { + unsafe { + PKey { + evp: EVP_PKEY_new(), + parts: Neither, + } + } + } + + fn _tostr(&self, f: unsafe extern "C" fn(*mut EVP_PKEY, *const *mut u8) -> c_int) -> Vec<u8> { + unsafe { + let len = f(self.evp, ptr::null()); + if len < 0 as c_int { return vec!(); } + let mut s = Vec::from_elem(len as uint, 0u8); + + let r = f(self.evp, &s.as_mut_ptr()); + + s.truncate(r as uint); + s + } + } + + fn _fromstr(&mut self, s: &[u8], f: unsafe extern "C" fn(c_int, *const *mut EVP_PKEY, *const *const u8, c_uint) -> *mut EVP_PKEY) { + unsafe { + let evp = ptr::mut_null(); + f(6 as c_int, &evp, &s.as_ptr(), s.len() as c_uint); + self.evp = evp; + } + } + + pub fn gen(&mut self, keysz: uint) { + unsafe { + let rsa = RSA_generate_key( + keysz as c_uint, + 65537u as c_uint, + ptr::null(), + ptr::null() + ); + + // XXX: 6 == NID_rsaEncryption + EVP_PKEY_assign( + self.evp, + 6 as c_int, + mem::transmute(rsa)); + + self.parts = Both; + } + } + + /** + * Returns a serialized form of the public key, suitable for load_pub(). + */ + pub fn save_pub(&self) -> Vec<u8> { + self._tostr(i2d_PublicKey) + } + + /** + * Loads a serialized form of the public key, as produced by save_pub(). + */ + pub fn load_pub(&mut self, s: &[u8]) { + self._fromstr(s, d2i_PublicKey); + self.parts = Public; + } + + /** + * Returns a serialized form of the public and private keys, suitable for + * load_priv(). + */ + pub fn save_priv(&self) -> Vec<u8> { + self._tostr(i2d_PrivateKey) + } + /** + * Loads a serialized form of the public and private keys, as produced by + * save_priv(). + */ + pub fn load_priv(&mut self, s: &[u8]) { + self._fromstr(s, d2i_PrivateKey); + self.parts = Both; + } + + /** + * Returns the size of the public key modulus. + */ + pub fn size(&self) -> uint { + unsafe { + RSA_size(EVP_PKEY_get1_RSA(self.evp)) as uint + } + } + + /** + * Returns whether this pkey object can perform the specified role. + */ + pub fn can(&self, r: Role) -> bool { + match r { + Encrypt => + match self.parts { + Neither => false, + _ => true, + }, + Verify => + match self.parts { + Neither => false, + _ => true, + }, + Decrypt => + match self.parts { + Both => true, + _ => false, + }, + Sign => + match self.parts { + Both => true, + _ => false, + }, + } + } + + /** + * Returns the maximum amount of data that can be encrypted by an encrypt() + * call. + */ + pub fn max_data(&self) -> uint { + unsafe { + let rsa = EVP_PKEY_get1_RSA(self.evp); + let len = RSA_size(rsa); + + // 41 comes from RSA_public_encrypt(3) for OAEP + len as uint - 41u + } + } + + pub fn encrypt_with_padding(&self, s: &[u8], padding: EncryptionPadding) -> Vec<u8> { + unsafe { + let rsa = EVP_PKEY_get1_RSA(self.evp); + let len = RSA_size(rsa); + + assert!(s.len() < self.max_data()); + + let mut r = Vec::from_elem(len as uint + 1u, 0u8); + + let rv = RSA_public_encrypt( + s.len() as c_uint, + s.as_ptr(), + r.as_mut_ptr(), + rsa, + openssl_padding_code(padding)); + + if rv < 0 as c_int { + vec!() + } else { + r.truncate(rv as uint); + r + } + } + } + + pub fn decrypt_with_padding(&self, s: &[u8], padding: EncryptionPadding) -> Vec<u8> { + unsafe { + let rsa = EVP_PKEY_get1_RSA(self.evp); + let len = RSA_size(rsa); + + assert_eq!(s.len() as c_uint, RSA_size(rsa)); + + let mut r = Vec::from_elem(len as uint + 1u, 0u8); + + let rv = RSA_private_decrypt( + s.len() as c_uint, + s.as_ptr(), + r.as_mut_ptr(), + rsa, + openssl_padding_code(padding)); + + if rv < 0 as c_int { + vec!() + } else { + r.truncate(rv as uint); + r + } + } + } + + /** + * Encrypts data using OAEP padding, returning the encrypted data. The + * supplied data must not be larger than max_data(). + */ + pub fn encrypt(&self, s: &[u8]) -> Vec<u8> { self.encrypt_with_padding(s, OAEP) } + + /** + * Decrypts data, expecting OAEP padding, returning the decrypted data. + */ + pub fn decrypt(&self, s: &[u8]) -> Vec<u8> { self.decrypt_with_padding(s, OAEP) } + + /** + * Signs data, using OpenSSL's default scheme and sha256. Unlike encrypt(), + * can process an arbitrary amount of data; returns the signature. + */ + pub fn sign(&self, s: &[u8]) -> Vec<u8> { self.sign_with_hash(s, SHA256) } + + /** + * Verifies a signature s (using OpenSSL's default scheme and sha256) on a + * message m. Returns true if the signature is valid, and false otherwise. + */ + pub fn verify(&self, m: &[u8], s: &[u8]) -> bool { self.verify_with_hash(m, s, SHA256) } + + pub fn sign_with_hash(&self, s: &[u8], hash: HashType) -> Vec<u8> { + unsafe { + let rsa = EVP_PKEY_get1_RSA(self.evp); + let mut len = RSA_size(rsa); + let mut r = Vec::from_elem(len as uint + 1u, 0u8); + + let rv = RSA_sign( + openssl_hash_nid(hash), + s.as_ptr(), + s.len() as c_uint, + r.as_mut_ptr(), + &mut len, + rsa); + + if rv < 0 as c_int { + vec!() + } else { + r.truncate(len as uint); + r + } + } + } + + pub fn verify_with_hash(&self, m: &[u8], s: &[u8], hash: HashType) -> bool { + unsafe { + let rsa = EVP_PKEY_get1_RSA(self.evp); + + let rv = RSA_verify( + openssl_hash_nid(hash), + m.as_ptr(), + m.len() as c_uint, + s.as_ptr(), + s.len() as c_uint, + rsa + ); + + rv == 1 as c_int + } + } +} + +impl Drop for PKey { + fn drop(&mut self) { + unsafe { + EVP_PKEY_free(self.evp); + } + } +} + +#[cfg(test)] +mod tests { + use crypto::hash::{MD5, SHA1}; + + #[test] + fn test_gen_pub() { + let mut k0 = super::PKey::new(); + let mut k1 = super::PKey::new(); + k0.gen(512u); + k1.load_pub(k0.save_pub().as_slice()); + assert_eq!(k0.save_pub(), k1.save_pub()); + assert_eq!(k0.size(), k1.size()); + assert!(k0.can(super::Encrypt)); + assert!(k0.can(super::Decrypt)); + assert!(k0.can(super::Verify)); + assert!(k0.can(super::Sign)); + assert!(k1.can(super::Encrypt)); + assert!(!k1.can(super::Decrypt)); + assert!(k1.can(super::Verify)); + assert!(!k1.can(super::Sign)); + } + + #[test] + fn test_gen_priv() { + let mut k0 = super::PKey::new(); + let mut k1 = super::PKey::new(); + k0.gen(512u); + k1.load_priv(k0.save_priv().as_slice()); + assert_eq!(k0.save_priv(), k1.save_priv()); + assert_eq!(k0.size(), k1.size()); + assert!(k0.can(super::Encrypt)); + assert!(k0.can(super::Decrypt)); + assert!(k0.can(super::Verify)); + assert!(k0.can(super::Sign)); + assert!(k1.can(super::Encrypt)); + assert!(k1.can(super::Decrypt)); + assert!(k1.can(super::Verify)); + assert!(k1.can(super::Sign)); + } + + #[test] + fn test_encrypt() { + let mut k0 = super::PKey::new(); + let mut k1 = super::PKey::new(); + let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); + k0.gen(512u); + k1.load_pub(k0.save_pub().as_slice()); + let emsg = k1.encrypt(msg.as_slice()); + let dmsg = k0.decrypt(emsg.as_slice()); + assert!(msg == dmsg); + } + + #[test] + fn test_encrypt_pkcs() { + let mut k0 = super::PKey::new(); + let mut k1 = super::PKey::new(); + let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); + k0.gen(512u); + k1.load_pub(k0.save_pub().as_slice()); + let emsg = k1.encrypt_with_padding(msg.as_slice(), super::PKCS1v15); + let dmsg = k0.decrypt_with_padding(emsg.as_slice(), super::PKCS1v15); + assert!(msg == dmsg); + } + + #[test] + fn test_sign() { + let mut k0 = super::PKey::new(); + let mut k1 = super::PKey::new(); + let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); + k0.gen(512u); + k1.load_pub(k0.save_pub().as_slice()); + let sig = k0.sign(msg.as_slice()); + let rv = k1.verify(msg.as_slice(), sig.as_slice()); + assert!(rv == true); + } + + #[test] + fn test_sign_hashes() { + let mut k0 = super::PKey::new(); + let mut k1 = super::PKey::new(); + let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8); + k0.gen(512u); + k1.load_pub(k0.save_pub().as_slice()); + + let sig = k0.sign_with_hash(msg.as_slice(), MD5); + + assert!(k1.verify_with_hash(msg.as_slice(), sig.as_slice(), MD5)); + assert!(!k1.verify_with_hash(msg.as_slice(), sig.as_slice(), SHA1)); + } +} diff --git a/src/crypto/rand.rs b/src/crypto/rand.rs new file mode 100644 index 00000000..9db87fcd --- /dev/null +++ b/src/crypto/rand.rs @@ -0,0 +1,30 @@ +use libc::c_int; + +#[link(name = "crypto")] +extern { + fn RAND_bytes(buf: *mut u8, num: c_int) -> c_int; +} + +pub fn rand_bytes(len: uint) -> Vec<u8> { + unsafe { + let mut out = Vec::with_capacity(len); + + let r = RAND_bytes(out.as_mut_ptr(), len as c_int); + if r != 1 as c_int { fail!() } + + out.set_len(len); + + out + } +} + +#[cfg(test)] +mod tests { + use super::rand_bytes; + + #[test] + fn test_rand_bytes() { + let bytes = rand_bytes(32u); + println!("{}", bytes); + } +} diff --git a/src/crypto/symm.rs b/src/crypto/symm.rs new file mode 100644 index 00000000..8d8f651c --- /dev/null +++ b/src/crypto/symm.rs @@ -0,0 +1,276 @@ +use libc::{c_int, c_uint}; +use libc; + +#[allow(non_camel_case_types)] +pub type EVP_CIPHER_CTX = *mut libc::c_void; + +#[allow(non_camel_case_types)] +pub type EVP_CIPHER = *mut libc::c_void; + +#[link(name = "crypto")] +extern { + fn EVP_CIPHER_CTX_new() -> EVP_CIPHER_CTX; + fn EVP_CIPHER_CTX_set_padding(ctx: EVP_CIPHER_CTX, padding: c_int); + fn EVP_CIPHER_CTX_free(ctx: EVP_CIPHER_CTX); + + fn EVP_aes_128_ecb() -> EVP_CIPHER; + fn EVP_aes_128_cbc() -> EVP_CIPHER; + // fn EVP_aes_128_ctr() -> EVP_CIPHER; + // fn EVP_aes_128_gcm() -> EVP_CIPHER; + + fn EVP_aes_256_ecb() -> EVP_CIPHER; + fn EVP_aes_256_cbc() -> EVP_CIPHER; + // fn EVP_aes_256_ctr() -> EVP_CIPHER; + // fn EVP_aes_256_gcm() -> EVP_CIPHER; + + fn EVP_rc4() -> EVP_CIPHER; + + fn EVP_CipherInit(ctx: EVP_CIPHER_CTX, evp: EVP_CIPHER, + key: *const u8, iv: *const u8, mode: c_int); + fn EVP_CipherUpdate(ctx: EVP_CIPHER_CTX, outbuf: *mut u8, + outlen: &mut c_uint, inbuf: *const u8, inlen: c_int); + fn EVP_CipherFinal(ctx: EVP_CIPHER_CTX, res: *mut u8, len: &mut c_int); +} + +pub enum Mode { + Encrypt, + Decrypt, +} + +#[allow(non_camel_case_types)] +pub enum Type { + AES_128_ECB, + AES_128_CBC, + // AES_128_CTR, + //AES_128_GCM, + + AES_256_ECB, + AES_256_CBC, + // AES_256_CTR, + //AES_256_GCM, + + RC4_128, +} + +fn evpc(t: Type) -> (EVP_CIPHER, uint, uint) { + unsafe { + match t { + AES_128_ECB => (EVP_aes_128_ecb(), 16u, 16u), + AES_128_CBC => (EVP_aes_128_cbc(), 16u, 16u), + // AES_128_CTR => (EVP_aes_128_ctr(), 16u, 0u), + //AES_128_GCM => (EVP_aes_128_gcm(), 16u, 16u), + + AES_256_ECB => (EVP_aes_256_ecb(), 32u, 16u), + AES_256_CBC => (EVP_aes_256_cbc(), 32u, 16u), + // AES_256_CTR => (EVP_aes_256_ctr(), 32u, 0u), + //AES_256_GCM => (EVP_aes_256_gcm(), 32u, 16u), + + RC4_128 => (EVP_rc4(), 16u, 0u), + } + } +} + +/// Represents a symmetric cipher context. +pub struct Crypter { + evp: EVP_CIPHER, + ctx: EVP_CIPHER_CTX, + keylen: uint, + blocksize: uint +} + +impl Crypter { + pub fn new(t: Type) -> Crypter { + let ctx = unsafe { EVP_CIPHER_CTX_new() }; + let (evp, keylen, blocksz) = evpc(t); + Crypter { evp: evp, ctx: ctx, keylen: keylen, blocksize: blocksz } + } + + /** + * Enables or disables padding. If padding is disabled, total amount of + * data encrypted must be a multiple of block size. + */ + pub fn pad(&self, padding: bool) { + if self.blocksize > 0 { + unsafe { + let v = if padding { 1 } else { 0 } as c_int; + EVP_CIPHER_CTX_set_padding(self.ctx, v); + } + } + } + + /** + * Initializes this crypter. + */ + pub fn init(&self, mode: Mode, key: &[u8], iv: Vec<u8>) { + unsafe { + let mode = match mode { + Encrypt => 1 as c_int, + Decrypt => 0 as c_int, + }; + assert_eq!(key.len(), self.keylen); + + EVP_CipherInit( + self.ctx, + self.evp, + key.as_ptr(), + iv.as_ptr(), + mode + ) + } + } + + /** + * Update this crypter with more data to encrypt or decrypt. Returns + * encrypted or decrypted bytes. + */ + pub fn update(&self, data: &[u8]) -> Vec<u8> { + unsafe { + let mut res = Vec::from_elem(data.len() + self.blocksize, 0u8); + let mut reslen = (data.len() + self.blocksize) as u32; + + EVP_CipherUpdate( + self.ctx, + res.as_mut_ptr(), + &mut reslen, + data.as_ptr(), + data.len() as c_int + ); + + res.truncate(reslen as uint); + res + } + } + + /** + * Finish crypting. Returns the remaining partial block of output, if any. + */ + pub fn final(&self) -> Vec<u8> { + unsafe { + let mut res = Vec::from_elem(self.blocksize, 0u8); + let mut reslen = self.blocksize as c_int; + + EVP_CipherFinal(self.ctx, + res.as_mut_ptr(), + &mut reslen); + + res.truncate(reslen as uint); + res + } + } +} + +impl Drop for Crypter { + fn drop(&mut self) { + unsafe { + EVP_CIPHER_CTX_free(self.ctx); + } + } +} + +/** + * Encrypts data, using the specified crypter type in encrypt mode with the + * specified key and iv; returns the resulting (encrypted) data. + */ +pub fn encrypt(t: Type, key: &[u8], iv: Vec<u8>, data: &[u8]) -> Vec<u8> { + let c = Crypter::new(t); + c.init(Encrypt, key, iv); + let r = c.update(data); + let rest = c.final(); + r.append(rest.as_slice()) +} + +/** + * Decrypts data, using the specified crypter type in decrypt mode with the + * specified key and iv; returns the resulting (decrypted) data. + */ +pub fn decrypt(t: Type, key: &[u8], iv: Vec<u8>, data: &[u8]) -> Vec<u8> { + let c = Crypter::new(t); + c.init(Decrypt, key, iv); + let r = c.update(data); + let rest = c.final(); + r.append(rest.as_slice()) +} + +#[cfg(test)] +mod tests { + use serialize::hex::FromHex; + + // Test vectors from FIPS-197: + // http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf + #[test] + fn test_aes_256_ecb() { + let k0 = + vec!(0x00u8, 0x01u8, 0x02u8, 0x03u8, 0x04u8, 0x05u8, 0x06u8, 0x07u8, + 0x08u8, 0x09u8, 0x0au8, 0x0bu8, 0x0cu8, 0x0du8, 0x0eu8, 0x0fu8, + 0x10u8, 0x11u8, 0x12u8, 0x13u8, 0x14u8, 0x15u8, 0x16u8, 0x17u8, + 0x18u8, 0x19u8, 0x1au8, 0x1bu8, 0x1cu8, 0x1du8, 0x1eu8, 0x1fu8); + let p0 = + vec!(0x00u8, 0x11u8, 0x22u8, 0x33u8, 0x44u8, 0x55u8, 0x66u8, 0x77u8, + 0x88u8, 0x99u8, 0xaau8, 0xbbu8, 0xccu8, 0xddu8, 0xeeu8, 0xffu8); + let c0 = + vec!(0x8eu8, 0xa2u8, 0xb7u8, 0xcau8, 0x51u8, 0x67u8, 0x45u8, 0xbfu8, + 0xeau8, 0xfcu8, 0x49u8, 0x90u8, 0x4bu8, 0x49u8, 0x60u8, 0x89u8); + let c = super::Crypter::new(super::AES_256_ECB); + c.init(super::Encrypt, k0.as_slice(), vec![]); + c.pad(false); + let r0 = c.update(p0.as_slice()).append(c.final().as_slice()); + assert!(r0 == c0); + c.init(super::Decrypt, k0.as_slice(), vec![]); + c.pad(false); + let p1 = c.update(r0.as_slice()).append(c.final().as_slice()); + assert!(p1 == p0); + } + + fn cipher_test(ciphertype: super::Type, pt: &str, ct: &str, key: &str, iv: &str) { + use serialize::hex::ToHex; + + let cipher = super::Crypter::new(ciphertype); + cipher.init(super::Encrypt, key.from_hex().unwrap().as_slice(), iv.from_hex().unwrap()); + + let expected = Vec::from_slice(ct.from_hex().unwrap().as_slice()); + let computed = cipher.update(pt.from_hex().unwrap().as_slice()).append(cipher.final().as_slice()); + + if computed != expected { + println!("Computed: {}", computed.as_slice().to_hex()); + println!("Expected: {}", expected.as_slice().to_hex()); + if computed.len() != expected.len() { + println!("Lengths differ: {} in computed vs {} expected", + computed.len(), expected.len()); + } + fail!("test failure"); + } + } + + #[test] + fn test_rc4() { + + let pt = "0000000000000000000000000000000000000000000000000000000000000000000000000000"; + let ct = "A68686B04D686AA107BD8D4CAB191A3EEC0A6294BC78B60F65C25CB47BD7BB3A48EFC4D26BE4"; + let key = "97CD440324DA5FD1F7955C1C13B6B466"; + let iv = ""; + + cipher_test(super::RC4_128, pt, ct, key, iv); + } + + /*#[test] + fn test_aes128_ctr() { + + let pt = ~"6BC1BEE22E409F96E93D7E117393172AAE2D8A571E03AC9C9EB76FAC45AF8E5130C81C46A35CE411E5FBC1191A0A52EFF69F2445DF4F9B17AD2B417BE66C3710"; + let ct = ~"874D6191B620E3261BEF6864990DB6CE9806F66B7970FDFF8617187BB9FFFDFF5AE4DF3EDBD5D35E5B4F09020DB03EAB1E031DDA2FBE03D1792170A0F3009CEE"; + let key = ~"2B7E151628AED2A6ABF7158809CF4F3C"; + let iv = ~"F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF"; + + cipher_test(super::AES_128_CTR, pt, ct, key, iv); + }*/ + + /*#[test] + fn test_aes128_gcm() { + // Test case 3 in GCM spec + let pt = ~"d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255"; + let ct = ~"42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091473f59854d5c2af327cd64a62cf35abd2ba6fab4"; + let key = ~"feffe9928665731c6d6a8f9467308308"; + let iv = ~"cafebabefacedbaddecaf888"; + + cipher_test(super::AES_128_GCM, pt, ct, key, iv); + }*/ +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 00000000..3e0f3b92 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,14 @@ +#![feature(struct_variant, macro_rules)] +#![crate_name="openssl"] +#![crate_type="rlib"] +#![crate_type="dylib"] +#![doc(html_root_url="http://www.rust-ci.org/sfackler/rust-openssl/doc")] + +extern crate libc; +#[cfg(test)] +extern crate serialize; +extern crate sync; + +pub mod ssl; +pub mod crypto; +pub mod bn; diff --git a/src/ssl/error.rs b/src/ssl/error.rs new file mode 100644 index 00000000..dd387e2f --- /dev/null +++ b/src/ssl/error.rs @@ -0,0 +1,60 @@ +use libc::c_ulong; +use std::io::IoError; + +use ssl::ffi; + +/// An SSL error +#[deriving(Show)] +pub enum SslError { + /// The underlying stream has reported an error + StreamError(IoError), + /// The SSL session has been closed by the other end + SslSessionClosed, + /// An error in the OpenSSL library + OpenSslErrors(Vec<OpensslError>) +} + +/// An error from the OpenSSL library +#[deriving(Show)] +pub enum OpensslError { + /// An unknown error + UnknownError { + /// The library reporting the error + library: u8, + /// The function reporting the error + function: u16, + /// The reason for the error + reason: u16 + } +} + +fn get_lib(err: c_ulong) -> u8 { + ((err >> 24) & 0xff) as u8 +} + +fn get_func(err: c_ulong) -> u16 { + ((err >> 12) & 0xfff) as u16 +} + +fn get_reason(err: c_ulong) -> u16 { + (err & 0xfff) as u16 +} + +impl SslError { + /// Creates a new `OpenSslErrors` with the current contents of the error + /// stack. + pub fn get() -> SslError { + let mut errs = vec!(); + loop { + match unsafe { ffi::ERR_get_error() } { + 0 => break, + err => errs.push(UnknownError { + library: get_lib(err), + function: get_func(err), + reason: get_reason(err) + }) + } + } + OpenSslErrors(errs) + } +} diff --git a/src/ssl/ffi.rs b/src/ssl/ffi.rs new file mode 100644 index 00000000..4677c189 --- /dev/null +++ b/src/ssl/ffi.rs @@ -0,0 +1,159 @@ +#![allow(non_camel_case_types)] + +use libc::{c_int, c_void, c_long, c_ulong, c_char}; + +pub type SSL_CTX = c_void; +pub type SSL_METHOD = c_void; +pub type SSL = c_void; +pub type BIO = c_void; +pub type BIO_METHOD = c_void; +pub type X509_STORE_CTX = c_void; +pub type X509 = c_void; +pub type X509_NAME = c_void; +pub type CRYPTO_EX_DATA = c_void; + +pub type CRYPTO_EX_new = extern "C" fn(parent: *mut c_void, ptr: *mut c_void, + ad: *const CRYPTO_EX_DATA, idx: c_int, + argl: c_long, argp: *const c_void) -> c_int; +pub type CRYPTO_EX_dup = extern "C" fn(to: *mut CRYPTO_EX_DATA, + from: *mut CRYPTO_EX_DATA, from_d: *mut c_void, + idx: c_int, argl: c_long, argp: *mut c_void) + -> c_int; +pub type CRYPTO_EX_free = extern "C" fn(parent: *mut c_void, ptr: *mut c_void, + ad: *mut CRYPTO_EX_DATA, idx: c_int, + argl: c_long, argp: *mut c_void); + +pub static CRYPTO_LOCK: c_int = 1; + +pub static SSL_ERROR_NONE: c_int = 0; +pub static SSL_ERROR_SSL: c_int = 1; +pub static SSL_ERROR_WANT_READ: c_int = 2; +pub static SSL_ERROR_WANT_WRITE: c_int = 3; +pub static SSL_ERROR_WANT_X509_LOOKUP: c_int = 4; +pub static SSL_ERROR_SYSCALL: c_int = 5; +pub static SSL_ERROR_ZERO_RETURN: c_int = 6; +pub static SSL_ERROR_WANT_CONNECT: c_int = 7; +pub static SSL_ERROR_WANT_ACCEPT: c_int = 8; + +pub static SSL_VERIFY_NONE: c_int = 0; +pub static SSL_VERIFY_PEER: c_int = 1; + +pub static X509_V_OK: c_int = 0; +pub static X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: c_int = 2; +pub static X509_V_ERR_UNABLE_TO_GET_CRL: c_int = 3; +pub static X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE: c_int = 4; +pub static X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: c_int = 5; +pub static X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: c_int = 6; +pub static X509_V_ERR_CERT_SIGNATURE_FAILURE: c_int = 7; +pub static X509_V_ERR_CRL_SIGNATURE_FAILURE: c_int = 8; +pub static X509_V_ERR_CERT_NOT_YET_VALID: c_int = 9; +pub static X509_V_ERR_CERT_HAS_EXPIRED: c_int = 10; +pub static X509_V_ERR_CRL_NOT_YET_VALID: c_int = 11; +pub static X509_V_ERR_CRL_HAS_EXPIRED: c_int = 12; +pub static X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: c_int = 13; +pub static X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: c_int = 14; +pub static X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: c_int = 15; +pub static X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: c_int = 16; +pub static X509_V_ERR_OUT_OF_MEM: c_int = 17; +pub static X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: c_int = 18; +pub static X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: c_int = 19; +pub static X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: c_int = 20; +pub static X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: c_int = 21; +pub static X509_V_ERR_CERT_CHAIN_TOO_LONG: c_int = 22; +pub static X509_V_ERR_CERT_REVOKED: c_int = 23; +pub static X509_V_ERR_INVALID_CA: c_int = 24; +pub static X509_V_ERR_PATH_LENGTH_EXCEEDED: c_int = 25; +pub static X509_V_ERR_INVALID_PURPOSE: c_int = 26; +pub static X509_V_ERR_CERT_UNTRUSTED: c_int = 27; +pub static X509_V_ERR_CERT_REJECTED: c_int = 28; +pub static X509_V_ERR_SUBJECT_ISSUER_MISMATCH: c_int = 29; +pub static X509_V_ERR_AKID_SKID_MISMATCH: c_int = 30; +pub static X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH: c_int = 31; +pub static X509_V_ERR_KEYUSAGE_NO_CERTSIGN: c_int = 32; +pub static X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER: c_int = 33; +pub static X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION: c_int = 34; +pub static X509_V_ERR_KEYUSAGE_NO_CRL_SIGN: c_int = 35; +pub static X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION: c_int = 36; +pub static X509_V_ERR_INVALID_NON_CA: c_int = 37; +pub static X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED: c_int = 38; +pub static X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE: c_int = 39; +pub static X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED: c_int = 40; +pub static X509_V_ERR_INVALID_EXTENSION: c_int = 41; +pub static X509_V_ERR_INVALID_POLICY_EXTENSION: c_int = 42; +pub static X509_V_ERR_NO_EXPLICIT_POLICY: c_int = 43; +pub static X509_V_ERR_DIFFERENT_CRL_SCOPE: c_int = 44; +pub static X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE: c_int = 45; +pub static X509_V_ERR_UNNESTED_RESOURCE: c_int = 46; +pub static X509_V_ERR_PERMITTED_VIOLATION: c_int = 47; +pub static X509_V_ERR_EXCLUDED_VIOLATION: c_int = 48; +pub static X509_V_ERR_SUBTREE_MINMAX: c_int = 49; +pub static X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE: c_int = 51; +pub static X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX: c_int = 52; +pub static X509_V_ERR_UNSUPPORTED_NAME_SYNTAX: c_int = 53; +pub static X509_V_ERR_CRL_PATH_VALIDATION_ERROR: c_int = 54; +pub static X509_V_ERR_APPLICATION_VERIFICATION: c_int = 50; + +#[link(name="ssl")] +#[link(name="crypto")] +extern "C" { + pub fn CRYPTO_num_locks() -> c_int; + pub fn CRYPTO_set_locking_callback(func: extern "C" fn(mode: c_int, + n: c_int, + file: *const c_char, + line: c_int)); + + pub fn ERR_get_error() -> c_ulong; + + pub fn SSL_library_init() -> c_int; + + #[cfg(sslv2)] + pub fn SSLv2_method() -> *const SSL_METHOD; + pub fn SSLv3_method() -> *const SSL_METHOD; + pub fn TLSv1_method() -> *const SSL_METHOD; + pub fn SSLv23_method() -> *const SSL_METHOD; + + pub fn SSL_CTX_new(method: *const SSL_METHOD) -> *mut SSL_CTX; + pub fn SSL_CTX_free(ctx: *mut SSL_CTX); + pub fn SSL_CTX_set_verify(ctx: *mut SSL_CTX, mode: c_int, + verify_callback: Option<extern fn(c_int, *mut X509_STORE_CTX) -> c_int>); + pub fn SSL_CTX_load_verify_locations(ctx: *mut SSL_CTX, CAfile: *const c_char, + CApath: *const c_char) -> c_int; + pub fn SSL_CTX_get_ex_new_index(argl: c_long, argp: *const c_void, + new_func: Option<CRYPTO_EX_new>, + dup_func: Option<CRYPTO_EX_dup>, + free_func: Option<CRYPTO_EX_free>) + -> c_int; + pub fn SSL_CTX_set_ex_data(ctx: *mut SSL_CTX, idx: c_int, data: *mut c_void) + -> c_int; + pub fn SSL_CTX_get_ex_data(ctx: *mut SSL_CTX, idx: c_int) -> *mut c_void; + + pub fn X509_STORE_CTX_get_ex_data(ctx: *mut X509_STORE_CTX, idx: c_int) + -> *mut c_void; + pub fn X509_STORE_CTX_get_current_cert(ct: *mut X509_STORE_CTX) -> *mut X509; + pub fn X509_STORE_CTX_get_error(ctx: *mut X509_STORE_CTX) -> c_int; + + pub fn X509_get_subject_name(x: *mut X509) -> *mut X509_NAME; + + pub fn SSL_new(ctx: *mut SSL_CTX) -> *mut SSL; + pub fn SSL_free(ssl: *mut SSL); + pub fn SSL_set_bio(ssl: *mut SSL, rbio: *mut BIO, wbio: *mut BIO); + pub fn SSL_get_rbio(ssl: *mut SSL) -> *mut BIO; + pub fn SSL_get_wbio(ssl: *mut SSL) -> *mut BIO; + pub fn SSL_connect(ssl: *mut SSL) -> c_int; + pub fn SSL_get_error(ssl: *mut SSL, ret: c_int) -> c_int; + pub fn SSL_read(ssl: *mut SSL, buf: *mut c_void, num: c_int) -> c_int; + pub fn SSL_write(ssl: *mut SSL, buf: *const c_void, num: c_int) -> c_int; + pub fn SSL_get_ex_data_X509_STORE_CTX_idx() -> c_int; + pub fn SSL_get_SSL_CTX(ssl: *mut SSL) -> *mut SSL_CTX; + + pub fn BIO_s_mem() -> *const BIO_METHOD; + pub fn BIO_new(type_: *const BIO_METHOD) -> *mut BIO; + pub fn BIO_free_all(a: *mut BIO); + pub fn BIO_read(b: *mut BIO, buf: *mut c_void, len: c_int) -> c_int; + pub fn BIO_write(b: *mut BIO, buf: *const c_void, len: c_int) -> c_int; +} + +#[cfg(target_os = "win32")] +#[link(name="gdi32")] +#[link(name="wsock32")] +extern { } diff --git a/src/ssl/mod.rs b/src/ssl/mod.rs new file mode 100644 index 00000000..7c9b2d60 --- /dev/null +++ b/src/ssl/mod.rs @@ -0,0 +1,541 @@ +use libc::{c_int, c_void, c_char}; +use std::io::{IoResult, IoError, EndOfFile, Stream, Reader, Writer}; +use std::mem; +use std::ptr; +use std::rt::mutex::NativeMutex; +use sync::one::{Once, ONCE_INIT}; + +use ssl::error::{SslError, SslSessionClosed, StreamError}; + +pub mod error; +mod ffi; +#[cfg(test)] +mod tests; + +static mut VERIFY_IDX: c_int = -1; +static mut MUTEXES: *mut Vec<NativeMutex> = 0 as *mut Vec<NativeMutex>; + +macro_rules! try_ssl( + ($e:expr) => ( + match $e { + Ok(ok) => ok, + Err(err) => return Err(StreamError(err)) + } + ) +) + +fn init() { + static mut INIT: Once = ONCE_INIT; + + unsafe { + INIT.doit(|| { + ffi::SSL_library_init(); + let verify_idx = ffi::SSL_CTX_get_ex_new_index(0, ptr::null(), None, + None, None); + assert!(verify_idx >= 0); + VERIFY_IDX = verify_idx; + + let num_locks = ffi::CRYPTO_num_locks(); + let mutexes = box Vec::from_fn(num_locks as uint, |_| NativeMutex::new()); + MUTEXES = mem::transmute(mutexes); + + ffi::CRYPTO_set_locking_callback(locking_function); + }); + } +} + +/// Determines the SSL method supported +pub enum SslMethod { + #[cfg(sslv2)] + /// Only support the SSLv2 protocol + Sslv2, + /// Only support the SSLv3 protocol + Sslv3, + /// Only support the TLSv1 protocol + Tlsv1, + /// Support the SSLv2, SSLv3 and TLSv1 protocols + Sslv23, +} + +impl SslMethod { + unsafe fn to_raw(&self) -> *const ffi::SSL_METHOD { + match *self { + #[cfg(sslv2)] + Sslv2 => ffi::SSLv2_method(), + Sslv3 => ffi::SSLv3_method(), + Tlsv1 => ffi::TLSv1_method(), + Sslv23 => ffi::SSLv23_method() + } + } +} + +/// Determines the type of certificate verification used +#[repr(i32)] +pub enum SslVerifyMode { + /// Verify that the server's certificate is trusted + SslVerifyPeer = ffi::SSL_VERIFY_PEER, + /// Do not verify the server's certificate + SslVerifyNone = ffi::SSL_VERIFY_NONE +} + +extern fn locking_function(mode: c_int, n: c_int, _file: *const c_char, + _line: c_int) { + unsafe { + let mutex = (*MUTEXES).get_mut(n as uint); + + if mode & ffi::CRYPTO_LOCK != 0 { + mutex.lock_noguard(); + } else { + mutex.unlock_noguard(); + } + } +} + +extern fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) + -> c_int { + unsafe { + let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx(); + let ssl = ffi::X509_STORE_CTX_get_ex_data(x509_ctx, idx); + let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); + let verify = ffi::SSL_CTX_get_ex_data(ssl_ctx, VERIFY_IDX); + let verify: Option<VerifyCallback> = mem::transmute(verify); + + let ctx = X509StoreContext { ctx: x509_ctx }; + + match verify { + None => preverify_ok, + Some(verify) => verify(preverify_ok != 0, &ctx) as c_int + } + } +} + +/// The signature of functions that can be used to manually verify certificates +pub type VerifyCallback = fn(preverify_ok: bool, + x509_ctx: &X509StoreContext) -> bool; + +/// An SSL context object +pub struct SslContext { + ctx: *mut ffi::SSL_CTX +} + +impl Drop for SslContext { + fn drop(&mut self) { + unsafe { ffi::SSL_CTX_free(self.ctx) } + } +} + +impl SslContext { + /// Attempts to create a new SSL context. + pub fn try_new(method: SslMethod) -> Result<SslContext, SslError> { + init(); + + let ctx = unsafe { ffi::SSL_CTX_new(method.to_raw()) }; + if ctx == ptr::mut_null() { + return Err(SslError::get()); + } + + Ok(SslContext { ctx: ctx }) + } + + /// A convenience wrapper around `try_new`. + pub fn new(method: SslMethod) -> SslContext { + match SslContext::try_new(method) { + Ok(ctx) => ctx, + Err(err) => fail!("Error creating SSL context: {}", err) + } + } + + /// Configures the certificate verification method for new connections. + pub fn set_verify(&mut self, mode: SslVerifyMode, + verify: Option<VerifyCallback>) { + unsafe { + ffi::SSL_CTX_set_ex_data(self.ctx, VERIFY_IDX, + mem::transmute(verify)); + ffi::SSL_CTX_set_verify(self.ctx, mode as c_int, Some(raw_verify)); + } + } + + #[allow(non_snake_case_functions)] + /// Specifies the file that contains trusted CA certificates. + pub fn set_CA_file(&mut self, file: &str) -> Option<SslError> { + let ret = file.with_c_str(|file| { + unsafe { + ffi::SSL_CTX_load_verify_locations(self.ctx, file, ptr::null()) + } + }); + + if ret == 0 { + Some(SslError::get()) + } else { + None + } + } +} + +pub struct X509StoreContext { + ctx: *mut ffi::X509_STORE_CTX +} + +impl X509StoreContext { + pub fn get_error(&self) -> Option<X509ValidationError> { + let err = unsafe { ffi::X509_STORE_CTX_get_error(self.ctx) }; + X509ValidationError::from_raw(err) + } + + pub fn get_current_cert<'a>(&'a self) -> Option<X509<'a>> { + let ptr = unsafe { ffi::X509_STORE_CTX_get_current_cert(self.ctx) }; + + if ptr.is_null() { + None + } else { + Some(X509 { ctx: self, x509: ptr }) + } + } +} + +#[allow(dead_code)] +/// A public key certificate +pub struct X509<'ctx> { + ctx: &'ctx X509StoreContext, + x509: *mut ffi::X509 +} + +impl<'ctx> X509<'ctx> { + pub fn subject_name<'a>(&'a self) -> X509Name<'a> { + let name = unsafe { ffi::X509_get_subject_name(self.x509) }; + X509Name { x509: self, name: name } + } +} + +#[allow(dead_code)] +pub struct X509Name<'x> { + x509: &'x X509<'x>, + name: *mut ffi::X509_NAME +} + +macro_rules! make_validation_error( + ($ok_val:ident, $($name:ident = $val:ident,)+) => ( + pub enum X509ValidationError { + $($name,)+ + X509UnknownError(c_int) + } + + impl X509ValidationError { + #[doc(hidden)] + pub fn from_raw(err: c_int) -> Option<X509ValidationError> { + match err { + self::ffi::$ok_val => None, + $(self::ffi::$val => Some($name),)+ + err => Some(X509UnknownError(err)) + } + } + } + ) +) + +make_validation_error!(X509_V_OK, + X509UnableToGetIssuerCert = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, + X509UnableToGetCrl = X509_V_ERR_UNABLE_TO_GET_CRL, + X509UnableToDecryptCertSignature = X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, + X509UnableToDecryptCrlSignature = X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, + X509UnableToDecodeIssuerPublicKey = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, + X509CertSignatureFailure = X509_V_ERR_CERT_SIGNATURE_FAILURE, + X509CrlSignatureFailure = X509_V_ERR_CRL_SIGNATURE_FAILURE, + X509CertNotYetValid = X509_V_ERR_CERT_NOT_YET_VALID, + X509CertHasExpired = X509_V_ERR_CERT_HAS_EXPIRED, + X509CrlNotYetValid = X509_V_ERR_CRL_NOT_YET_VALID, + X509CrlHasExpired = X509_V_ERR_CRL_HAS_EXPIRED, + X509ErrorInCertNotBeforeField = X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, + X509ErrorInCertNotAfterField = X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, + X509ErrorInCrlLastUpdateField = X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, + X509ErrorInCrlNextUpdateField = X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, + X509OutOfMem = X509_V_ERR_OUT_OF_MEM, + X509DepthZeroSelfSignedCert = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, + X509SelfSignedCertInChain = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, + X509UnableToGetIssuerCertLocally = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, + X509UnableToVerifyLeafSignature = X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, + X509CertChainTooLong = X509_V_ERR_CERT_CHAIN_TOO_LONG, + X509CertRevoked = X509_V_ERR_CERT_REVOKED, + X509InvalidCA = X509_V_ERR_INVALID_CA, + X509PathLengthExceeded = X509_V_ERR_PATH_LENGTH_EXCEEDED, + X509InvalidPurpose = X509_V_ERR_INVALID_PURPOSE, + X509CertUntrusted = X509_V_ERR_CERT_UNTRUSTED, + X509CertRejected = X509_V_ERR_CERT_REJECTED, + X509SubjectIssuerMismatch = X509_V_ERR_SUBJECT_ISSUER_MISMATCH, + X509AkidSkidMismatch = X509_V_ERR_AKID_SKID_MISMATCH, + X509AkidIssuerSerialMismatch = X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH, + X509KeyusageNoCertsign = X509_V_ERR_KEYUSAGE_NO_CERTSIGN, + X509UnableToGetCrlIssuer = X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, + X509UnhandledCriticalExtension = X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION, + X509KeyusageNoCrlSign = X509_V_ERR_KEYUSAGE_NO_CRL_SIGN, + X509UnhandledCriticalCrlExtension = X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION, + X509InvalidNonCA = X509_V_ERR_INVALID_NON_CA, + X509ProxyPathLengthExceeded = X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED, + X509KeyusageNoDigitalSignature = X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE, + X509ProxyCertificatesNotAllowed = X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED, + X509InvalidExtension = X509_V_ERR_INVALID_EXTENSION, + X509InavlidPolicyExtension = X509_V_ERR_INVALID_POLICY_EXTENSION, + X509NoExplicitPolicy = X509_V_ERR_NO_EXPLICIT_POLICY, + X509DifferentCrlScope = X509_V_ERR_DIFFERENT_CRL_SCOPE, + X509UnsupportedExtensionFeature = X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE, + X509UnnestedResource = X509_V_ERR_UNNESTED_RESOURCE, + X509PermittedVolation = X509_V_ERR_PERMITTED_VIOLATION, + X509ExcludedViolation = X509_V_ERR_EXCLUDED_VIOLATION, + X509SubtreeMinmax = X509_V_ERR_SUBTREE_MINMAX, + X509UnsupportedConstraintType = X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE, + X509UnsupportedConstraintSyntax = X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX, + X509UnsupportedNameSyntax = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX, + X509CrlPathValidationError= X509_V_ERR_CRL_PATH_VALIDATION_ERROR, + X509ApplicationVerification = X509_V_ERR_APPLICATION_VERIFICATION, +) + +struct Ssl { + ssl: *mut ffi::SSL +} + +impl Drop for Ssl { + fn drop(&mut self) { + unsafe { ffi::SSL_free(self.ssl) } + } +} + +impl Ssl { + fn try_new(ctx: &SslContext) -> Result<Ssl, SslError> { + let ssl = unsafe { ffi::SSL_new(ctx.ctx) }; + if ssl == ptr::mut_null() { + return Err(SslError::get()); + } + let ssl = Ssl { ssl: ssl }; + + let rbio = unsafe { ffi::BIO_new(ffi::BIO_s_mem()) }; + if rbio == ptr::mut_null() { + return Err(SslError::get()); + } + + let wbio = unsafe { ffi::BIO_new(ffi::BIO_s_mem()) }; + if wbio == ptr::mut_null() { + unsafe { ffi::BIO_free_all(rbio) } + return Err(SslError::get()); + } + + unsafe { ffi::SSL_set_bio(ssl.ssl, rbio, wbio) } + Ok(ssl) + } + + fn get_rbio<'a>(&'a self) -> MemBioRef<'a> { + unsafe { self.wrap_bio(ffi::SSL_get_rbio(self.ssl)) } + } + + fn get_wbio<'a>(&'a self) -> MemBioRef<'a> { + unsafe { self.wrap_bio(ffi::SSL_get_wbio(self.ssl)) } + } + + fn wrap_bio<'a>(&'a self, bio: *mut ffi::BIO) -> MemBioRef<'a> { + assert!(bio != ptr::mut_null()); + MemBioRef { + ssl: self, + bio: MemBio { + bio: bio, + owned: false + } + } + } + + fn connect(&self) -> c_int { + unsafe { ffi::SSL_connect(self.ssl) } + } + + fn read(&self, buf: &mut [u8]) -> c_int { + unsafe { ffi::SSL_read(self.ssl, buf.as_ptr() as *mut c_void, + buf.len() as c_int) } + } + + fn write(&self, buf: &[u8]) -> c_int { + unsafe { ffi::SSL_write(self.ssl, buf.as_ptr() as *const c_void, + buf.len() as c_int) } + } + + fn get_error(&self, ret: c_int) -> LibSslError { + let err = unsafe { ffi::SSL_get_error(self.ssl, ret) }; + match FromPrimitive::from_int(err as int) { + Some(err) => err, + None => unreachable!() + } + } +} + +#[deriving(FromPrimitive)] +#[repr(i32)] +enum LibSslError { + ErrorNone = ffi::SSL_ERROR_NONE, + ErrorSsl = ffi::SSL_ERROR_SSL, + ErrorWantRead = ffi::SSL_ERROR_WANT_READ, + ErrorWantWrite = ffi::SSL_ERROR_WANT_WRITE, + ErrorWantX509Lookup = ffi::SSL_ERROR_WANT_X509_LOOKUP, + ErrorSyscall = ffi::SSL_ERROR_SYSCALL, + ErrorZeroReturn = ffi::SSL_ERROR_ZERO_RETURN, + ErrorWantConnect = ffi::SSL_ERROR_WANT_CONNECT, + ErrorWantAccept = ffi::SSL_ERROR_WANT_ACCEPT, +} + +#[allow(dead_code)] +struct MemBioRef<'ssl> { + ssl: &'ssl Ssl, + bio: MemBio, +} + +impl<'ssl> MemBioRef<'ssl> { + fn read(&self, buf: &mut [u8]) -> Option<uint> { + self.bio.read(buf) + } + + fn write(&self, buf: &[u8]) { + self.bio.write(buf) + } +} + +struct MemBio { + bio: *mut ffi::BIO, + owned: bool +} + +impl Drop for MemBio { + fn drop(&mut self) { + if self.owned { + unsafe { + ffi::BIO_free_all(self.bio); + } + } + } +} + +impl MemBio { + fn read(&self, buf: &mut [u8]) -> Option<uint> { + let ret = unsafe { + ffi::BIO_read(self.bio, buf.as_ptr() as *mut c_void, + buf.len() as c_int) + }; + + if ret < 0 { + None + } else { + Some(ret as uint) + } + } + + fn write(&self, buf: &[u8]) { + let ret = unsafe { + ffi::BIO_write(self.bio, buf.as_ptr() as *const c_void, + buf.len() as c_int) + }; + assert_eq!(buf.len(), ret as uint); + } +} + +/// A stream wrapper which handles SSL encryption for an underlying stream. +pub struct SslStream<S> { + stream: S, + ssl: Ssl, + buf: Vec<u8> +} + +impl<S: Stream> SslStream<S> { + /// Attempts to create a new SSL stream + pub fn try_new(ctx: &SslContext, stream: S) -> Result<SslStream<S>, + SslError> { + let ssl = match Ssl::try_new(ctx) { + Ok(ssl) => ssl, + Err(err) => return Err(err) + }; + + let mut ssl = SslStream { + stream: stream, + ssl: ssl, + // Maximum TLS record size is 16k + buf: Vec::from_elem(16 * 1024, 0u8) + }; + + match ssl.in_retry_wrapper(|ssl| { ssl.connect() }) { + Ok(_) => Ok(ssl), + Err(err) => Err(err) + } + } + + /// A convenience wrapper around `try_new`. + pub fn new(ctx: &SslContext, stream: S) -> SslStream<S> { + match SslStream::try_new(ctx, stream) { + Ok(stream) => stream, + Err(err) => fail!("Error creating SSL stream: {}", err) + } + } + + fn in_retry_wrapper(&mut self, blk: |&Ssl| -> c_int) + -> Result<c_int, SslError> { + loop { + let ret = blk(&self.ssl); + if ret > 0 { + return Ok(ret); + } + + match self.ssl.get_error(ret) { + ErrorWantRead => { + try_ssl!(self.flush()); + let len = try_ssl!(self.stream.read(self.buf.as_mut_slice())); + self.ssl.get_rbio().write(self.buf.slice_to(len)); + } + ErrorWantWrite => { try_ssl!(self.flush()) } + ErrorZeroReturn => return Err(SslSessionClosed), + ErrorSsl => return Err(SslError::get()), + _ => unreachable!() + } + } + } + + fn write_through(&mut self) -> IoResult<()> { + loop { + match self.ssl.get_wbio().read(self.buf.as_mut_slice()) { + Some(len) => try!(self.stream.write(self.buf.slice_to(len))), + None => break + }; + } + Ok(()) + } +} + +impl<S: Stream> Reader for SslStream<S> { + fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { + match self.in_retry_wrapper(|ssl| { ssl.read(buf) }) { + Ok(len) => Ok(len as uint), + Err(SslSessionClosed) => + Err(IoError { + kind: EndOfFile, + desc: "SSL session closed", + detail: None + }), + Err(StreamError(e)) => Err(e), + _ => unreachable!() + } + } +} + +impl<S: Stream> Writer for SslStream<S> { + fn write(&mut self, buf: &[u8]) -> IoResult<()> { + let mut start = 0; + while start < buf.len() { + let ret = self.in_retry_wrapper(|ssl| { + ssl.write(buf.slice_from(start)) + }); + match ret { + Ok(len) => start += len as uint, + _ => unreachable!() + } + try!(self.write_through()); + } + Ok(()) + } + + fn flush(&mut self) -> IoResult<()> { + try!(self.write_through()); + self.stream.flush() + } +} diff --git a/src/ssl/tests.rs b/src/ssl/tests.rs new file mode 100644 index 00000000..3b10e878 --- /dev/null +++ b/src/ssl/tests.rs @@ -0,0 +1,160 @@ +use std::io::Writer; +use std::io::net::tcp::TcpStream; +use std::str; + +use ssl::{Sslv23, SslContext, SslStream, SslVerifyPeer, X509StoreContext}; + +#[test] +fn test_new_ctx() { + SslContext::new(Sslv23); +} + +#[test] +fn test_new_sslstream() { + let stream = TcpStream::connect("127.0.0.1", 15418).unwrap(); + SslStream::new(&SslContext::new(Sslv23), stream); +} + +#[test] +fn test_verify_untrusted() { + let stream = TcpStream::connect("127.0.0.1", 15418).unwrap(); + let mut ctx = SslContext::new(Sslv23); + ctx.set_verify(SslVerifyPeer, None); + match SslStream::try_new(&ctx, stream) { + Ok(_) => fail!("expected failure"), + Err(err) => println!("error {}", err) + } +} + +#[test] +fn test_verify_trusted() { + let stream = TcpStream::connect("127.0.0.1", 15418).unwrap(); + let mut ctx = SslContext::new(Sslv23); + ctx.set_verify(SslVerifyPeer, None); + match ctx.set_CA_file("test/cert.pem") { + None => {} + Some(err) => fail!("Unexpected error {}", err) + } + match SslStream::try_new(&ctx, stream) { + Ok(_) => (), + Err(err) => fail!("Expected success, got {}", err) + } +} + +#[test] +fn test_verify_untrusted_callback_override_ok() { + fn callback(_preverify_ok: bool, _x509_ctx: &X509StoreContext) -> bool { + true + } + let stream = TcpStream::connect("127.0.0.1", 15418).unwrap(); + let mut ctx = SslContext::new(Sslv23); + ctx.set_verify(SslVerifyPeer, Some(callback)); + match SslStream::try_new(&ctx, stream) { + Ok(_) => (), + Err(err) => fail!("Expected success, got {}", err) + } +} + +#[test] +fn test_verify_untrusted_callback_override_bad() { + fn callback(_preverify_ok: bool, _x509_ctx: &X509StoreContext) -> bool { + false + } + let stream = TcpStream::connect("127.0.0.1", 15418).unwrap(); + let mut ctx = SslContext::new(Sslv23); + ctx.set_verify(SslVerifyPeer, Some(callback)); + assert!(SslStream::try_new(&ctx, stream).is_err()); +} + +#[test] +fn test_verify_trusted_callback_override_ok() { + fn callback(_preverify_ok: bool, _x509_ctx: &X509StoreContext) -> bool { + true + } + let stream = TcpStream::connect("127.0.0.1", 15418).unwrap(); + let mut ctx = SslContext::new(Sslv23); + ctx.set_verify(SslVerifyPeer, Some(callback)); + match ctx.set_CA_file("test/cert.pem") { + None => {} + Some(err) => fail!("Unexpected error {}", err) + } + match SslStream::try_new(&ctx, stream) { + Ok(_) => (), + Err(err) => fail!("Expected success, got {}", err) + } +} + +#[test] +fn test_verify_trusted_callback_override_bad() { + fn callback(_preverify_ok: bool, _x509_ctx: &X509StoreContext) -> bool { + false + } + let stream = TcpStream::connect("127.0.0.1", 15418).unwrap(); + let mut ctx = SslContext::new(Sslv23); + ctx.set_verify(SslVerifyPeer, Some(callback)); + match ctx.set_CA_file("test/cert.pem") { + None => {} + Some(err) => fail!("Unexpected error {}", err) + } + assert!(SslStream::try_new(&ctx, stream).is_err()); +} + +#[test] +fn test_verify_callback_load_certs() { + fn callback(_preverify_ok: bool, x509_ctx: &X509StoreContext) -> bool { + assert!(x509_ctx.get_current_cert().is_some()); + true + } + let stream = TcpStream::connect("127.0.0.1", 15418).unwrap(); + let mut ctx = SslContext::new(Sslv23); + ctx.set_verify(SslVerifyPeer, Some(callback)); + assert!(SslStream::try_new(&ctx, stream).is_ok()); +} + +#[test] +fn test_verify_trusted_get_error_ok() { + fn callback(_preverify_ok: bool, x509_ctx: &X509StoreContext) -> bool { + assert!(x509_ctx.get_error().is_none()); + true + } + let stream = TcpStream::connect("127.0.0.1", 15418).unwrap(); + let mut ctx = SslContext::new(Sslv23); + ctx.set_verify(SslVerifyPeer, Some(callback)); + match ctx.set_CA_file("test/cert.pem") { + None => {} + Some(err) => fail!("Unexpected error {}", err) + } + assert!(SslStream::try_new(&ctx, stream).is_ok()); +} + +#[test] +fn test_verify_trusted_get_error_err() { + fn callback(_preverify_ok: bool, x509_ctx: &X509StoreContext) -> bool { + assert!(x509_ctx.get_error().is_some()); + false + } + let stream = TcpStream::connect("127.0.0.1", 15418).unwrap(); + let mut ctx = SslContext::new(Sslv23); + ctx.set_verify(SslVerifyPeer, Some(callback)); + assert!(SslStream::try_new(&ctx, stream).is_err()); +} + +#[test] +fn test_write() { + let stream = TcpStream::connect("127.0.0.1", 15418).unwrap(); + let mut stream = SslStream::new(&SslContext::new(Sslv23), stream); + stream.write("hello".as_bytes()).unwrap(); + stream.flush().unwrap(); + stream.write(" there".as_bytes()).unwrap(); + stream.flush().unwrap(); +} + +#[test] +fn test_read() { + let stream = TcpStream::connect("127.0.0.1", 15418).unwrap(); + let mut stream = SslStream::new(&SslContext::new(Sslv23), stream); + stream.write("GET /\r\n\r\n".as_bytes()).unwrap(); + stream.flush().unwrap(); + let buf = stream.read_to_end().ok().expect("read error"); + print!("{}", str::from_utf8(buf.as_slice())); +} |