Replace C code for serializing Elems with Rust code.

This commit is contained in:
Brian Smith 2017-03-19 11:45:38 -10:00
parent 3e4a207c13
commit 8b026c93f2
12 changed files with 25 additions and 371 deletions

View File

@ -172,7 +172,6 @@ const RING_TEST_SRCS: &'static [&'static str] = &[
("crypto/bn/bn_test.cc"),
("crypto/constant_time_test.c"),
("crypto/test/bn_test_convert.c"),
("crypto/test/bn_test_lib.c"),
("crypto/test/bn_test_new.c"),
("crypto/test/file_test.cc"),
];

View File

@ -93,7 +93,7 @@
/* Prototypes to avoid -Wmissing-prototypes warnings. */
extern "C" int bssl_bn_test_main(RAND *rng);
extern "C" int bssl_bn_test_main(void);
static int HexToBIGNUM(ScopedBIGNUM *out, const char *in) {
@ -447,74 +447,6 @@ static bool RunTest(FileTest *t, void *) {
return false;
}
static bool TestBN2BinPadded(RAND *rng) {
uint8_t zeros[256], out[256], reference[128];
memset(zeros, 0, sizeof(zeros));
// Test edge case at 0.
ScopedBIGNUM n(GFp_BN_new());
if (!n || !GFp_BN_bn2bin_padded(NULL, 0, n.get())) {
fprintf(stderr,
"GFp_BN_bn2bin_padded failed to encode 0 in an empty buffer.\n");
return false;
}
memset(out, -1, sizeof(out));
if (!GFp_BN_bn2bin_padded(out, sizeof(out), n.get())) {
fprintf(stderr,
"GFp_BN_bn2bin_padded failed to encode 0 in a non-empty buffer.\n");
return false;
}
if (memcmp(zeros, out, sizeof(out))) {
fprintf(stderr, "GFp_BN_bn2bin_padded did not zero buffer.\n");
return false;
}
// Test a random numbers at various byte lengths.
for (size_t bytes = 128 - 7; bytes <= 128; bytes++) {
if (!GFp_BN_rand(n.get(), static_cast<int>(bytes * 8), rng)) {
return false;
}
if (GFp_BN_num_bytes(n.get()) != bytes ||
GFp_BN_bn2bin(n.get(), reference) != bytes) {
fprintf(stderr, "Bad result from GFp_BN_rand; bytes.\n");
return false;
}
// Empty buffer should fail.
if (GFp_BN_bn2bin_padded(NULL, 0, n.get())) {
fprintf(stderr,
"GFp_BN_bn2bin_padded incorrectly succeeded on empty buffer.\n");
return false;
}
// One byte short should fail.
if (GFp_BN_bn2bin_padded(out, bytes - 1, n.get())) {
fprintf(stderr, "GFp_BN_bn2bin_padded incorrectly succeeded on short.\n");
return false;
}
// Exactly right size should encode.
if (!GFp_BN_bn2bin_padded(out, bytes, n.get()) ||
memcmp(out, reference, bytes) != 0) {
fprintf(stderr, "GFp_BN_bn2bin_padded gave a bad result.\n");
return false;
}
// Pad up one byte extra.
if (!GFp_BN_bn2bin_padded(out, bytes + 1, n.get()) ||
memcmp(out + 1, reference, bytes) || memcmp(out, zeros, 1)) {
fprintf(stderr, "GFp_BN_bn2bin_padded gave a bad result.\n");
return false;
}
// Pad up to 256.
if (!GFp_BN_bn2bin_padded(out, sizeof(out), n.get()) ||
memcmp(out + sizeof(out) - bytes, reference, bytes) ||
memcmp(out, zeros, sizeof(out) - bytes)) {
fprintf(stderr, "GFp_BN_bn2bin_padded gave a bad result.\n");
return false;
}
}
return true;
}
static int BN_is_word(const BIGNUM *bn, BN_ULONG w) {
return GFp_BN_abs_is_word(bn, w) && (w == 0 || bn->neg == 0);
}
@ -557,28 +489,6 @@ static bool TestHex2BN() {
return true;
}
static bool TestRand(RAND *rng) {
ScopedBIGNUM bn(GFp_BN_new());
if (!bn) {
return false;
}
// Test GFp_BN_rand accounts for degenerate cases
if (!GFp_BN_rand(bn.get(), 0, rng) ||
!GFp_BN_is_zero(bn.get())) {
fprintf(stderr, "GFp_BN_rand gave a bad result.\n");
return false;
}
if (!GFp_BN_rand(bn.get(), 1, rng) ||
!BN_is_word(bn.get(), 1)) {
fprintf(stderr, "GFp_BN_rand gave a bad result.\n");
return false;
}
return true;
}
static bool TestNegativeZero() {
ScopedBIGNUM a(GFp_BN_new());
ScopedBIGNUM b(GFp_BN_new());
@ -762,10 +672,8 @@ static bool TestCmpWord() {
return true;
}
extern "C" int bssl_bn_test_main(RAND *rng) {
if (!TestBN2BinPadded(rng) ||
!TestHex2BN() ||
!TestRand(rng) ||
extern "C" int bssl_bn_test_main() {
if (!TestHex2BN() ||
!TestNegativeZero() ||
!TestBadModulus() ||
!TestCmpWord()) {

View File

@ -100,66 +100,3 @@ int GFp_BN_bin2bn(const uint8_t *in, size_t len, BIGNUM *ret) {
GFp_bn_correct_top(ret);
return 1;
}
/* constant_time_select_ulong returns |x| if |v| is 1 and |y| if |v| is 0. Its
* behavior is undefined if |v| takes any other value. */
static BN_ULONG constant_time_select_ulong(int v, BN_ULONG x, BN_ULONG y) {
BN_ULONG mask = v;
mask--;
return (~mask & x) | (mask & y);
}
/* constant_time_le_size_t returns 1 if |x| <= |y| and 0 otherwise. |x| and |y|
* must not have their MSBs set. */
static int constant_time_le_size_t(size_t x, size_t y) {
return ((x - y - 1) >> (sizeof(size_t) * 8 - 1)) & 1;
}
/* read_word_padded returns the |i|'th word of |in|, if it is not out of
* bounds. Otherwise, it returns 0. It does so without branches on the size of
* |in|, however it necessarily does not have the same memory access pattern. If
* the access would be out of bounds, it reads the last word of |in|. |in| must
* not be zero. */
static BN_ULONG read_word_padded(const BIGNUM *in, size_t i) {
/* Read |in->d[i]| if valid. Otherwise, read the last word. */
BN_ULONG l = in->d[constant_time_select_ulong(
constant_time_le_size_t(in->dmax, i), in->dmax - 1, i)];
/* Clamp to zero if above |d->top|. */
return constant_time_select_ulong(constant_time_le_size_t(in->top, i), 0, l);
}
int GFp_BN_bn2bin_padded(uint8_t *out, size_t len, const BIGNUM *in) {
/* Special case for |in| = 0. Just branch as the probability is negligible. */
if (GFp_BN_is_zero(in)) {
memset(out, 0, len);
return 1;
}
/* Check if the integer is too big. This case can exit early in non-constant
* time. */
if ((size_t)in->top > (len + (BN_BYTES - 1)) / BN_BYTES) {
return 0;
}
if ((len % BN_BYTES) != 0) {
BN_ULONG l = read_word_padded(in, len / BN_BYTES);
if (l >> (8 * (len % BN_BYTES)) != 0) {
return 0;
}
}
/* Write the bytes out one by one. Serialization is done without branching on
* the bits of |in| or on |in->top|, but if the routine would otherwise read
* out of bounds, the memory access pattern can't be fixed. However, for an
* RSA key of size a multiple of the word size, the probability of BN_BYTES
* leading zero octets is low.
*
* See Falko Stenzke, "Manger's Attack revisited", ICICS 2010. */
size_t i = len;
while (i--) {
BN_ULONG l = read_word_padded(in, i / BN_BYTES);
*(out++) = (uint8_t)(l >> (8 * (i % BN_BYTES))) & 0xff;
}
return 1;
}

View File

@ -180,18 +180,6 @@ int GFp_BN_hex2bn(BIGNUM **outp, const char *in) {
return bn_x2bn(outp, in, decode_hex, isxdigit);
}
size_t GFp_BN_bn2bin(const BIGNUM *in, uint8_t *out) {
size_t n, i;
BN_ULONG l;
n = i = GFp_BN_num_bytes(in);
while (i--) {
l = in->d[i / BN_BYTES];
*(out++) = (unsigned char)(l >> (8 * (i % BN_BYTES))) & 0xff;
}
return n;
}
void GFp_BN_set_negative(BIGNUM *bn, int sign) {
if (sign && !GFp_BN_is_zero(bn)) {
bn->neg = 1;

View File

@ -1,162 +0,0 @@
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com). */
#include <openssl/bn.h>
#include <string.h>
#include <openssl/err.h>
#include <openssl/mem.h>
#include "bn_test_lib.h"
#include "rand.h"
#include "../bn/internal.h"
int GFp_BN_rand(BIGNUM *rnd, int bits, RAND *rng) {
uint8_t *buf = NULL;
int ret = 0, bit, bytes, mask;
if (rnd == NULL) {
return 0;
}
if (bits == 0) {
GFp_BN_zero(rnd);
return 1;
}
bytes = (bits + 7) / 8;
bit = (bits - 1) % 8;
mask = 0xff << (bit + 1);
buf = OPENSSL_malloc(bytes);
if (buf == NULL) {
OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
goto err;
}
/* Make a random number. */
if (!GFp_RAND_bytes(rng, buf, bytes)) {
goto err;
}
/* Ensure top bit is always set, and higher bits are not. */
buf[0] |= (1 << bit);
buf[0] &= ~mask;
if (!GFp_BN_bin2bn(buf, bytes, rnd)) {
goto err;
}
ret = 1;
err:
OPENSSL_free(buf);
return (ret);
}

View File

@ -145,20 +145,6 @@ OPENSSL_EXPORT unsigned GFp_BN_num_bytes(const BIGNUM *bn);
void GFp_BN_set_negative(BIGNUM *bn, int sign);
/* Conversion functions. */
/* BN_bn2bin serialises the absolute value of |in| to |out| as a big-endian
* integer, which must have |BN_num_bytes| of space available. It returns the
* number of bytes written. */
OPENSSL_EXPORT size_t GFp_BN_bn2bin(const BIGNUM *in, uint8_t *out);
/* Random generation. */
/* BN_rand sets |rnd| to a random number of length |bits|. The
* most-significant bit, if any, will always be set. */
OPENSSL_EXPORT int GFp_BN_rand(BIGNUM *rnd, int bits, RAND *rng);
#if defined(__cplusplus)
}

View File

@ -201,13 +201,6 @@ OPENSSL_EXPORT int GFp_BN_is_negative(const BIGNUM *bn);
* as a big-endian number. It returns one on success and zero otherwise. */
OPENSSL_EXPORT int GFp_BN_bin2bn(const uint8_t *in, size_t len, BIGNUM *ret);
/* GFp_BN_bn2bin_padded serialises the absolute value of |in| to |out| as a
* big-endian integer. The integer is padded with leading zeros up to size
* |len|. If |len| is smaller than |GFp_BN_num_bytes|, the function fails and
* returns 0. Otherwise, it returns 1. */
OPENSSL_EXPORT int GFp_BN_bn2bin_padded(uint8_t *out, size_t len,
const BIGNUM *in);
/* Internal functions.
*

View File

@ -51,23 +51,21 @@ macro_rules! bssl_test {
// Adapt a BoringSSL test suite to a Rust test like `bssl_test`, passing the
// test suite function a `rand::SecureRandom`.
#[cfg(test)]
macro_rules! bssl_test_rng {
macro_rules! bssl_test {
( $fn_name:ident, $bssl_test_main_fn_name:ident ) => {
#[test]
#[allow(improper_ctypes)]
fn $fn_name() {
use $crate::{c, init, rand};
use $crate::{c, init};
extern {
fn $bssl_test_main_fn_name(rng: *mut rand::RAND) -> c::int;
fn $bssl_test_main_fn_name() -> c::int;
}
init::init_once();
::std::env::set_current_dir(::test::ring_src_path()).unwrap();
let rng = rand::SystemRandom::new();
let mut rng = rand::RAND { rng: &rng };
let result = unsafe {
$bssl_test_main_fn_name(&mut rng)
$bssl_test_main_fn_name()
};
assert_eq!(result, 0);
}

View File

@ -187,7 +187,7 @@ mod private {
mod tests {
#[cfg(all(feature = "use_heap",
not(any(target_os = "macos", target_os = "ios"))))]
bssl_test_rng!(test_bn, bssl_bn_test_main);
bssl_test!(test_bn, bssl_bn_test_main);
bssl_test!(test_constant_time, bssl_constant_time_test_main);
}

View File

@ -350,12 +350,9 @@ impl<M> Elem<M, Unencoded> {
Ok(r)
}
pub fn fill_be_bytes(&self, out: &mut [u8])
-> Result<(), error::Unspecified> {
bssl::map_result(unsafe {
GFp_BN_bn2bin_padded(out.as_mut_ptr(), out.len(),
self.value.as_ref())
})
#[inline]
pub fn fill_be_bytes(&self, out: &mut [u8]) {
limb::big_endian_from_limbs_padded(self.value.limbs(), out)
}
pub fn is_one(&self) -> bool { self.value.is_one() }
@ -719,6 +716,9 @@ impl Nonnegative {
bits::BitLength::from_usize_bits(bits)
}
#[inline]
fn limbs(&self) -> &[limb::Limb] { self.0.limbs() }
fn verify_less_than(&self, other: &Self)
-> Result<(), error::Unspecified> {
let r = unsafe { GFp_BN_ucmp(self.as_ref(), other.as_ref()) };
@ -824,6 +824,13 @@ mod repr_c {
flags: 0,
}
}
#[inline]
pub fn limbs(&self) -> &[limb::Limb] {
unsafe {
core::slice::from_raw_parts(self.d, self.top as usize)
}
}
}
}
@ -833,8 +840,6 @@ extern {
fn GFp_BN_one(r: &mut BIGNUM) -> c::int;
fn GFp_BN_bin2bn(in_: *const u8, len: c::size_t, ret: &mut BIGNUM)
-> c::int;
fn GFp_BN_bn2bin_padded(out_: *mut u8, len: c::size_t, in_: &BIGNUM)
-> c::int;
fn GFp_BN_ucmp(a: &BIGNUM, b: &BIGNUM) -> c::int;
fn GFp_BN_get_positive_u64(a: &BIGNUM) -> u64;
fn GFp_BN_equal_consttime(a: &BIGNUM, b: &BIGNUM) -> c::int;

View File

@ -587,7 +587,9 @@ impl RSASigningState {
Ok(m)
}));
result.fill_be_bytes(signature)
result.fill_be_bytes(signature);
Ok(())
}
}

View File

@ -151,7 +151,7 @@ pub fn verify_rsa(params: &RSAParameters,
// Step 3.
let mut decoded = [0u8; PUBLIC_KEY_PUBLIC_MODULUS_MAX_LEN];
let decoded = &mut decoded[..n_bits.as_usize_bytes_rounded_up()];
try!(m.fill_be_bytes(decoded));
m.fill_be_bytes(decoded);
// Verify the padded message is correct.
let m_hash = digest::digest(params.padding_alg.digest_alg(),