AK+Everywhere: Change AK::fill_with_random to accept a Bytes object

Rather than the very C-like API we currently have, accepting a void* and
a length, let's take a Bytes object instead. In almost all existing
cases, the compiler figures out the length.
This commit is contained in:
Timothy Flynn 2023-04-02 13:08:43 -04:00 committed by Andreas Kling
parent 5c045b6934
commit 15532df83d
20 changed files with 37 additions and 39 deletions

View file

@ -7,6 +7,7 @@
#pragma once #pragma once
#include <AK/Platform.h> #include <AK/Platform.h>
#include <AK/Span.h>
#include <AK/StdLibExtras.h> #include <AK/StdLibExtras.h>
#include <AK/Types.h> #include <AK/Types.h>
#include <stdlib.h> #include <stdlib.h>
@ -21,36 +22,32 @@
namespace AK { namespace AK {
inline void fill_with_random([[maybe_unused]] void* buffer, [[maybe_unused]] size_t length) inline void fill_with_random([[maybe_unused]] Bytes bytes)
{ {
#if defined(AK_OS_SERENITY) || defined(AK_OS_ANDROID) #if defined(AK_OS_SERENITY) || defined(AK_OS_ANDROID)
arc4random_buf(buffer, length); arc4random_buf(bytes.data(), bytes.size());
#elif defined(OSS_FUZZ) #elif defined(OSS_FUZZ)
#else #else
auto fill_with_random_fallback = [&]() { auto fill_with_random_fallback = [&]() {
char* char_buffer = static_cast<char*>(buffer); for (auto& byte : bytes)
for (size_t i = 0; i < length; i++) byte = rand();
char_buffer[i] = rand();
}; };
# if defined(__unix__) or defined(AK_OS_MACOS) # if defined(__unix__) or defined(AK_OS_MACOS)
// The maximum permitted value for the getentropy length argument. // The maximum permitted value for the getentropy length argument.
static constexpr size_t getentropy_length_limit = 256; static constexpr size_t getentropy_length_limit = 256;
auto iterations = bytes.size() / getentropy_length_limit;
auto iterations = length / getentropy_length_limit;
auto remainder = length % getentropy_length_limit;
auto address = reinterpret_cast<FlatPtr>(buffer);
for (size_t i = 0; i < iterations; ++i) { for (size_t i = 0; i < iterations; ++i) {
if (getentropy(reinterpret_cast<void*>(address), getentropy_length_limit) != 0) { if (getentropy(bytes.data(), getentropy_length_limit) != 0) {
fill_with_random_fallback(); fill_with_random_fallback();
return; return;
} }
address += getentropy_length_limit; bytes = bytes.slice(getentropy_length_limit);
} }
if (remainder == 0 || getentropy(reinterpret_cast<void*>(address), remainder) == 0) if (bytes.is_empty() || getentropy(bytes.data(), bytes.size()) == 0)
return; return;
# endif # endif
@ -62,7 +59,7 @@ template<typename T>
inline T get_random() inline T get_random()
{ {
T t; T t;
fill_with_random(&t, sizeof(T)); fill_with_random({ &t, sizeof(T) });
return t; return t;
} }

View file

@ -59,7 +59,7 @@ static bool test_single(Testcase<TArg> const& testcase)
// Setup // Setup
ByteBuffer actual = ByteBuffer::create_uninitialized(SANDBOX_CANARY_SIZE + testcase.dest_n + SANDBOX_CANARY_SIZE).release_value(); ByteBuffer actual = ByteBuffer::create_uninitialized(SANDBOX_CANARY_SIZE + testcase.dest_n + SANDBOX_CANARY_SIZE).release_value();
fill_with_random(actual.data(), actual.size()); fill_with_random(actual);
ByteBuffer expected = actual; ByteBuffer expected = actual;
VERIFY(actual.offset_pointer(0) != expected.offset_pointer(0)); VERIFY(actual.offset_pointer(0) != expected.offset_pointer(0));
actual.overwrite(SANDBOX_CANARY_SIZE, testcase.dest, testcase.dest_n); actual.overwrite(SANDBOX_CANARY_SIZE, testcase.dest, testcase.dest_n);

View file

@ -56,7 +56,7 @@ static bool test_single(Testcase const& testcase)
// Setup // Setup
ByteBuffer actual = ByteBuffer::create_uninitialized(SANDBOX_CANARY_SIZE + testcase.dest_n + SANDBOX_CANARY_SIZE).release_value(); ByteBuffer actual = ByteBuffer::create_uninitialized(SANDBOX_CANARY_SIZE + testcase.dest_n + SANDBOX_CANARY_SIZE).release_value();
fill_with_random(actual.data(), actual.size()); fill_with_random(actual);
ByteBuffer expected = actual; ByteBuffer expected = actual;
VERIFY(actual.offset_pointer(0) != expected.offset_pointer(0)); VERIFY(actual.offset_pointer(0) != expected.offset_pointer(0));
actual.overwrite(SANDBOX_CANARY_SIZE, testcase.dest, testcase.dest_n); actual.overwrite(SANDBOX_CANARY_SIZE, testcase.dest, testcase.dest_n);

View file

@ -115,7 +115,7 @@ TEST_CASE(deflate_decompress_zeroes)
TEST_CASE(deflate_round_trip_store) TEST_CASE(deflate_round_trip_store)
{ {
auto original = ByteBuffer::create_uninitialized(1024).release_value(); auto original = ByteBuffer::create_uninitialized(1024).release_value();
fill_with_random(original.data(), 1024); fill_with_random(original);
auto compressed = Compress::DeflateCompressor::compress_all(original, Compress::DeflateCompressor::CompressionLevel::STORE); auto compressed = Compress::DeflateCompressor::compress_all(original, Compress::DeflateCompressor::CompressionLevel::STORE);
EXPECT(!compressed.is_error()); EXPECT(!compressed.is_error());
auto uncompressed = Compress::DeflateDecompressor::decompress_all(compressed.value()); auto uncompressed = Compress::DeflateDecompressor::decompress_all(compressed.value());
@ -126,7 +126,7 @@ TEST_CASE(deflate_round_trip_store)
TEST_CASE(deflate_round_trip_compress) TEST_CASE(deflate_round_trip_compress)
{ {
auto original = ByteBuffer::create_zeroed(2048).release_value(); auto original = ByteBuffer::create_zeroed(2048).release_value();
fill_with_random(original.data(), 1024); // we pre-filled the second half with 0s to make sure we test back references as well fill_with_random(original.bytes().trim(1024)); // we pre-filled the second half with 0s to make sure we test back references as well
// Since the different levels just change how much time is spent looking for better matches, just use fast here to reduce test time // Since the different levels just change how much time is spent looking for better matches, just use fast here to reduce test time
auto compressed = Compress::DeflateCompressor::compress_all(original, Compress::DeflateCompressor::CompressionLevel::FAST); auto compressed = Compress::DeflateCompressor::compress_all(original, Compress::DeflateCompressor::CompressionLevel::FAST);
EXPECT(!compressed.is_error()); EXPECT(!compressed.is_error());
@ -139,7 +139,7 @@ TEST_CASE(deflate_round_trip_compress_large)
{ {
auto size = Compress::DeflateCompressor::block_size * 2; auto size = Compress::DeflateCompressor::block_size * 2;
auto original = ByteBuffer::create_uninitialized(size).release_value(); // Compress a buffer larger than the maximum block size to test the sliding window mechanism auto original = ByteBuffer::create_uninitialized(size).release_value(); // Compress a buffer larger than the maximum block size to test the sliding window mechanism
fill_with_random(original.data(), size); fill_with_random(original);
// Since the different levels just change how much time is spent looking for better matches, just use fast here to reduce test time // Since the different levels just change how much time is spent looking for better matches, just use fast here to reduce test time
auto compressed = Compress::DeflateCompressor::compress_all(original, Compress::DeflateCompressor::CompressionLevel::FAST); auto compressed = Compress::DeflateCompressor::compress_all(original, Compress::DeflateCompressor::CompressionLevel::FAST);
EXPECT(!compressed.is_error()); EXPECT(!compressed.is_error());

View file

@ -88,7 +88,7 @@ TEST_CASE(gzip_decompress_repeat_around_buffer)
TEST_CASE(gzip_round_trip) TEST_CASE(gzip_round_trip)
{ {
auto original = ByteBuffer::create_uninitialized(1024).release_value(); auto original = ByteBuffer::create_uninitialized(1024).release_value();
fill_with_random(original.data(), 1024); fill_with_random(original);
auto compressed = Compress::GzipCompressor::compress_all(original); auto compressed = Compress::GzipCompressor::compress_all(original);
EXPECT(!compressed.is_error()); EXPECT(!compressed.is_error());
auto uncompressed = Compress::GzipDecompressor::decompress_all(compressed.value()); auto uncompressed = Compress::GzipDecompressor::decompress_all(compressed.value());

View file

@ -398,7 +398,7 @@ TEST_CASE(test_bigint_import_big_endian_decode_encode_roundtrip)
{ {
u8 random_bytes[128]; u8 random_bytes[128];
u8 target_buffer[128]; u8 target_buffer[128];
fill_with_random(random_bytes, 128); fill_with_random(random_bytes);
auto encoded = Crypto::UnsignedBigInteger::import_data(random_bytes, 128); auto encoded = Crypto::UnsignedBigInteger::import_data(random_bytes, 128);
encoded.export_data({ target_buffer, 128 }); encoded.export_data({ target_buffer, 128 });
EXPECT(memcmp(target_buffer, random_bytes, 128) == 0); EXPECT(memcmp(target_buffer, random_bytes, 128) == 0);

View file

@ -30,7 +30,7 @@ namespace Core {
static DeprecatedString get_salt() static DeprecatedString get_salt()
{ {
char random_data[12]; char random_data[12];
fill_with_random(random_data, sizeof(random_data)); fill_with_random({ random_data, sizeof(random_data) });
StringBuilder builder; StringBuilder builder;
builder.append("$5$"sv); builder.append("$5$"sv);

View file

@ -19,7 +19,7 @@ ErrorOr<ByteBuffer> Ed25519::generate_private_key()
// about randomness. // about randomness.
auto buffer = TRY(ByteBuffer::create_uninitialized(key_size())); auto buffer = TRY(ByteBuffer::create_uninitialized(key_size()));
fill_with_random(buffer.data(), buffer.size()); fill_with_random(buffer);
return buffer; return buffer;
}; };

View file

@ -357,7 +357,7 @@ static bool is_point_on_curve(JacobianPoint const& point)
ErrorOr<ByteBuffer> SECP256r1::generate_private_key() ErrorOr<ByteBuffer> SECP256r1::generate_private_key()
{ {
auto buffer = TRY(ByteBuffer::create_uninitialized(32)); auto buffer = TRY(ByteBuffer::create_uninitialized(32));
fill_with_random(buffer.data(), buffer.size()); fill_with_random(buffer);
return buffer; return buffer;
} }

View file

@ -30,7 +30,7 @@ static void conditional_swap(u32* first, u32* second, u32 condition)
ErrorOr<ByteBuffer> X25519::generate_private_key() ErrorOr<ByteBuffer> X25519::generate_private_key()
{ {
auto buffer = TRY(ByteBuffer::create_uninitialized(BYTES)); auto buffer = TRY(ByteBuffer::create_uninitialized(BYTES));
fill_with_random(buffer.data(), buffer.size()); fill_with_random(buffer);
return buffer; return buffer;
} }

View file

@ -291,7 +291,7 @@ static void modular_multiply_inverse(u32* state, u32* value)
ErrorOr<ByteBuffer> X448::generate_private_key() ErrorOr<ByteBuffer> X448::generate_private_key()
{ {
auto buffer = TRY(ByteBuffer::create_uninitialized(BYTES)); auto buffer = TRY(ByteBuffer::create_uninitialized(BYTES));
fill_with_random(buffer.data(), buffer.size()); fill_with_random(buffer);
return buffer; return buffer;
} }

View file

@ -168,7 +168,7 @@ UnsignedBigInteger random_number(UnsignedBigInteger const& min, UnsignedBigInteg
auto buffer = ByteBuffer::create_uninitialized(size).release_value_but_fixme_should_propagate_errors(); // FIXME: Handle possible OOM situation. auto buffer = ByteBuffer::create_uninitialized(size).release_value_but_fixme_should_propagate_errors(); // FIXME: Handle possible OOM situation.
auto* buf = buffer.data(); auto* buf = buffer.data();
fill_with_random(buf, size); fill_with_random(buffer);
UnsignedBigInteger random { buf, size }; UnsignedBigInteger random { buf, size };
// At this point, `random` is a large number, in the range [0, 256^size). // At this point, `random` is a large number, in the range [0, 256^size).
// To get down to the actual range, we could just compute random % range. // To get down to the actual range, we could just compute random % range.

View file

@ -39,7 +39,7 @@ public:
auto em_length = (em_bits + 7) / 8; auto em_length = (em_bits + 7) / 8;
u8 salt[SaltLength]; u8 salt[SaltLength];
fill_with_random(salt, SaltLength); fill_with_random(salt);
if (em_length < hash_length + SaltLength + 2) { if (em_length < hash_length + SaltLength + 2) {
dbgln("Ooops...encoding error"); dbgln("Ooops...encoding error");

View file

@ -343,12 +343,13 @@ void RSA_PKCS1_EME::encrypt(ReadonlyBytes in, Bytes& out)
Vector<u8, 8096> ps; Vector<u8, 8096> ps;
ps.resize(ps_length); ps.resize(ps_length);
fill_with_random(ps.data(), ps_length); fill_with_random(ps);
// since fill_with_random can create zeros (shocking!) // since fill_with_random can create zeros (shocking!)
// we have to go through and un-zero the zeros // we have to go through and un-zero the zeros
for (size_t i = 0; i < ps_length; ++i) for (size_t i = 0; i < ps_length; ++i) {
while (!ps[i]) while (!ps[i])
fill_with_random(ps.span().offset(i), 1); ps[i] = get_random<u8>();
}
u8 paddings[] { 0x00, 0x02 }; u8 paddings[] { 0x00, 0x02 };

View file

@ -18,7 +18,7 @@ namespace TLS {
ByteBuffer TLSv12::build_hello() ByteBuffer TLSv12::build_hello()
{ {
fill_with_random(&m_context.local_random, 32); fill_with_random(m_context.local_random);
auto packet_version = (u16)m_context.options.version; auto packet_version = (u16)m_context.options.version;
auto version = (u16)m_context.options.version; auto version = (u16)m_context.options.version;

View file

@ -157,7 +157,7 @@ void TLSv12::build_rsa_pre_master_secret(PacketBuilder& builder)
u8 random_bytes[48]; u8 random_bytes[48];
size_t bytes = 48; size_t bytes = 48;
fill_with_random(random_bytes, bytes); fill_with_random(random_bytes);
// remove zeros from the random bytes // remove zeros from the random bytes
for (size_t i = 0; i < bytes; ++i) { for (size_t i = 0; i < bytes; ++i) {

View file

@ -159,7 +159,7 @@ void TLSv12::update_packet(ByteBuffer& packet)
u8 iv[16]; u8 iv[16];
Bytes iv_bytes { iv, 16 }; Bytes iv_bytes { iv, 16 };
Bytes { m_context.crypto.local_aead_iv, 4 }.copy_to(iv_bytes); Bytes { m_context.crypto.local_aead_iv, 4 }.copy_to(iv_bytes);
fill_with_random(iv_bytes.offset(4), 8); fill_with_random(iv_bytes.slice(4, 8));
memset(iv_bytes.offset(12), 0, 4); memset(iv_bytes.offset(12), 0, 4);
// write the random part of the iv out // write the random part of the iv out
@ -207,7 +207,7 @@ void TLSv12::update_packet(ByteBuffer& packet)
VERIFY_NOT_REACHED(); VERIFY_NOT_REACHED();
} }
auto iv = iv_buffer_result.release_value(); auto iv = iv_buffer_result.release_value();
fill_with_random(iv.data(), iv.size()); fill_with_random(iv);
// write it into the ciphertext portion of the message // write it into the ciphertext portion of the message
ct.overwrite(header_size, iv.data(), iv.size()); ct.overwrite(header_size, iv.data(), iv.size());

View file

@ -61,7 +61,7 @@ WebIDL::ExceptionOr<JS::Value> Crypto::get_random_values(JS::Value array) const
// FIXME: Handle SharedArrayBuffers // FIXME: Handle SharedArrayBuffers
// 3. Overwrite all elements of array with cryptographically strong random values of the appropriate type. // 3. Overwrite all elements of array with cryptographically strong random values of the appropriate type.
fill_with_random(typed_array.viewed_array_buffer()->buffer().data(), typed_array.viewed_array_buffer()->buffer().size()); fill_with_random(typed_array.viewed_array_buffer()->buffer());
// 4. Return array. // 4. Return array.
return array; return array;
@ -88,7 +88,7 @@ ErrorOr<String> generate_random_uuid()
u8 bytes[16]; u8 bytes[16];
// 2. Fill bytes with cryptographically secure random bytes. // 2. Fill bytes with cryptographically secure random bytes.
fill_with_random(bytes, 16); fill_with_random(bytes);
// 3. Set the 4 most significant bits of bytes[6], which represent the UUID version, to 0100. // 3. Set the 4 most significant bits of bytes[6], which represent the UUID version, to 0100.
bytes[6] &= ~(1 << 7); bytes[6] &= ~(1 << 7);

View file

@ -184,7 +184,7 @@ void WebSocket::send_client_handshake()
// 7. 16-byte nonce encoded as Base64 // 7. 16-byte nonce encoded as Base64
u8 nonce_data[16]; u8 nonce_data[16];
fill_with_random(nonce_data, 16); fill_with_random(nonce_data);
// FIXME: change to TRY() and make method fallible // FIXME: change to TRY() and make method fallible
m_websocket_key = MUST(encode_base64({ nonce_data, 16 })).to_deprecated_string(); m_websocket_key = MUST(encode_base64({ nonce_data, 16 })).to_deprecated_string();
builder.appendff("Sec-WebSocket-Key: {}\r\n", m_websocket_key); builder.appendff("Sec-WebSocket-Key: {}\r\n", m_websocket_key);
@ -579,7 +579,7 @@ void WebSocket::send_frame(WebSocket::OpCode op_code, ReadonlyBytes payload, boo
// > Clients MUST choose a new masking key for each frame, using an algorithm // > Clients MUST choose a new masking key for each frame, using an algorithm
// > that cannot be predicted by end applications that provide data // > that cannot be predicted by end applications that provide data
u8 masking_key[4]; u8 masking_key[4];
fill_with_random(masking_key, 4); fill_with_random(masking_key);
m_impl->send(ReadonlyBytes(masking_key, 4)); m_impl->send(ReadonlyBytes(masking_key, 4));
// don't try to send empty payload // don't try to send empty payload
if (payload.size() == 0) if (payload.size() == 0)

View file

@ -136,7 +136,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
auto get_salt = []() -> ErrorOr<DeprecatedString> { auto get_salt = []() -> ErrorOr<DeprecatedString> {
char random_data[12]; char random_data[12];
fill_with_random(random_data, sizeof(random_data)); fill_with_random({ random_data, sizeof(random_data) });
StringBuilder builder; StringBuilder builder;
builder.append("$5$"sv); builder.append("$5$"sv);