mirror of
https://github.com/dani-garcia/vaultwarden.git
synced 2025-09-11 11:15:58 +03:00
Use constant size generic parameter for random bytes generation
All uses of `get_random()` were in the form of: `&get_random(vec![0u8; SIZE])` with `SIZE` being a constant. Building a `Vec` is unnecessary for two reasons. First, it uses a very short-lived dynamic memory allocation. Second, a `Vec` is a resizable object, which is useless in those context when random data have a fixed size and will only be read. `get_random_bytes()` takes a constant as a generic parameter and returns an array with the requested number of random bytes. Stack safety analysis: the random bytes will be allocated on the caller stack for a very short time (until the encoding function has been called on the data). In some cases, the random bytes take less room than the `Vec` did (a `Vec` is 24 bytes on a 64 bit computer). The maximum used size is 180 bytes, which makes it for 0.008% of the default stack size for a Rust thread (2MiB), so this is a non-issue. Also, most of the uses of those random bytes are to encode them using an `Encoding`. The function `crypto::encode_random_bytes()` generates random bytes and encode them with the provided `Encoding`, leading to code deduplication. `generate_id()` has also been converted to use a constant generic parameter as well since the length of the requested String is always a constant.
This commit is contained in:
@@ -34,7 +34,7 @@ async fn generate_authenticator(data: JsonUpcase<PasswordData>, headers: Headers
|
||||
|
||||
let (enabled, key) = match twofactor {
|
||||
Some(tf) => (true, tf.data),
|
||||
_ => (false, BASE32.encode(&crypto::get_random(vec![0u8; 20]))),
|
||||
_ => (false, crypto::encode_random_bytes::<20>(BASE32)),
|
||||
};
|
||||
|
||||
Ok(Json(json!({
|
||||
|
@@ -105,7 +105,7 @@ async fn recover(data: JsonUpcase<RecoverTwoFactor>, mut conn: DbConn) -> JsonRe
|
||||
|
||||
async fn _generate_recover_code(user: &mut User, conn: &mut DbConn) {
|
||||
if user.totp_recover.is_none() {
|
||||
let totp_recover = BASE32.encode(&crypto::get_random(vec![0u8; 20]));
|
||||
let totp_recover = crypto::encode_random_bytes::<20>(BASE32);
|
||||
user.totp_recover = Some(totp_recover);
|
||||
user.save(conn).await.ok();
|
||||
}
|
||||
|
@@ -56,7 +56,7 @@ fn negotiate(_headers: Headers) -> Json<JsonValue> {
|
||||
use crate::crypto;
|
||||
use data_encoding::BASE64URL;
|
||||
|
||||
let conn_id = BASE64URL.encode(&crypto::get_random(vec![0u8; 16]));
|
||||
let conn_id = crypto::encode_random_bytes::<16>(BASE64URL);
|
||||
let mut available_transports: Vec<JsonValue> = Vec::new();
|
||||
|
||||
if CONFIG.websocket_enabled() {
|
||||
|
Reference in New Issue
Block a user