Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 0 additions & 68 deletions jni/cpp/Random.cpp

This file was deleted.

2 changes: 2 additions & 0 deletions rust/tw_crypto/src/crypto_mnemonic/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,6 @@ pub enum Error {
BadEntropyBitCount(usize),
/// The mnemonic has an invalid checksum.
InvalidChecksum,
/// Error from the random number generator.
RandGeneratorError,
}
3 changes: 2 additions & 1 deletion rust/tw_crypto/src/crypto_mnemonic/mnemonic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@ impl Mnemonic {

let entropy_bytes = (word_count / 3) * 4;
let mut entropy = [0u8; (MAX_NB_WORDS / 3) * 4];
RngCore::fill_bytes(rng, &mut entropy[0..entropy_bytes]);
RngCore::try_fill_bytes(rng, &mut entropy[0..entropy_bytes])
.map_err(|_err| Error::RandGeneratorError)?;
let mnemonic = Mnemonic::from_entropy_in(&entropy[0..entropy_bytes])?;
entropy.zeroize();
Ok(mnemonic)
Expand Down
42 changes: 42 additions & 0 deletions rust/tw_crypto/src/ffi/crypto_random.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// SPDX-License-Identifier: Apache-2.0
//
// Copyright © 2017 Trust Wallet.

#![allow(clippy::missing_safety_doc)]

use rand_core::RngCore;
use tw_memory::ffi::c_byte_array_mut::CByteArrayMut;
use tw_memory::ffi::c_result::ErrorCode;
use tw_misc::try_or_else;

#[repr(C)]
pub enum CRandomCode {
Ok = 0,
NullBuffer = 1,
NotAvailable = 2,
}

impl From<CRandomCode> for ErrorCode {
fn from(error: CRandomCode) -> Self {
error as ErrorCode
}
}

/// Fills the provided buffer with cryptographically secure random bytes.
///
/// \param data *non-null* byte array.
/// \param size the length of the `data` array.
/// \return `CRandomCode::Ok` on success, or an error code otherwise.
#[no_mangle]
pub unsafe extern "C" fn crypto_random_buffer(data: *mut u8, size: usize) -> ErrorCode {
if data.is_null() || size == 0 {
return ErrorCode::from(CRandomCode::NullBuffer);
}

let mut bytes_mut = CByteArrayMut::new(data, size);
try_or_else!(
rand::thread_rng().try_fill_bytes(bytes_mut.as_mut()),
|| ErrorCode::from(CRandomCode::NotAvailable)
);
ErrorCode::from(CRandomCode::Ok)
}
1 change: 1 addition & 0 deletions rust/tw_crypto/src/ffi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ pub mod crypto_hd_node;
pub mod crypto_hd_node_public;
pub mod crypto_mnemonic;
pub mod crypto_pbkdf2;
pub mod crypto_random;
pub mod crypto_scrypt;
49 changes: 49 additions & 0 deletions rust/tw_crypto/tests/crypto_random_ffi.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// SPDX-License-Identifier: Apache-2.0
//
// Copyright © 2017 Trust Wallet.

use std::ptr;
use tw_crypto::ffi::crypto_random::{crypto_random_buffer, CRandomCode};

#[test]
fn test_crypto_random_buffer() {
let sizes = &[1_usize, 2, 16, 32, 64, 128, 200, 1000, 10_000];
for size in sizes.iter().copied() {
let mut buffer_0 = vec![0u8; size];
let result = unsafe { crypto_random_buffer(buffer_0.as_mut_ptr(), size) };
assert_eq!(result, CRandomCode::Ok as i32);

if size < 16 {
continue;
}

// Check that not all values are the same
let first_value = buffer_0[0];
assert!(
buffer_0.iter().any(|&b| b != first_value),
"Buffer contains all the same values"
);

// Check that two consecutive random buffers are not equal.
let mut buffer_1 = vec![0u8; size];
let result = unsafe { crypto_random_buffer(buffer_1.as_mut_ptr(), size) };
assert_eq!(result, CRandomCode::Ok as i32);
assert_ne!(
buffer_0, buffer_1,
"Two consecutive random buffers are equal"
);
}
}

#[test]
fn test_crypto_random_buffer_null_buffer() {
// Pass data=null & size=1 intentionally with null pointer to test null buffer case.
let result = unsafe { crypto_random_buffer(ptr::null_mut(), 1) };
assert_eq!(result, CRandomCode::NullBuffer as i32);

// Pass data=!null & size=0 intentionally to test null buffer case.
let non_empty_buffer = &mut [0_u8];
let result = unsafe { crypto_random_buffer(non_empty_buffer.as_mut_ptr(), 0) };
assert_eq!(result, CRandomCode::NullBuffer as i32);
assert_eq!(non_empty_buffer, &[0_u8]);
}
29 changes: 29 additions & 0 deletions rust/tw_memory/src/ffi/c_byte_array_mut.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// SPDX-License-Identifier: Apache-2.0
//
// Copyright © 2017 Trust Wallet.

/// A C-compatible wrapper over a mutable byte array pointer given as an FFI argument.
#[repr(C)]
pub struct CByteArrayMut {
data: *mut u8,
size: usize,
}

impl CByteArrayMut {
/// Creates a new `CByteArrayMut` from the allocated byte array.
pub fn new(data: *mut u8, size: usize) -> CByteArrayMut {
CByteArrayMut { data, size }
}

/// Returns a slice.
///
/// # Safety
///
/// The inner data must be valid.
pub unsafe fn as_mut(&mut self) -> &mut [u8] {
if self.data.is_null() {
return &mut [];
}
std::slice::from_raw_parts_mut(self.data, self.size)
}
}
1 change: 1 addition & 0 deletions rust/tw_memory/src/ffi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use std::ffi::{c_char, CString};

pub mod c_byte_array;
pub mod c_byte_array_mut;
pub mod c_byte_array_ref;
pub mod c_result;
pub mod tw_data;
Expand Down
4 changes: 3 additions & 1 deletion src/FIO/Encryption.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ Data Encryption::checkEncrypt(const Data& secret, const Data& message, Data& iv)
if (iv.size() == 0) {
// fill iv with strong random value
iv = Data(IvSize);
random_buffer(iv.data(), iv.size());
if (Random::random_buffer(iv.data(), iv.size()) != Random::OK) {
throw std::runtime_error("Unable to generate random iv");
}
} else {
if (iv.size() != IvSize) {
throw std::invalid_argument("invalid IV size");
Expand Down
4 changes: 3 additions & 1 deletion src/Keystore/AESParameters.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ namespace {

Data generateIv(std::size_t blockSize = TW::Keystore::gBlockSize) {
auto iv = Data(blockSize, 0);
random_buffer(iv.data(), blockSize);
if (Random::random_buffer(iv.data(), blockSize) != Random::OK) {
throw std::runtime_error("Unable to generate random iv");
}
return iv;
}

Expand Down
4 changes: 3 additions & 1 deletion src/Keystore/PBKDF2Parameters.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ namespace TW::Keystore {

PBKDF2Parameters::PBKDF2Parameters()
: salt(32) {
random_buffer(salt.data(), salt.size());
if (Random::random_buffer(salt.data(), salt.size()) != Random::OK) {
throw std::runtime_error("Error generating random salt");
}
}

// -----------------
Expand Down
4 changes: 3 additions & 1 deletion src/Keystore/ScryptParameters.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ namespace internal {

Data randomSalt() {
Data salt(32);
random_buffer(salt.data(), salt.size());
if (Random::random_buffer(salt.data(), salt.size()) != Random::OK) {
throw std::runtime_error("Error generating random salt");
}
return salt;
}

Expand Down
10 changes: 4 additions & 6 deletions src/interface/TWPrivateKey.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,11 @@ using namespace TW;

struct TWPrivateKey *TWPrivateKeyCreate(enum TWCurve curve) {
Data bytes(PrivateKey::_size);
random_buffer(bytes.data(), PrivateKey::_size);
if (Random::random_buffer(bytes.data(), PrivateKey::_size) != Random::OK) {
return nullptr;
}
if (!PrivateKey::isValid(bytes, curve)) {
// Under no circumstance return an invalid private key. We'd rather
// crash. This also captures cases where the random generator fails
// since we initialize the array to zeros, which is an invalid private
// key.
std::terminate();
return nullptr;
}

return new TWPrivateKey{ PrivateKey(std::move(bytes), curve) };
Expand Down
48 changes: 13 additions & 35 deletions src/rand.cpp
Original file line number Diff line number Diff line change
@@ -1,41 +1,19 @@
/**
* Copyright (c) 2013-2014 Tomas Dzetkulic
* Copyright (c) 2013-2014 Pavol Rusnak
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
// SPDX-License-Identifier: Apache-2.0
//
// Copyright © 2017 Trust Wallet.

#include "rand.h"
#include "rust/Wrapper.h"

#include <fcntl.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <stdexcept>
namespace TW::Random {

void __attribute__((weak)) random_buffer(uint8_t *buf, size_t len) {
int randomData = open("/dev/urandom", O_RDONLY);
if (randomData < 0) {
throw std::runtime_error("Failed to open /dev/urandom");
RandomResult random_buffer(uint8_t *buf, size_t len) {
const int32_t res = Rust::crypto_random_buffer(buf, len);
if (res == static_cast<int32_t>(Rust::OK_CODE)) {
return OK;
}
if (read(randomData, buf, len) < len) {
throw std::runtime_error("Failed to read from /dev/urandom");
}
close(randomData);

return ERROR_UNKNOWN;
}

} // namespace TW::Random
50 changes: 13 additions & 37 deletions src/rand.h
Original file line number Diff line number Diff line change
@@ -1,43 +1,19 @@
/**
* Copyright (c) 2013-2014 Tomas Dzetkulic
* Copyright (c) 2013-2014 Pavol Rusnak
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
// SPDX-License-Identifier: Apache-2.0
//
// Copyright © 2017 Trust Wallet.

#ifndef __RAND_H__
#define __RAND_H__
#pragma once

#include <stdint.h>
#include <stdlib.h>
#include "Data.h"

#ifdef __cplusplus
extern "C" {
#endif
namespace TW::Random {

void random_buffer(uint8_t *buf, size_t len);
enum RandomResult : int32_t {
OK = 0,
ERROR_UNKNOWN = -1,
};

//uint32_t random_uniform(uint32_t n);
//void random_permute(char *buf, size_t len);
// Fills the provided buffer with cryptographically secure random bytes.
RandomResult random_buffer(uint8_t *buf, size_t len);

#ifdef __cplusplus
} /* extern "C" */
#endif

#endif
}
Loading
Loading