-
Notifications
You must be signed in to change notification settings - Fork 1.9k
fix(random): Enhance security by replacing platform-specific randomizer code with Rust's bindings #4626
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+200
−262
Merged
fix(random): Enhance security by replacing platform-specific randomizer code with Rust's bindings #4626
Changes from 4 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
7fb9321
fix(random):
sergei-boiko-trustwallet bda7c1e
Merge branch 'dev' into fix/random-buffer-error-code
sergei-boiko-trustwallet 16def3a
chore(sync): Fix JNI
sergei-boiko-trustwallet c3210bb
fix(random): Replace platform-specific randomizer code with Rust's ra…
sergei-boiko-trustwallet ecd1fe4
fix(random): Minor change
sergei-boiko-trustwallet 3814d2a
chore(random): `random_buffer` takes `Data&` instead of raw pointers
sergei-boiko-trustwallet aa8289e
Merge branch 'dev' into fix/random-buffer-rust-binding
sergei-boiko-trustwallet abc8d08
fix(random): Change `CByteArrayMut::as_mut` to return Option
sergei-boiko-trustwallet 461b5e1
fix(random): Rename `CByteArrayMut` as `CByteArrayRefMut`
sergei-boiko-trustwallet File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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]); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 { | ||
sergei-boiko-trustwallet marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| 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 []; | ||
sergei-boiko-trustwallet marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| std::slice::from_raw_parts_mut(self.data, self.size) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
|
|
||
sergei-boiko-trustwallet marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return ERROR_UNKNOWN; | ||
| } | ||
|
|
||
| } // namespace TW::Random | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
sergei-boiko-trustwallet marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| }; | ||
|
|
||
| //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 | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.