diff --git a/.travis.yml b/.travis.yml index e73df5f0..91c6ad62 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,7 +18,7 @@ matrix: # include: # - os: linux # env: TARGET=arm-unknown-linux-gnueabihf TEST_FEATURES=true - # rust: 1.8.0 + # rust: 1.7.0 exclude: - os: osx env: TEST_FEATURES=true diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 00000000..3e02eded --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,2 @@ +[workspace] +members = ["openssl", "openssl-sys", "openssl-sys-extras"] diff --git a/README.md b/README.md index 2fe4ae6f..b3ce0bc0 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![Build Status](https://travis-ci.org/sfackler/rust-openssl.svg?branch=master)](https://travis-ci.org/sfackler/rust-openssl) -[Documentation](https://sfackler.github.io/rust-openssl/doc/v0.7.10/openssl). +[Documentation](https://sfackler.github.io/rust-openssl/doc/v0.7.14/openssl). ## Building @@ -44,10 +44,30 @@ export OPENSSL_LIB_DIR=`brew --prefix openssl`/lib On Windows, consider building with [mingw-w64](http://mingw-w64.org/). Build script will try to find mingw in `PATH` environment variable to provide Cargo with location where openssl libs from mingw-w64 package may be found. -If you followed guide [Building on Windows](https://github.com/rust-lang/rust#building-on-windows) -from rust repo, then you should have [MSYS2](http://msys2.github.io/) with -`mingw-w64-openssl` installed as part of `mingw-w64-x86_64-toolchain` -(or `mingw-w64-i686-toolchain`) package. + +mingw-w64 can be easily installed by using [MSYS2](http://msys2.github.io/). Install MSYS2 according to the instructions, and then, from an MSYS2 Shell, install mingw-w64: + +32-bit: +```bash +pacman -S mingw-w64-i686-gcc +``` + +64-bit +```bash +pacman -S mingw-w64-x86_64-gcc +``` + +and then install the mingw-w64 toolchain. + +32-bit: +```bash +pacman -S mingw-w64-i686-toolchain +``` + +64-bit: +```bash +pacman -S mingw-w64-x86_64-toolchain +``` Alternatively, install OpenSSL from [here][1]. Cargo will not be able to find OpenSSL if it's installed to the default location. You can either copy the `include/openssl` diff --git a/appveyor.yml b/appveyor.yml index 5b98e736..f835d9f6 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -9,7 +9,7 @@ environment: # BITS: 64 install: - ps: Start-FileDownload "http://slproweb.com/download/Win${env:BITS}OpenSSL-1_0_2h.exe" - - Win%BITS%OpenSSL-1_0_2g.exe /SILENT /VERYSILENT /SP- /DIR="C:\OpenSSL" + - Win%BITS%OpenSSL-1_0_2h.exe /SILENT /VERYSILENT /SP- /DIR="C:\OpenSSL" - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-1.8.0-${env:TARGET}.exe" - rust-1.8.0-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin diff --git a/openssl-sys-extras/Cargo.toml b/openssl-sys-extras/Cargo.toml index c655f6fe..903305d7 100644 --- a/openssl-sys-extras/Cargo.toml +++ b/openssl-sys-extras/Cargo.toml @@ -1,11 +1,11 @@ [package] name = "openssl-sys-extras" -version = "0.7.10" +version = "0.7.14" authors = ["Steven Fackler "] license = "MIT" description = "Extra FFI bindings to OpenSSL that require a C shim" repository = "https://github.com/sfackler/rust-openssl" -documentation = "https://sfackler.github.io/rust-openssl/doc/v0.7.10/openssl_sys_extras" +documentation = "https://sfackler.github.io/rust-openssl/doc/v0.7.14/openssl_sys_extras" build = "build.rs" [features] @@ -13,7 +13,7 @@ ecdh_auto = [] [dependencies] libc = "0.2" -openssl-sys = { version = "0.7.10", path = "../openssl-sys" } +openssl-sys = { version = "0.7.14", path = "../openssl-sys" } [build-dependencies] gcc = "0.3" diff --git a/openssl-sys-extras/src/lib.rs b/openssl-sys-extras/src/lib.rs index 97dc0c2b..8e7542fc 100644 --- a/openssl-sys-extras/src/lib.rs +++ b/openssl-sys-extras/src/lib.rs @@ -1,5 +1,5 @@ #![allow(non_upper_case_globals, non_snake_case)] -#![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.14")] extern crate openssl_sys; extern crate libc; @@ -60,6 +60,8 @@ extern { pub fn SSL_CTX_set_options_shim(ctx: *mut SSL_CTX, options: c_long) -> c_long; pub fn SSL_CTX_get_options_shim(ctx: *mut SSL_CTX) -> c_long; pub fn SSL_CTX_clear_options_shim(ctx: *mut SSL_CTX, options: c_long) -> c_long; + #[link_name = "SSL_CTX_set_mode_shim"] + pub fn SSL_CTX_set_mode(ctx: *mut SSL_CTX, options: c_long) -> c_long; #[link_name = "SSL_CTX_add_extra_chain_cert_shim"] pub fn SSL_CTX_add_extra_chain_cert(ctx: *mut SSL_CTX, x509: *mut X509) -> c_long; #[link_name = "SSL_CTX_set_read_ahead_shim"] diff --git a/openssl-sys-extras/src/openssl_shim.c b/openssl-sys-extras/src/openssl_shim.c index 11df1ca6..db2a8786 100644 --- a/openssl-sys-extras/src/openssl_shim.c +++ b/openssl-sys-extras/src/openssl_shim.c @@ -93,6 +93,10 @@ long SSL_CTX_clear_options_shim(SSL_CTX *ctx, long options) { return SSL_CTX_clear_options(ctx, options); } +long SSL_CTX_set_mode_shim(SSL_CTX *ctx, long options) { + return SSL_CTX_set_mode(ctx, options); +} + long SSL_CTX_add_extra_chain_cert_shim(SSL_CTX *ctx, X509 *x509) { return SSL_CTX_add_extra_chain_cert(ctx, x509); } diff --git a/openssl-sys/Cargo.toml b/openssl-sys/Cargo.toml index 0c166a53..c203b6d6 100644 --- a/openssl-sys/Cargo.toml +++ b/openssl-sys/Cargo.toml @@ -1,12 +1,12 @@ [package] name = "openssl-sys" -version = "0.7.10" +version = "0.7.14" authors = ["Alex Crichton ", "Steven Fackler "] license = "MIT" description = "FFI bindings to OpenSSL" repository = "https://github.com/sfackler/rust-openssl" -documentation = "https://sfackler.github.io/rust-openssl/doc/v0.7.10/openssl_sys" +documentation = "https://sfackler.github.io/rust-openssl/doc/v0.7.14/openssl_sys" links = "openssl" build = "build.rs" @@ -41,14 +41,14 @@ libressl-pnacl-sys = "2.1.0" # Only here to make sure we link to these in a static build on Windows [target.i686-pc-windows-gnu.dependencies] -user32-sys = "0.1" -gdi32-sys = "0.1" +user32-sys = "0.2" +gdi32-sys = "0.2" [target.x86_64-pc-windows-gnu.dependencies] -user32-sys = "0.1" -gdi32-sys = "0.1" +user32-sys = "0.2" +gdi32-sys = "0.2" [target.i686-pc-windows-msvc.dependencies] -user32-sys = "0.1" -gdi32-sys = "0.1" +user32-sys = "0.2" +gdi32-sys = "0.2" [target.x86_64-pc-windows-msvc.dependencies] -user32-sys = "0.1" -gdi32-sys = "0.1" +user32-sys = "0.2" +gdi32-sys = "0.2" diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 3d7c59c3..1a15fecb 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1,6 +1,6 @@ #![allow(non_camel_case_types, non_upper_case_globals, non_snake_case)] #![allow(dead_code)] -#![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.14")] extern crate libc; @@ -114,6 +114,28 @@ pub struct RSA { pub mt_blinding: *mut c_void, } +#[repr(C)] +pub struct DSA { + pub pad: c_int, + pub version: c_long, + pub write_params: c_int, + + pub p: *mut BIGNUM, + pub q: *mut BIGNUM, + pub g: *mut BIGNUM, + pub pub_key: *mut BIGNUM, + pub priv_key: *mut BIGNUM, + pub kinv: *mut BIGNUM, + pub r: *mut BIGNUM, + + pub flags: c_int, + pub _method_mont_p: *mut c_void, + pub references: c_int, + pub ex_data: *mut c_void, + pub meth: *const c_void, + pub engine: *const c_void, +} + #[repr(C)] pub struct EVP_PKEY { pub type_: c_int, @@ -270,8 +292,11 @@ pub const SSL_CTRL_SET_TLSEXT_SERVERNAME_CB: c_int = 53; pub const SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG: c_int = 54; pub const SSL_CTRL_SET_TLSEXT_HOSTNAME: c_int = 55; pub const SSL_CTRL_EXTRA_CHAIN_CERT: c_int = 14; - pub const SSL_CTRL_SET_READ_AHEAD: c_int = 41; + +pub const SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER: c_long = 2; +pub const SSL_MODE_AUTO_RETRY: c_long = 4; + pub const SSL_ERROR_NONE: c_int = 0; pub const SSL_ERROR_SSL: c_int = 1; pub const SSL_ERROR_SYSCALL: c_int = 5; @@ -623,10 +648,28 @@ extern "C" { pub fn PEM_read_bio_RSA_PUBKEY(bio: *mut BIO, rsa: *mut *mut RSA, callback: Option, user_data: *mut c_void) -> *mut RSA; pub fn PEM_write_bio_PrivateKey(bio: *mut BIO, pkey: *mut EVP_PKEY, cipher: *const EVP_CIPHER, - kstr: *mut c_char, klen: c_int, + kstr: *mut c_uchar, klen: c_int, callback: Option, user_data: *mut c_void) -> c_int; pub fn PEM_write_bio_PUBKEY(bp: *mut BIO, x: *mut EVP_PKEY) -> c_int; + pub fn PEM_write_bio_RSAPrivateKey(bp: *mut BIO, rsa: *mut RSA, cipher: *const EVP_CIPHER, + kstr: *mut c_uchar, klen: c_int, + callback: Option, + user_data: *mut c_void) -> c_int; + pub fn PEM_write_bio_RSAPublicKey(bp: *mut BIO, rsa: *mut RSA) -> c_int; + pub fn PEM_write_bio_RSA_PUBKEY(bp: *mut BIO, rsa: *mut RSA) -> c_int; + + pub fn PEM_read_bio_DSAPrivateKey(bp: *mut BIO, dsa: *mut *mut DSA, callback: Option, + user_data: *mut c_void) -> *mut DSA; + pub fn PEM_read_bio_DSA_PUBKEY(bp: *mut BIO, dsa: *mut *mut DSA, callback: Option, + user_data: *mut c_void) -> *mut DSA; + pub fn PEM_write_bio_DSAPrivateKey(bp: *mut BIO, dsa: *mut DSA, cipher: *const EVP_CIPHER, + kstr: *mut c_uchar, klen: c_int, callback: Option, + user_data: *mut c_void) -> c_int; + pub fn PEM_write_bio_DSA_PUBKEY(bp: *mut BIO, dsa: *mut DSA) -> c_int; + + + pub fn PEM_write_bio_X509(bio: *mut BIO, x509: *mut X509) -> c_int; pub fn PEM_write_bio_X509_REQ(bio: *mut BIO, x509: *mut X509_REQ) -> c_int; @@ -660,6 +703,18 @@ extern "C" { pub fn RSA_verify(t: c_int, m: *const u8, mlen: c_uint, sig: *const u8, siglen: c_uint, k: *mut RSA) -> c_int; + pub fn DSA_new() -> *mut DSA; + pub fn DSA_free(dsa: *mut DSA); + pub fn DSA_size(dsa: *const DSA) -> c_int; + pub fn DSA_generate_parameters_ex(dsa: *mut DSA, bits: c_int, seed: *const c_uchar, seed_len: c_int, + counter_ref: *mut c_int, h_ret: *mut c_ulong, + cb: *const c_void) -> c_int; + pub fn DSA_generate_key(dsa: *mut DSA) -> c_int; + pub fn DSA_sign(dummy: c_int, dgst: *const c_uchar, len: c_int, sigret: *mut c_uchar, + siglen: *mut c_uint, dsa: *mut DSA) -> c_int; + pub fn DSA_verify(dummy: c_int, dgst: *const c_uchar, len: c_int, sigbuf: *const c_uchar, + siglen: c_int, dsa: *mut DSA) -> c_int; + pub fn SSL_library_init() -> c_int; pub fn SSL_load_error_strings(); @@ -832,6 +887,9 @@ extern "C" { pub fn X509_REQ_add_extensions(req: *mut X509_REQ, exts: *mut stack_st_X509_EXTENSION) -> c_int; pub fn X509_REQ_sign(x: *mut X509_REQ, pkey: *mut EVP_PKEY, md: *const EVP_MD) -> c_int; + pub fn i2d_X509_bio(b: *mut BIO, x: *mut X509) -> c_int; + pub fn i2d_X509_REQ_bio(b: *mut BIO, x: *mut X509_REQ) -> c_int; + pub fn i2d_RSA_PUBKEY(k: *mut RSA, buf: *const *mut u8) -> c_int; pub fn d2i_RSA_PUBKEY(k: *const *mut RSA, buf: *const *const u8, len: c_uint) -> *mut RSA; pub fn i2d_RSAPrivateKey(k: *mut RSA, buf: *const *mut u8) -> c_int; diff --git a/openssl/Cargo.toml b/openssl/Cargo.toml index c9eba838..218969eb 100644 --- a/openssl/Cargo.toml +++ b/openssl/Cargo.toml @@ -1,11 +1,11 @@ [package] name = "openssl" -version = "0.7.10" +version = "0.7.14" authors = ["Steven Fackler "] license = "Apache-2.0" description = "OpenSSL bindings" repository = "https://github.com/sfackler/rust-openssl" -documentation = "https://sfackler.github.io/rust-openssl/doc/v0.7.10/openssl" +documentation = "https://sfackler.github.io/rust-openssl/doc/v0.7.14/openssl" readme = "../README.md" keywords = ["crypto", "tls", "ssl", "dtls"] build = "build.rs" @@ -27,13 +27,14 @@ ecdh_auto = ["openssl-sys-extras/ecdh_auto"] pkcs5_pbkdf2_hmac = ["openssl-sys/pkcs5_pbkdf2_hmac"] nightly = [] +catch_unwind = [] [dependencies] -bitflags = ">= 0.5.0, < 0.7.0" +bitflags = ">= 0.5.0, < 0.8.0" lazy_static = "0.2" libc = "0.2" -openssl-sys = { version = "0.7.10", path = "../openssl-sys" } -openssl-sys-extras = { version = "0.7.10", path = "../openssl-sys-extras" } +openssl-sys = { version = "0.7.14", path = "../openssl-sys" } +openssl-sys-extras = { version = "0.7.14", path = "../openssl-sys-extras" } [build-dependencies] gcc = "0.3" diff --git a/openssl/src/bn/mod.rs b/openssl/src/bn/mod.rs index eb697248..f937089d 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 error::ErrorStack; +/// 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<(), ErrorStack> { 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<(), ErrorStack> { 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<(), ErrorStack> { 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<(), ErrorStack> { 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; diff --git a/openssl/src/crypto/dsa.rs b/openssl/src/crypto/dsa.rs new file mode 100644 index 00000000..36806a48 --- /dev/null +++ b/openssl/src/crypto/dsa.rs @@ -0,0 +1,351 @@ +use ffi; +use std::fmt; +use error::ErrorStack; +use std::ptr; +use std::io::{self, Read, Write}; +use libc::{c_uint, c_int}; + +use bn::BigNum; +use bio::MemBio; +use crypto::hash; +use crypto::HashTypeInternals; + +#[cfg(feature = "catch_unwind")] +use libc::{c_char, c_void}; +#[cfg(feature = "catch_unwind")] +use crypto::util::{CallbackState, invoke_passwd_cb}; + +/// Builder for upfront DSA parameter generateration +pub struct DSAParams(*mut ffi::DSA); + +impl DSAParams { + pub fn with_size(size: usize) -> Result { + 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) -> io::Result + where R: Read + { + let mut mem_bio = try!(MemBio::new()); + try!(io::copy(reader, &mut mem_bio)); + + unsafe { + let dsa = try_ssl_null!(ffi::PEM_read_bio_DSAPrivateKey(mem_bio.get_handle(), + ptr::null_mut(), + None, + ptr::null_mut())); + let dsa = DSA(dsa); + assert!(dsa.has_private_key()); + Ok(dsa) + } + } + + /// Read a private key from PEM supplying a password callback to be invoked if the private key + /// is encrypted. + /// + /// The callback will be passed the password buffer and should return the number of characters + /// placed into the buffer. + /// + /// Requires the `catch_unwind` feature. + #[cfg(feature = "catch_unwind")] + pub fn private_key_from_pem_cb(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) -> io::Result<()> + where W: Write + { + assert!(self.has_private_key()); + let mut mem_bio = try!(MemBio::new()); + + unsafe { + try_ssl!(ffi::PEM_write_bio_DSAPrivateKey(mem_bio.get_handle(), self.0, + ptr::null(), ptr::null_mut(), 0, + None, ptr::null_mut())) + }; + + + try!(io::copy(&mut mem_bio, writer)); + Ok(()) + } + + /// Reads an DSA public key from PEM formatted data. + pub fn public_key_from_pem(reader: &mut R) -> io::Result + where R: Read + { + let mut mem_bio = try!(MemBio::new()); + try!(io::copy(reader, &mut mem_bio)); + + unsafe { + let dsa = try_ssl_null!(ffi::PEM_read_bio_DSA_PUBKEY(mem_bio.get_handle(), + ptr::null_mut(), + None, + ptr::null_mut())); + Ok(DSA(dsa)) + } + } + + /// Writes an DSA public key as PEM formatted data + pub fn public_key_to_pem(&self, writer: &mut W) -> io::Result<()> + where W: Write + { + let mut mem_bio = try!(MemBio::new()); + + unsafe { try_ssl!(ffi::PEM_write_bio_DSA_PUBKEY(mem_bio.get_handle(), self.0)) }; + + try!(io::copy(&mut mem_bio, writer)); + Ok(()) + } + + pub fn size(&self) -> Option { + if self.has_q() { + unsafe { Some(ffi::DSA_size(self.0) as u32) } + } else { + None + } + } + + pub fn sign(&self, hash: hash::Type, message: &[u8]) -> Result, ErrorStack> { + let k_len = self.size().expect("DSA missing a q") as c_uint; + let mut sig = vec![0; k_len as usize]; + let mut sig_len = k_len; + assert!(self.has_private_key()); + + unsafe { + try_ssl!(ffi::DSA_sign(hash.as_nid() as c_int, + message.as_ptr(), + message.len() as c_int, + sig.as_mut_ptr(), + &mut sig_len, + self.0)); + sig.set_len(sig_len as usize); + sig.shrink_to_fit(); + Ok(sig) + } + } + + pub fn verify(&self, hash: hash::Type, message: &[u8], sig: &[u8]) -> Result { + unsafe { + let result = ffi::DSA_verify(hash.as_nid() as c_int, + message.as_ptr(), + message.len() as c_int, + sig.as_ptr(), + sig.len() as c_int, + self.0); + + try_ssl_if!(result == -1); + Ok(result == 1) + } + } + + pub fn as_ptr(&self) -> *mut ffi::DSA { + self.0 + } + + // 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/hash.rs b/openssl/src/crypto/hash.rs index 78465851..69d3a350 100644 --- a/openssl/src/crypto/hash.rs +++ b/openssl/src/crypto/hash.rs @@ -2,9 +2,11 @@ use libc::c_uint; use std::iter::repeat; use std::io::prelude::*; use std::io; - use ffi; +use crypto::HashTypeInternals; +use nid::Nid; + /// Message digest (hash) type. #[derive(Copy, Clone)] pub enum Type { @@ -17,19 +19,32 @@ pub enum Type { RIPEMD160, } +impl HashTypeInternals for Type { + fn as_nid(&self) -> Nid { + match *self { + Type::MD5 => Nid::MD5, + Type::SHA1 => Nid::SHA1, + Type::SHA224 => Nid::SHA224, + Type::SHA256 => Nid::SHA256, + Type::SHA384 => Nid::SHA384, + Type::SHA512 => Nid::SHA512, + Type::RIPEMD160 => Nid::RIPEMD160, + } + } +} + impl Type { /// Returns the length of the message digest. #[inline] pub fn md_len(&self) -> usize { - use self::Type::*; match *self { - MD5 => 16, - SHA1 => 20, - SHA224 => 28, - SHA256 => 32, - SHA384 => 48, - SHA512 => 64, - RIPEMD160 => 20, + Type::MD5 => 16, + Type::SHA1 => 20, + Type::SHA224 => 28, + Type::SHA256 => 32, + Type::SHA384 => 48, + Type::SHA512 => 64, + Type::RIPEMD160 => 20, } } @@ -37,15 +52,14 @@ impl Type { #[inline] pub fn evp_md(&self) -> *const ffi::EVP_MD { unsafe { - use self::Type::*; match *self { - MD5 => ffi::EVP_md5(), - SHA1 => ffi::EVP_sha1(), - SHA224 => ffi::EVP_sha224(), - SHA256 => ffi::EVP_sha256(), - SHA384 => ffi::EVP_sha384(), - SHA512 => ffi::EVP_sha512(), - RIPEMD160 => ffi::EVP_ripemd160(), + Type::MD5 => ffi::EVP_md5(), + Type::SHA1 => ffi::EVP_sha1(), + Type::SHA224 => ffi::EVP_sha224(), + Type::SHA256 => ffi::EVP_sha256(), + Type::SHA384 => ffi::EVP_sha384(), + Type::SHA512 => ffi::EVP_sha512(), + Type::RIPEMD160 => ffi::EVP_ripemd160(), } } } diff --git a/openssl/src/crypto/hmac.rs b/openssl/src/crypto/hmac.rs index 866087b0..143c7b75 100644 --- a/openssl/src/crypto/hmac.rs +++ b/openssl/src/crypto/hmac.rs @@ -387,8 +387,7 @@ mod tests { let tests: [(Vec, 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/mod.rs b/openssl/src/crypto/mod.rs index bb77453f..6a34bd59 100644 --- a/openssl/src/crypto/mod.rs +++ b/openssl/src/crypto/mod.rs @@ -14,6 +14,8 @@ // limitations under the License. // +use nid::Nid; + pub mod hash; pub mod hmac; pub mod pkcs5; @@ -22,5 +24,12 @@ pub mod rand; pub mod symm; pub mod memcmp; pub mod rsa; +pub mod dsa; +#[cfg(feature = "catch_unwind")] +mod util; mod symm_internal; + +trait HashTypeInternals { + fn as_nid(&self) -> Nid; +} diff --git a/openssl/src/crypto/pkey.rs b/openssl/src/crypto/pkey.rs index 1020a82e..0231cc95 100644 --- a/openssl/src/crypto/pkey.rs +++ b/openssl/src/crypto/pkey.rs @@ -5,12 +5,19 @@ use std::iter::repeat; use std::mem; use std::ptr; use bio::MemBio; + +use crypto::HashTypeInternals; use crypto::hash; use crypto::hash::Type as HashType; use ffi; use crypto::rsa::RSA; use error::ErrorStack; +#[cfg(feature = "catch_unwind")] +use libc::{c_void, c_char}; +#[cfg(feature = "catch_unwind")] +use crypto::util::{CallbackState, invoke_passwd_cb}; + #[derive(Copy, Clone)] pub enum Parts { Neither, @@ -41,18 +48,6 @@ fn openssl_padding_code(padding: EncryptionPadding) -> c_int { } } -fn openssl_hash_nid(hash: HashType) -> c_int { - match hash { - HashType::MD5 => 4, // NID_md5, - HashType::SHA1 => 64, // NID_sha1 - HashType::SHA224 => 675, // NID_sha224 - HashType::SHA256 => 672, // NID_sha256 - HashType::SHA384 => 673, // NID_sha384 - HashType::SHA512 => 674, // NID_sha512 - HashType::RIPEMD160 => 117, // NID_ripemd160 - } -} - pub struct PKey { evp: *mut ffi::EVP_PKEY, parts: Parts, @@ -104,6 +99,35 @@ impl PKey { } } + /// Read a private key from PEM, supplying a password callback to be invoked if the private key + /// is encrypted. + /// + /// The callback will be passed the password buffer and should return the number of characters + /// placed into the buffer. + /// + /// Requires the `catch_unwind` feature. + #[cfg(feature = "catch_unwind")] + pub fn private_key_from_pem_cb(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 evp = try_ssl_null!(ffi::PEM_read_bio_PrivateKey(mem_bio.get_handle(), + ptr::null_mut(), + Some(invoke_passwd_cb::), + &mut cb as *mut _ as *mut c_void)); + + Ok(PKey { + evp: evp as *mut ffi::EVP_PKEY, + parts: Parts::Both, + }) + } + } + /// Reads public key from PEM, takes ownership of handle pub fn public_key_from_pem(reader: &mut R) -> io::Result where R: Read @@ -125,7 +149,7 @@ impl PKey { /// Reads an RSA private key from PEM, takes ownership of handle pub fn private_rsa_key_from_pem(reader: &mut R) -> io::Result - where R: Read + where R: Read { let rsa = try!(RSA::private_key_from_pem(reader)); unsafe { @@ -143,7 +167,7 @@ impl PKey { /// Reads an RSA public key from PEM, takes ownership of handle pub fn public_rsa_key_from_pem(reader: &mut R) -> io::Result - where R: Read + where R: Read { let rsa = try!(RSA::public_key_from_pem(reader)); unsafe { @@ -561,7 +585,7 @@ impl PKey { let mut r = repeat(0u8).take(len as usize + 1).collect::>(); let mut len = 0; - let rv = ffi::RSA_sign(openssl_hash_nid(hash), + let rv = ffi::RSA_sign(hash.as_nid() as c_int, s.as_ptr(), s.len() as c_uint, r.as_mut_ptr(), @@ -584,7 +608,7 @@ impl PKey { panic!("Could not get RSA key for verification"); } - let rv = ffi::RSA_verify(openssl_hash_nid(hash), + let rv = ffi::RSA_verify(hash.as_nid() as c_int, h.as_ptr(), h.len() as c_uint, s.as_ptr(), @@ -615,16 +639,15 @@ impl Drop for PKey { impl Clone for PKey { fn clone(&self) -> Self { let mut pkey = PKey::from_handle(unsafe { ffi::EVP_PKEY_new() }, self.parts); - // copy by encoding to DER and back + // copy by encoding to DER and back match self.parts { Parts::Public => { pkey.load_pub(&self.save_pub()[..]); - }, + } Parts::Both => { pkey.load_priv(&self.save_priv()[..]); - }, - Parts::Neither => { - }, + } + Parts::Neither => {} } pkey } @@ -699,8 +722,8 @@ mod tests { fn test_private_rsa_key_from_pem() { let key_path = Path::new("test/key.pem"); let mut file = File::open(&key_path) - .ok() - .expect("Failed to open `test/key.pem`"); + .ok() + .expect("Failed to open `test/key.pem`"); super::PKey::private_rsa_key_from_pem(&mut file).unwrap(); } @@ -709,8 +732,8 @@ mod tests { fn test_public_rsa_key_from_pem() { let key_path = Path::new("test/key.pem.pub"); let mut file = File::open(&key_path) - .ok() - .expect("Failed to open `test/key.pem.pub`"); + .ok() + .expect("Failed to open `test/key.pem.pub`"); super::PKey::public_rsa_key_from_pem(&mut file).unwrap(); } diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs index 11970933..b403eab5 100644 --- a/openssl/src/crypto/rsa.rs +++ b/openssl/src/crypto/rsa.rs @@ -1,11 +1,19 @@ use ffi; use std::fmt; use std::ptr; -use std::io::{self, Read}; +use std::io::{self, Read, Write}; +use libc::c_int; use bn::BigNum; use bio::MemBio; use error::ErrorStack; +use crypto::HashTypeInternals; +use crypto::hash; + +#[cfg(feature = "catch_unwind")] +use libc::{c_void, c_char}; +#[cfg(feature = "catch_unwind")] +use crypto::util::{CallbackState, invoke_passwd_cb}; pub struct RSA(*mut ffi::RSA); @@ -29,6 +37,29 @@ impl RSA { } } + pub fn from_private_components(n: BigNum, + e: BigNum, + d: BigNum, + p: BigNum, + q: BigNum, + dp: BigNum, + dq: BigNum, + qi: BigNum) + -> Result { + unsafe { + let rsa = try_ssl_null!(ffi::RSA_new()); + (*rsa).n = n.into_raw(); + (*rsa).e = e.into_raw(); + (*rsa).d = d.into_raw(); + (*rsa).p = p.into_raw(); + (*rsa).q = q.into_raw(); + (*rsa).dmp1 = dp.into_raw(); + (*rsa).dmq1 = dq.into_raw(); + (*rsa).iqmp = qi.into_raw(); + Ok(RSA(rsa)) + } + } + /// the caller should assert that the rsa pointer is valid. pub unsafe fn from_raw(rsa: *mut ffi::RSA) -> RSA { RSA(rsa) @@ -36,7 +67,7 @@ impl RSA { /// Reads an RSA private key from PEM formatted data. pub fn private_key_from_pem(reader: &mut R) -> io::Result - where R: Read + where R: Read { let mut mem_bio = try!(MemBio::new()); try!(io::copy(reader, &mut mem_bio)); @@ -50,9 +81,51 @@ impl RSA { } } + /// Reads an RSA private key from PEM formatted data and supplies a password callback. + /// + /// Requires the `catch_unwind` feature. + #[cfg(feature = "catch_unwind")] + pub fn private_key_from_pem_cb(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 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) -> io::Result<()> + where W: Write + { + let mut mem_bio = try!(MemBio::new()); + + unsafe { + try_ssl!(ffi::PEM_write_bio_RSAPrivateKey(mem_bio.get_handle(), + self.0, + ptr::null(), + ptr::null_mut(), + 0, + None, + ptr::null_mut())); + } + try!(io::copy(&mut mem_bio, writer)); + Ok(()) + } + /// Reads an RSA public key from PEM formatted data. pub fn public_key_from_pem(reader: &mut R) -> io::Result - where R: Read + where R: Read { let mut mem_bio = try!(MemBio::new()); try!(io::copy(reader, &mut mem_bio)); @@ -66,6 +139,58 @@ impl RSA { } } + /// Writes an RSA public key as PEM formatted data + pub fn public_key_to_pem(&self, writer: &mut W) -> io::Result<()> + where W: Write + { + let mut mem_bio = try!(MemBio::new()); + + unsafe { + try_ssl!(ffi::PEM_write_bio_RSA_PUBKEY(mem_bio.get_handle(), self.0)) + }; + + try!(io::copy(&mut mem_bio, writer)); + Ok(()) + } + + pub fn size(&self) -> Option { + if self.has_n() { + unsafe { Some(ffi::RSA_size(self.0) as u32) } + } else { + None + } + } + + pub fn sign(&self, hash: hash::Type, message: &[u8]) -> Result, ErrorStack> { + let k_len = self.size().expect("RSA missing an n"); + let mut sig = vec![0; k_len as usize]; + let mut sig_len = k_len; + + unsafe { + try_ssl!(ffi::RSA_sign(hash.as_nid() as c_int, + message.as_ptr(), + message.len() as u32, + sig.as_mut_ptr(), + &mut sig_len, + self.0)); + assert!(sig_len == k_len); + Ok(sig) + } + } + + pub fn verify(&self, hash: hash::Type, message: &[u8], sig: &[u8]) -> Result { + unsafe { + let result = ffi::RSA_verify(hash.as_nid() as c_int, + message.as_ptr(), + message.len() as u32, + sig.as_ptr(), + sig.len() as u32, + self.0); + try_ssl_if!(result == -1); + Ok(result == 1) + } + } + pub fn as_ptr(&self) -> *mut ffi::RSA { self.0 } @@ -78,9 +203,7 @@ impl RSA { } pub fn has_n(&self) -> bool { - unsafe { - !(*self.0).n.is_null() - } + unsafe { !(*self.0).n.is_null() } } pub fn d(&self) -> Result { @@ -96,9 +219,7 @@ impl RSA { } pub fn has_e(&self) -> bool { - unsafe { - !(*self.0).e.is_null() - } + unsafe { !(*self.0).e.is_null() } } pub fn p(&self) -> Result { @@ -119,3 +240,84 @@ impl fmt::Debug for RSA { write!(f, "RSA") } } + +#[cfg(test)] +mod test { + use std::fs::File; + use std::io::Write; + use super::*; + use crypto::hash::*; + + fn signing_input_rs256() -> Vec { + 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(Type::SHA256, &digest).unwrap(); + + assert_eq!(result, signature_rs256()); + } + + #[test] + pub fn test_verify() { + let mut buffer = File::open("test/rsa.pem.pub").unwrap(); + let public_key = RSA::public_key_from_pem(&mut buffer).unwrap(); + + let mut sha = Hasher::new(Type::SHA256); + sha.write_all(&signing_input_rs256()).unwrap(); + let digest = sha.finish(); + + let result = public_key.verify(Type::SHA256, &digest, &signature_rs256()).unwrap(); + + assert!(result); + } + + #[test] + #[cfg(feature = "catch_unwind")] + pub fn test_password() { + let mut password_queried = false; + let mut buffer = File::open("test/rsa-encrypted.pem").unwrap(); + RSA::private_key_from_pem_cb(&mut buffer, |password| { + password_queried = true; + password[0] = b'm' as _; + password[1] = b'y' as _; + password[2] = b'p' as _; + password[3] = b'a' as _; + password[4] = b's' as _; + password[5] = b's' as _; + 6 + }).unwrap(); + + assert!(password_queried); + } +} diff --git a/openssl/src/crypto/util.rs b/openssl/src/crypto/util.rs new file mode 100644 index 00000000..be72aa59 --- /dev/null +++ b/openssl/src/crypto/util.rs @@ -0,0 +1,58 @@ +use libc::{c_int, c_char, c_void}; + +use std::any::Any; +use std::panic; +use std::slice; + +/// Wraps a user-supplied callback and a slot for panics thrown inside the callback (while FFI +/// frames are on the stack). +/// +/// When dropped, checks if the callback has panicked, and resumes unwinding if so. +pub struct CallbackState { + /// 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: FnOnce(&mut [i8]) -> usize { + let result = panic::catch_unwind(|| { + // build a `i8` slice to pass to the user callback + let pass_slice = unsafe { slice::from_raw_parts_mut(buf, size as usize) }; + let callback = unsafe { &mut *(cb_state as *mut CallbackState) }; + + callback.cb.take().unwrap()(pass_slice) + }); + + if let Ok(len) = result { + return len as c_int; + } else { + return 0; + } +} diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index ae347eee..aafbac76 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.14")] #![cfg_attr(feature = "nightly", feature(const_fn))] #[macro_use] diff --git a/openssl/src/nid.rs b/openssl/src/nid.rs index bfcae15a..874d4a6f 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,26 @@ 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, + SHA224, } diff --git a/openssl/src/ssl/bio.rs b/openssl/src/ssl/bio.rs index 44893b88..3ced1c95 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 89a7f7d4..b18df7b3 100644 --- a/openssl/src/ssl/mod.rs +++ b/openssl/src/ssl/mod.rs @@ -475,6 +475,8 @@ impl SslContext { SslMethod::Dtlsv1_2 => ctx.set_read_ahead(1), _ => {} } + // this is a bit dubious (?) + try!(ctx.set_mode(ffi::SSL_MODE_AUTO_RETRY | ffi::SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)); Ok(ctx) } @@ -527,6 +529,10 @@ impl SslContext { } } + fn set_mode(&self, mode: c_long) -> Result<(), ErrorStack> { + wrap_ssl_result(unsafe { ffi_extras::SSL_CTX_set_mode(self.ctx, mode) as c_int }) + } + pub fn set_tmp_dh(&mut self, dh: DH) -> Result<(), ErrorStack> { wrap_ssl_result(unsafe { ffi_extras::SSL_CTX_set_tmp_dh(self.ctx, dh.raw()) as i32 }) } @@ -729,7 +735,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 { @@ -753,12 +759,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, + } } } } @@ -853,7 +865,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::)); } } @@ -865,7 +879,10 @@ impl Ssl { if ptr.is_null() { None } else { - Some(SslCipher{ cipher: ptr, ph: PhantomData }) + Some(SslCipher { + cipher: ptr, + ph: PhantomData, + }) } } } @@ -918,8 +935,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() @@ -1038,7 +1055,8 @@ pub struct SslStream { unsafe impl Send 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") @@ -1156,8 +1174,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()) }; diff --git a/openssl/src/ssl/tests/mod.rs b/openssl/src/ssl/tests/mod.rs index 94bb4b4b..1fc0076b 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}; use ssl::SSL_VERIFY_PEER; - use crypto::hash::Type::SHA256; + use crypto::hash::Type::{SHA1, SHA256}; use x509::X509StoreContext; use serialize::hex::FromHex; use super::Server; @@ -236,7 +236,7 @@ run_test!(verify_untrusted, |method, stream| { match SslStream::connect(&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(&ctx, stream) { Ok(_) => (), - Err(err) => panic!("Expected success, got {:?}", err) + Err(err) => panic!("Expected success, got {:?}", err), } }); @@ -260,7 +260,7 @@ run_test!(verify_untrusted_callback_override_ok, |method, stream| { match SslStream::connect(&ctx, stream) { Ok(_) => (), - Err(err) => panic!("Expected success, got {:?}", err) + Err(err) => panic!("Expected success, got {:?}", err), } }); @@ -277,11 +277,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(&ctx, stream) { Ok(_) => (), - Err(err) => panic!("Expected success, got {:?}", err) + Err(err) => panic!("Expected success, got {:?}", err), } }); @@ -291,7 +291,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(&ctx, stream).is_err()); }); @@ -315,7 +315,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(&ctx, stream).is_ok()); }); @@ -337,14 +337,14 @@ 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_callback(SSL_VERIFY_PEER, move |_preverify_ok, x509_ctx| { let cert = x509_ctx.get_current_cert(); match cert { None => false, Some(cert) => { - let fingerprint = cert.fingerprint(SHA256).unwrap(); + let fingerprint = cert.fingerprint(SHA1).unwrap(); fingerprint == node_id } } @@ -353,7 +353,7 @@ run_test!(verify_callback_data, |method, stream| { match SslStream::connect(&ctx, stream) { Ok(_) => (), - Err(err) => panic!("Expected success, got {:?}", err) + Err(err) => panic!("Expected success, got {:?}", err), } }); @@ -366,14 +366,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 } } @@ -381,7 +381,7 @@ run_test!(ssl_verify_callback, |method, stream| { match SslStream::connect(ssl, stream) { Ok(_) => (), - Err(err) => panic!("Expected success, got {:?}", err) + Err(err) => panic!("Expected success, got {:?}", err), } assert_eq!(CHECKED.load(Ordering::SeqCst), 1); @@ -475,11 +475,10 @@ fn test_write_direct() { } run_test!(get_peer_certificate, |method, stream| { - let stream = SslStream::connect(&SslContext::new(method).unwrap(), - stream).unwrap(); + let stream = SslStream::connect(&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/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 a928b533..05d8221e 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(); @@ -530,6 +532,17 @@ impl<'ctx> X509<'ctx> { } io::copy(&mut mem_bio, writer).map(|_| ()) } + + /// Returns a DER serialized form of the certificate + pub fn save_der(&self) -> Result, ErrorStack> { + let mut mem_bio = try!(MemBio::new()); + unsafe { + ffi::i2d_X509_bio(mem_bio.get_handle(), self.handle); + } + let mut v = Vec::new(); + drop(io::copy(&mut mem_bio, &mut v)); + Ok(v) + } } extern "C" { @@ -539,9 +552,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) } } @@ -609,6 +622,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) -> io::Result where R: Read @@ -635,6 +652,17 @@ impl X509Req { } io::copy(&mut mem_bio, writer).map(|_| ()) } + + /// Returns a DER serialized form of the CSR + pub fn save_der(&self) -> Result, ErrorStack> { + let mut mem_bio = try!(MemBio::new()); + unsafe { + ffi::i2d_X509_REQ_bio(mem_bio.get_handle(), self.handle); + } + let mut v = Vec::new(); + drop(io::copy(&mut mem_bio, &mut v)); + Ok(v) + } } impl Drop for X509Req { @@ -671,7 +699,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 +721,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 +826,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 +849,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 0032d108..5d9b30ab 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, @@ -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()); } @@ -83,18 +84,27 @@ 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); } +#[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"); @@ -109,7 +119,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] @@ -166,7 +176,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"[..])); } @@ -178,8 +189,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()); diff --git a/openssl/test/cert.pem b/openssl/test/cert.pem index 0ca22e3d..b8c5ce01 100644 --- a/openssl/test/cert.pem +++ b/openssl/test/cert.pem @@ -1,24 +1,21 @@ -----BEGIN CERTIFICATE----- -MIID9DCCAtygAwIBAgIJALuA8gDKi5EzMA0GCSqGSIb3DQEBCwUAMFkxCzAJBgNV -BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX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OCAQEAALVDDD2f25h5ytSkoUqQilybeRDg +bPhTEEC83NWg2snV1yGtwO3zZ+hvX+J/RqOn33ER/RnQCZTB9FGPj566IbLwLSAE +y83GDsbsFEWCL8yN4Q3dQVub7D3HZ5PBtGpBxC7brvJD7OnR3n75QOFC+OaGKUCo +16XulVsB3IQsXdzL4GwoUqWGWaUyf5MkzFruBma16QetK5J10R42skeXssjvqupv +qUQZxzGOzIGuLTBvJrtFxtoTCu+oZV942wGmuyvLwqRfzIODLNcGLS6lGJudXJPT +Vapaj6maldL3qe1X4bxvtglnpdlrOJ65E3YEC1gcD1KUvfO5vItKrP1FbA== -----END CERTIFICATE----- diff --git a/openssl/test/dsa-encrypted.pem b/openssl/test/dsa-encrypted.pem new file mode 100644 index 00000000..9b1984eb --- /dev/null +++ b/openssl/test/dsa-encrypted.pem @@ -0,0 +1,15 @@ +-----BEGIN DSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: DES-EDE3-CBC,5B99FC62C376CA1F + +5nN039tLa3AHnSaQ0lk+Zsguu1EE+EyUlW1GHKs7ls2gOsZH1kR0+A+MiwNKlP24 +Syy8KYyAbgsirhtwN5IOSsA97feR/vHTY4xQ8nEef8tB7VeRJzOFLHGgS0hwIxOM +Tb8gb4y0FtoWdAgorieP4c1emu8VwTTkHd44AArDXsP1Y7s+a3IEMcHcc3tW+qBk +xuVnqBEETL1t0I5rKy+AYvPmGgEZ0dGRRnUlVMC5jMTozJFcStdSzKUY27prUBz2 +FREOJOA/dIjVn1UGijI64Io5sPCAbDPPmG2k4kywbEbd7Ee/MxEvRNcAyv4boyA8 +GnHZTILKi/WY5+SNlHE3YepCFo1XU+59SovB1lDhRmi43L4vfdGc/6y8L/+rbLuU +Y58DxLdOZLTjpf9GLLf9WcpHhNZhwFfBFA8HuT8FtKDPqlf2t65z+1AVV8JTH2wM +BrRHXTrBKn8YgafXD5MisKFmajoAtNZTvhYGm0D8BLIiNwOwLsGfXZ0hYAie0eoI +Xl6MbHp1n/e+R+XKJ3M9DPM8mzWntlltAhS5+Az0Zi4aBdzqQaTpqvEku21sygq8 +Hwm0fpAq7y4bMnjNbMqQVw== +-----END DSA PRIVATE KEY----- diff --git a/openssl/test/dsa.pem b/openssl/test/dsa.pem new file mode 100644 index 00000000..9b550184 --- /dev/null +++ b/openssl/test/dsa.pem @@ -0,0 +1,12 @@ +-----BEGIN DSA PRIVATE KEY----- +MIIBuwIBAAKBgQCkKe/jtYKJNQafaE7kg2aaJOEPUV0Doi451jkXHp5UfLh6+t42 +eabSGkE9WBAlILgaB8yHckLe9+zozN39+SUDp94kb2r38/8w/9Ffhbsep9uiyOj2 +ZRQur6SkpKQDKcnAd6IMZXZcvdSgPC90A6qraYUZKq7Csjn63gbC+IvXHwIVAIgS +PE43lXD8/rGYxos4cxCgGGAxAoGASMV56WhLvVQtWMVI36WSIxbZnC2EsnNIKeVW +yXnP/OmPJ2mdezG7i1alcwsO2TnSLbvjvGPlyzIqZzHvWC8EmDqsfbU+n8we/Eal +sm5nloC8m9ECWpbTzbNdvrAAj9UPVWjcDwg7grAGGysh6lGbBv5P+4zL/niq1UiE +LnKcifgCgYEAo6mAasO0+MVcu8shxxUXXNeTLsZ8NB/BIx9EZ/dzE23ivNW8dq1A +eecAAYhssI2m/CspQvyKw+seCvg4FccxJgB3+mGOe+blFHwO3eAwoyRn/t3DZDHh +FjxKKRsQdy4BkZv+vhTyIYYCw0iPZ5Wfln+pyGGTveIDED1MPG+J6c8CFCJAUlEl +4nHvbC15xLXXpd46zycY +-----END DSA PRIVATE KEY----- diff --git a/openssl/test/dsa.pem.pub b/openssl/test/dsa.pem.pub new file mode 100644 index 00000000..ae298d09 --- /dev/null +++ b/openssl/test/dsa.pem.pub @@ -0,0 +1,12 @@ +-----BEGIN PUBLIC KEY----- +MIIBtzCCASsGByqGSM44BAEwggEeAoGBAKQp7+O1gok1Bp9oTuSDZpok4Q9RXQOi +LjnWORcenlR8uHr63jZ5ptIaQT1YECUguBoHzIdyQt737OjM3f35JQOn3iRvavfz +/zD/0V+Fux6n26LI6PZlFC6vpKSkpAMpycB3ogxldly91KA8L3QDqqtphRkqrsKy +OfreBsL4i9cfAhUAiBI8TjeVcPz+sZjGizhzEKAYYDECgYBIxXnpaEu9VC1YxUjf +pZIjFtmcLYSyc0gp5VbJec/86Y8naZ17MbuLVqVzCw7ZOdItu+O8Y+XLMipnMe9Y +LwSYOqx9tT6fzB78RqWybmeWgLyb0QJaltPNs12+sACP1Q9VaNwPCDuCsAYbKyHq +UZsG/k/7jMv+eKrVSIQucpyJ+AOBhQACgYEAo6mAasO0+MVcu8shxxUXXNeTLsZ8 +NB/BIx9EZ/dzE23ivNW8dq1AeecAAYhssI2m/CspQvyKw+seCvg4FccxJgB3+mGO +e+blFHwO3eAwoyRn/t3DZDHhFjxKKRsQdy4BkZv+vhTyIYYCw0iPZ5Wfln+pyGGT +veIDED1MPG+J6c8= +-----END PUBLIC KEY----- diff --git a/openssl/test/dsaparam.pem b/openssl/test/dsaparam.pem new file mode 100644 index 00000000..53bda543 --- /dev/null +++ b/openssl/test/dsaparam.pem @@ -0,0 +1,9 @@ +-----BEGIN DSA PARAMETERS----- +MIIBHgKBgQCkKe/jtYKJNQafaE7kg2aaJOEPUV0Doi451jkXHp5UfLh6+t42eabS +GkE9WBAlILgaB8yHckLe9+zozN39+SUDp94kb2r38/8w/9Ffhbsep9uiyOj2ZRQu +r6SkpKQDKcnAd6IMZXZcvdSgPC90A6qraYUZKq7Csjn63gbC+IvXHwIVAIgSPE43 +lXD8/rGYxos4cxCgGGAxAoGASMV56WhLvVQtWMVI36WSIxbZnC2EsnNIKeVWyXnP +/OmPJ2mdezG7i1alcwsO2TnSLbvjvGPlyzIqZzHvWC8EmDqsfbU+n8we/Ealsm5n +loC8m9ECWpbTzbNdvrAAj9UPVWjcDwg7grAGGysh6lGbBv5P+4zL/niq1UiELnKc +ifg= +-----END DSA PARAMETERS----- diff --git a/openssl/test/key.pem b/openssl/test/key.pem index 8ee80a8c..d381795d 100644 --- a/openssl/test/key.pem +++ b/openssl/test/key.pem @@ -1,27 +1,28 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpQIBAAKCAQEA1iDxqmqH6cdgEv8pL1Iu0OaFNHaz4feaTtq9cAJqEwS38Rqm -x+3lg4nwkCQ9uSjJ33VC3FusMXUzeu1N9bAet/iMJ5nqS3YJK9jIkI8//sltY90w -OxgUG2gE4RUx2M4uvhHy0Bqva3Ua7rcy7stZ5i/IUqomkOQ/fT+T44QPv2Xus5CD -p5U35COvXDHdVIGGi+xRKEadJHDlhaIqe+9ScfCrZ5eTBcU52SFE2xOlaBX4Rmw5 -26dzMZsQbipr6LAmOh39vw71HWsivXabCBPZTcYc2klTQj5C7bTrec42d2Ex8RLe -Z3pAIiUoxVgNJT9aWLmwvFPHKRda/njwhvxi/wIDAQABAoIBAQC918dqx7hoVBOh -xAfHpJ1NKJPAx90D4no0n0qFHB7fbbeHU5G6f/iUfp+BrB/tIXSZYWU96SjpUHer -7OjJgrQ5d2sLUTKgZK4M6c4oHFkok30gpOI2AksRYU+yHxBqn6JhcZhNWNtd8h1G -t7W4cSHrK0H3yFMY8sQ3Tz7W4Cb2ENIN4wBKeQnmk4k9icG5yz0xLI/vPxqujKij -JWMbk2jNllaUvDgsTAg/MFCzlJH98lzRrX/dhG+q6Rt4S18xac71PMGyUaWduyeC -BHGhHW34361zGQYyeG6eWroTQhvwMHjNxvzA/RiTgHBXV5oRvd9BPPoUS53HYQJO -mzNnfZvBAoGBAPF3VVw+RqG/+OyEkuqE20H35/oSB8tPC6QL/WjWUFwIcSfnkX7H -WmdHBfqCAZlAOqOYgO3iWcgbcOhnggP9J6ssooErt6M7s7hPG/WXwSf0DoCUgtQF -9OrcGNBvwtBMqm82hb8u4IpXUApMYF48MkjbaKSmHU3HQe0sIDese+wlAoGBAOME -YJgtl6t3rcaJ2jzHfEsCTCtCBs2vS9ido73xF3QHTafll/sKMp5bA0mgNhSsphhs -mJCfOl2Cr+0oN90zkumFe4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A76d5uw0pZbWFy7KI4qnzWutCzb+FMPWWsoFtLJLPZy//u/ZCUVFVa4d +0Y/ASNQIESVPXFLAltlLo4MSmsg1vCBsbviEEaPeEjvMrgki93pYtd/aOSgkYC1T +mEq154s5rmqh+h+XRIf7Au0SLw== +-----END PRIVATE KEY----- diff --git a/openssl/test/rsa-encrypted.pem b/openssl/test/rsa-encrypted.pem new file mode 100644 index 00000000..a6249997 --- /dev/null +++ b/openssl/test/rsa-encrypted.pem @@ -0,0 +1,30 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: AES-128-CBC,E2F16153E2BA3D617285A68C896BA6AF + +vO9SnhtGjGe8pG1pN//vsONnvJr+DjU+lFCiSqGMPT7tezDnbehLfS+9kus2HV7r +HmI14JvVG9O7NpF7zMyBRlHYdWcCCWED9Yar0NsWN9419e5pMe/bqIXAzAiJbtT4 +OB9U5XF3m+349zjN1dVXPPLGRmMC1pcHAlofeb5nIUFTvUi5xcsbe1itGjgkkvHb +Bt8NioHTBun8kKrlsFQOuB55ylBU/eWG8DQBtvFOmQ7iWp0RnGQfh8k5e5rcZNpQ +fD9ygc7UVISl0xTrIG4IH15g34H+nrBauKtIPOpNPuXQPOMHCZv3XH8wnhrWHHwT +ZFnQBdXbSpQtMsRh0phG2G+VIlyCgSn4+CxjCJ+TgFtsoK/tU0unmRYc59QnTxxb +qkHYsPs3E0NApQAgH1ENEGl1M+FGLYQH7gftjc3ophBTeRA17sRmD7Y4QBInggsq +Gv6tImPVBdekAjz/Ls/EyMwjAvvrL5eAokqrIsAarGo+zmbJKHzknw2KUz2En0+k +YYaxB4oy9u7bzuQlvio6xYHJEb4K197bby4Dldmqv7YCCJBJwhOBAInMD687viKv +vcUwL8YuS6cW5E8MbvEENlY4+lvKKj3M8Bnyb79cYIPQe92EuCwXU9DZXPRMLwwM +oFEJpF5E/PmNJzu+B52ahHtDrh83WSx71fWqjdTqwkPZhAYo3ztsfFkb/UqUcq8u +rBSebeUjZh0XZ9B04eshZQ5vJUcXGtYIe/77beV3Pv89/fw+zTZjpiP9Q3sZALzf +Qt0YGp0/6qBuqR1tcqdu65AS2hun7yFw7uRavqYKvww4axRiz2do+xWmZFuoCAwD +EWktaUujltpvAc1lo7lg4C6nByefJB9Xqk22N/vpqOsWr1NbAntT42Qj/HF9BVWR +osvN3yMnKYWYe6oSTVnNBDM5obWAIHd3I9gcxTOTb1KsEwt2RrDs5EpB5ptS3Fjo +JfBRhNZQ3cXttrIIhsHgDn9BDNg865/xpIgktKj0gEd60Abx0PqkAIm6IZTh4Efg +7uZwfzxB+saOcddbrW2gNdzVZMC0s2Ye3sqHhtLbAJ3BlXYTxE4CAvTg54Ny+5hF +IjvjlOKgXceSG1cSfk21/wyp9RY3Ft0AEYvvp0kZScWZaoA2aSFDUrchXVhgrEbn +lJ7UptjefwRFIreAlwbKSbIDDNWnyzvIWyHfQ2aYqgnb7W7XqNPSgH9cALCfzirI +dlRHjha0bMUtrjPCC/YfMXzJBVniy0gG6Pd5uC7vz/Awn6/6HRQVNaTQASphPBQ7 +bJuz+JTfzI9OUVCMRMdnb6b35U4P9tibFmnPvzTIPe+3WUmf8aRsLS3NN3G1Webd +PMYVZpMycPaAI0Ht87axhsOzlxCWHYWjdHa+WoNNc1J90TxLCmAHquh5BDaWvjMK +0DySftJZjV7Tf1p2KosmU83LRl39B5NHMbZb1xOEZl9IWwhT/PVKTVZ25xdxWLfb +hF4l8rfvKehIp5r4t8zW1bvI2Hl6vrUvmcUVWt3BfKjxlgwRVD0vvwonMt1INesF +204vUBeXbDsUUicLwOyUgaFvJ3XU3dOyvL9MhOgM5OgoFRRhG+4AS8a5JCD8iLtq +-----END RSA PRIVATE KEY----- diff --git a/openssl/test/rsa.pem b/openssl/test/rsa.pem new file mode 100644 index 00000000..d8185fed --- /dev/null +++ b/openssl/test/rsa.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAofgWCuLjybRlzo0t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db7 +DOX4IKjzdahm+ctDAJN4O/y7OW5FKebvUjdAIt2GuoTZ71iTG+7F0F+lP88jtjP4 +U4qe7VHoewl4MKOfXZKTe+YCS1XbNvfgwJ3Ltyl1OH9hWvu2yza7q+d5PCsDzqtm +27kxuvULVeya+TEdAB1ijQKBgQCH/3r6YrVH/uCWGy6bzV1nGNOdjKc9tmkfOJmN +54dxdixdpozCQ6U4OxZrsj3FcOhHBsqAHvX2uuYjagqvo3cOj1TRqNocX40omfCC +Mx3bD1yPPf/6TI2XECva/ggqEY2mYzmIiA5LVVmc5nrybr+lssFKneeyxN2Wq93S +0iJMdQKBgCGHewxzoa1r8ZMD0LETNrToK423K377UCYqXfg5XMclbrjPbEC3YI1Z +NqMtuhdBJqUnBi6tjKMF+34Xf0CUN8ncuXGO2CAYvO8PdyCixHX52ybaDjy1FtCE +6yUXjoKNXKvUm7MWGsAYH6f4IegOetN5NvmUMFStCSkh7ixZLkN1 +-----END RSA PRIVATE KEY----- diff --git a/openssl/test/rsa.pem.pub b/openssl/test/rsa.pem.pub new file mode 100644 index 00000000..093f2ba1 --- /dev/null +++ b/openssl/test/rsa.pem.pub @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAofgWCuLjybRlzo0tZWJj +NiuSfb4p4fAkd/wWJcyQoTbji9k0l8W26mPddxHmfHQp+Vaw+4qPCJrcS2mJPMEz +P1Pt0Bm4d4QlL+yRT+SFd2lZS+pCgNMsD1W/YpRPEwOWvG6b32690r2jZ47soMZo +9wGzjb/7OMg0LOL+bSf63kpaSHSXndS5z5rexMdbBYUsLA9e+KXBdQOS+UTo7WTB +EMa2R2CapHg665xsmtdVMTBQY4uDZlxvb3qCo5ZwKh9kG4LT6/I5IhlJH7aGhyxX +FvUK+DWNmoudF8NAco9/h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXp +oQIDAQAB +-----END PUBLIC KEY----- diff --git a/openssl/test/run.sh b/openssl/test/run.sh index 829f11e9..85603773 100755 --- a/openssl/test/run.sh +++ b/openssl/test/run.sh @@ -8,7 +8,7 @@ if [ "$TEST_FEATURES" == "true" ]; then fi if [ "$TRAVIS_RUST_VERSION" == "nightly" ]; then - FEATURES="$FEATURES nightly" + FEATURES="$FEATURES nightly catch_unwind" fi if [ "$TRAVIS_OS_NAME" != "osx" ]; then @@ -33,4 +33,4 @@ else fi export PATH=$HOME/openssl/bin:$PATH -(cd openssl && cargo $COMMAND $FLAGS --features "$FEATURES") +(cd openssl && RUST_BACKTRACE=1 cargo $COMMAND $FLAGS --features "$FEATURES")