More fuzzing progress

This commit is contained in:
momo5502
2024-09-24 18:35:34 +02:00
parent 7547fee251
commit a259072b27
14 changed files with 321 additions and 94 deletions

View File

@@ -0,0 +1,11 @@
file(GLOB_RECURSE SRC_FILES CONFIGURE_DEPENDS
*.cpp
*.hpp
*.rc
)
list(SORT SRC_FILES)
add_executable(bad-sample ${SRC_FILES})
momo_assign_source_group(${SRC_FILES})

70
src/bad-sample/bad.cpp Normal file
View File

@@ -0,0 +1,70 @@
#include <cstdint>
#include <cstdio>
#include <Windows.h>
#define THE_SIZE 30
extern "C" __declspec(noinline)
__declspec(dllexport)
void vulnerable(const uint8_t* data, const size_t size)
{
if (size < 10)
{
return;
}
if (data[9] != 'A')
{
return;
}
if (data[8] != 'B')
{
return;
}
if (data[7] != 'C')
{
return;
}
if (data[2] != 'V')
{
return;
}
if (data[4] != 'H')
{
return;
}
if (data[0] != 'H' || data[1] != 'u')
{
return;
}
if (size < 100)
{
return;
}
*(int*)1 = 1;
}
uint8_t buffer[THE_SIZE] = {};
int main(int argc, const char* argv[])
{
const void* input = buffer;
auto size = sizeof(buffer);
if (argc > 1)
{
input = argv[1];
size = strlen(argv[1]);
}
vulnerable((uint8_t*)input, size);
return 0;
}

View File

@@ -36,6 +36,7 @@ struct basic_block
using edge_generation_hook_callback = std::function<void(const basic_block& current_block,
const basic_block& previous_block)>;
using basic_block_hook_callback = std::function<void(const basic_block& block)>;
using instruction_hook_callback = std::function<instruction_hook_continuation()>;
@@ -73,6 +74,7 @@ public:
virtual emulator_hook* hook_interrupt(interrupt_hook_callback callback) = 0;
virtual emulator_hook* hook_edge_generation(edge_generation_hook_callback callback) = 0;
virtual emulator_hook* hook_basic_block(basic_block_hook_callback callback) = 0;
virtual void delete_hook(emulator_hook* hook) = 0;

View File

@@ -5,6 +5,7 @@
#include <string_view>
#include <stdexcept>
#include <cstring>
#include <optional>
namespace utils
{
@@ -12,7 +13,7 @@ namespace utils
class buffer_deserializer;
template <typename T>
concept Serializable = requires(T a, const T ac, buffer_serializer & serializer, buffer_deserializer & deserializer)
concept Serializable = requires(T a, const T ac, buffer_serializer& serializer, buffer_deserializer& deserializer)
{
{ ac.serialize(serializer) } -> std::same_as<void>;
{ a.deserialize(deserializer) } -> std::same_as<void>;
@@ -100,7 +101,7 @@ namespace utils
this->offset_ += sizeof(old_size);
#endif
return result;
}
@@ -148,6 +149,19 @@ namespace utils
return object;
}
template <typename T>
void read_optional(std::optional<T>& val)
{
if (this->read<bool>())
{
val = this->read<T>();
}
else
{
val = {};
}
}
template <typename T>
void read_vector(std::vector<T>& result)
{
@@ -294,6 +308,17 @@ namespace utils
}
}
template <typename T>
void write_optional(const std::optional<T>& val)
{
this->write(val.has_value());
if (val.has_value())
{
this->write(*val);
}
}
template <typename T>
void write_span(const std::span<T> vec)
{

View File

@@ -15,6 +15,11 @@ namespace
{
win_emu.logger.disable_output(true);
win_emu.emu().start_from_ip();
if (win_emu.process().exception_rip.has_value())
{
throw std::runtime_error("Exception!");
}
}
catch (...)
{
@@ -28,7 +33,8 @@ namespace
void forward_emulator(windows_emulator& win_emu)
{
win_emu.emu().hook_memory_execution(0x140001000, 1, [&](uint64_t, size_t, uint64_t)
const auto target = win_emu.process().executable->find_export("vulnerable");
win_emu.emu().hook_memory_execution(target, 1, [&](uint64_t, size_t, uint64_t)
{
win_emu.emu().stop();
});
@@ -39,41 +45,50 @@ namespace
struct fuzzer_executer : fuzzer::executer
{
windows_emulator emu{};
std::span<const std::byte> emulator_data{};
std::unordered_set<uint64_t> visited_blocks{};
const std::function<fuzzer::coverage_functor>* handler{nullptr};
fuzzer_executer(std::span<const std::byte> data)
: emulator_data(data)
{
utils::buffer_deserializer deserializer{data};
emu.deserialize(deserializer);
//emu.save_snapshot();
emu.emu().hook_edge_generation([&](const basic_block& current_block,
const basic_block&)
emu.fuzzing = true;
emu.emu().hook_basic_block([&](const basic_block& block)
{
if (this->handler)
if (this->handler && visited_blocks.emplace(block.address).second)
{
(*this->handler)(current_block.address);
(*this->handler)(block.address);
}
});
utils::buffer_deserializer deserializer{emulator_data};
emu.deserialize(deserializer);
emu.save_snapshot();
const auto ret = emu.emu().read_stack(0);
emu.emu().hook_memory_execution(ret, 1, [&](uint64_t, size_t, uint64_t)
{
emu.emu().stop();
});
}
void restore_emulator()
{
/*utils::buffer_deserializer deserializer{ emulator_data };
emu.deserialize(deserializer);*/
emu.restore_snapshot();
}
fuzzer::execution_result execute(std::span<const uint8_t> data,
const std::function<fuzzer::coverage_functor>& coverage_handler) override
{
printf("Input size: %zd\n", data.size());
//printf("Input size: %zd\n", data.size());
this->handler = &coverage_handler;
this->visited_blocks.clear();
utils::buffer_serializer serializer{};
emu.serialize(serializer);
const auto _ = utils::finally([&]
{
utils::buffer_deserializer deserializer{serializer.get_buffer()};
emu.deserialize(deserializer);
});
//emu.restore_snapshot();
restore_emulator();
const auto memory = emu.emu().allocate_memory(page_align_up(std::max(data.size(), 1ULL)),
memory_permission::read_write);
@@ -117,7 +132,7 @@ namespace
void run_fuzzer(const windows_emulator& base_emulator)
{
const auto concurrency = std::thread::hardware_concurrency();
const auto concurrency = std::thread::hardware_concurrency() + 2;
utils::buffer_serializer serializer{};
base_emulator.serialize(serializer);

View File

@@ -37,13 +37,15 @@ namespace fuzzer
input_generator& generator;
handler& handler;
std::atomic_uint64_t executions{0};
private:
std::atomic_bool stop_{false};
};
void perform_fuzzing_iteration(const fuzzing_context& context, executer& executer)
void perform_fuzzing_iteration(fuzzing_context& context, executer& executer)
{
++context.executions;
context.generator.access_input([&](const std::span<const uint8_t> input)
{
uint64_t score{0};
@@ -52,9 +54,10 @@ namespace fuzzer
++score;
});
if(result == execution_result::error)
if (result == execution_result::error)
{
printf("Found error!");
printf("Found error!\n");
context.stop();
}
return score;
@@ -116,6 +119,11 @@ namespace fuzzer
while (!context.should_stop())
{
std::this_thread::sleep_for(std::chrono::seconds{1});
const auto executions = context.executions.exchange(0);
const auto highest_scorer = context.generator.get_highest_scorer();
const auto avg_score = context.generator.get_average_score();
printf("Executions/s: %lld - Score: %llX - Avg: %.3f\n", executions, highest_scorer.score, avg_score);
}
}
}

View File

@@ -1,5 +1,7 @@
#include "input_generator.hpp"
#include <cassert>
namespace fuzzer
{
namespace
@@ -52,7 +54,31 @@ namespace fuzzer
{
auto next_input = this->generate_next_input();
const auto score = handler(next_input);
this->store_input_entry({std::move(next_input), score});
input_entry e{};
e.data = std::move(next_input);
e.score = score;
this->store_input_entry(std::move(e));
}
input_entry input_generator::get_highest_scorer()
{
std::unique_lock lock{this->mutex_};
return this->highest_scorer_;
}
double input_generator::get_average_score()
{
std::unique_lock lock{this->mutex_};
double score{0.0};
for (const auto& e : this->top_scorer_)
{
score += static_cast<double>(e.score);
}
return score / static_cast<double>(this->top_scorer_.size());
}
void input_generator::store_input_entry(input_entry entry)
@@ -64,29 +90,33 @@ namespace fuzzer
return;
}
const auto score = entry.score;
if (entry.score > this->highest_scorer_.score)
{
this->highest_scorer_ = entry;
}
if (this->top_scorer_.size() < MAX_TOP_SCORER)
{
this->top_scorer_.emplace_back(std::move(entry));
}
else
{
const auto index = this->rng.get<size_t>() % this->top_scorer_.size();
this->top_scorer_[index] = std::move(entry);
}
this->lowest_score = score;
if (score < this->lowest_score)
{
return;
}
for (const auto& e : this->top_scorer_)
const auto insert_at_random = this->rng.get(10) == 0;
const auto index = insert_at_random
? (this->rng.get<size_t>() % this->top_scorer_.size())
: this->lowest_scorer;
this->top_scorer_[index] = std::move(entry);
this->lowest_score = this->top_scorer_[0].score;
this->lowest_scorer = 0;
for (size_t i = 1; i < this->top_scorer_.size(); ++i)
{
if (e.score < this->lowest_score)
if (this->top_scorer_[i].score < this->lowest_score)
{
this->lowest_score = e.score;
this->lowest_score = this->top_scorer_[i].score;
this->lowest_scorer = i;
}
}
}

View File

@@ -24,12 +24,18 @@ namespace fuzzer
void access_input(const std::function<input_handler>& handler);
input_entry get_highest_scorer();
double get_average_score();
private:
std::mutex mutex_{};
random_generator rng{};
std::vector<input_entry> top_scorer_{};
input_score lowest_score{0};
size_t lowest_scorer{0};
input_entry highest_scorer_{};
std::vector<uint8_t> generate_next_input();

View File

@@ -389,6 +389,32 @@ namespace unicorn
return result;
}
emulator_hook* hook_basic_block(basic_block_hook_callback callback) override
{
function_wrapper<void, uc_engine*, uint64_t, size_t> wrapper(
[c = std::move(callback)](uc_engine*, const uint64_t address, const size_t size)
{
basic_block block{};
block.address = address;
block.size = size;
c(block);
});
unicorn_hook hook{*this};
auto container = std::make_unique<hook_container>();
uce(uc_hook_add(*this, hook.make_reference(), UC_HOOK_BLOCK, wrapper.get_function(),
wrapper.get_user_data(), 0, std::numeric_limits<pointer_type>::max())
);
container->add(std::move(wrapper), std::move(hook));
auto* result = container->as_opaque_hook();
this->hooks_.push_back(std::move(container));
return result;
}
emulator_hook* hook_edge_generation(edge_generation_hook_callback callback) override
{
function_wrapper<void, uc_engine*, uc_tb*, uc_tb*> wrapper(

View File

@@ -27,4 +27,17 @@ struct mapped_module
{
return address >= this->image_base && address < (this->image_base + this->size_of_image);
}
uint64_t find_export(const std::string_view export_name) const
{
for (auto& symbol : this->exports)
{
if (symbol.name == export_name)
{
return symbol.address;
}
}
return 0;
}
};

View File

@@ -106,7 +106,6 @@ struct port
}
};
struct process_context
{
process_context(x64_emulator& emu)
@@ -123,6 +122,8 @@ struct process_context
uint64_t current_ip{0};
uint64_t previous_ip{0};
std::optional<uint64_t> exception_rip{};
emulator_object<TEB> teb;
emulator_object<PEB> peb;
emulator_object<RTL_USER_PROCESS_PARAMETERS> process_params;
@@ -150,6 +151,7 @@ struct process_context
buffer.write(this->executed_instructions);
buffer.write(this->current_ip);
buffer.write(this->previous_ip);
buffer.write_optional(this->exception_rip);
buffer.write(this->teb);
buffer.write(this->peb);
buffer.write(this->process_params);
@@ -176,6 +178,7 @@ struct process_context
buffer.read(this->executed_instructions);
buffer.read(this->current_ip);
buffer.read(this->previous_ip);
buffer.read_optional(this->exception_rip);
buffer.read(this->teb);
buffer.read(this->peb);
buffer.read(this->process_params);

View File

@@ -1050,6 +1050,24 @@ namespace
return STATUS_SUCCESS;
}
if (info_class == ProcessDefaultHardErrorMode)
{
if (return_length)
{
return_length.write(sizeof(ULONG));
}
if (process_information_length != sizeof(ULONG))
{
return STATUS_BUFFER_OVERFLOW;
}
const emulator_object<ULONG> info{c.emu, process_information};
info.write(0);
return STATUS_SUCCESS;
}
if (info_class == ProcessEnclaveInformation
|| info_class == ProcessMitigationPolicy)
{
@@ -1078,40 +1096,6 @@ namespace
return STATUS_SUCCESS;
}
if (info_class == ProcessImageFileNameWin32)
{
const auto peb = c.proc.peb.read();
emulator_object<RTL_USER_PROCESS_PARAMETERS> proc_params{c.emu, peb.ProcessParameters};
const auto params = proc_params.read();
const auto length = params.ImagePathName.Length + sizeof(UNICODE_STRING) + 2;
if (return_length)
{
return_length.write(static_cast<uint32_t>(length));
}
if (process_information_length < length)
{
return STATUS_BUFFER_OVERFLOW;
}
const emulator_object<UNICODE_STRING> info{c.emu, process_information};
info.access([&](UNICODE_STRING& str)
{
const auto buffer_start = static_cast<uint64_t>(process_information) + sizeof(UNICODE_STRING);
const auto string = read_unicode_string(c.emu, params.ImagePathName);
c.emu.write_memory(buffer_start, string.c_str(), (string.size() + 1) * 2);
str.Length = params.ImagePathName.Length;
str.MaximumLength = str.Length;
str.Buffer = reinterpret_cast<wchar_t*>(buffer_start);
});
return STATUS_SUCCESS;
}
printf("Unsupported process info class: %X\n", info_class);
c.emu.stop();
@@ -1409,7 +1393,7 @@ namespace
const emulator_object<ULONG> connection_info_length)
{
auto port_name = read_unicode_string(c.emu, server_port_name);
printf("NtConnectPort: %S\n", port_name.c_str());
c.win_emu.logger.print(color::dark_gray, "NtConnectPort: %S\n", port_name.c_str());
port p{};
p.name = std::move(port_name);
@@ -1693,6 +1677,16 @@ namespace
return STATUS_NOT_SUPPORTED;
}
NTSTATUS handle_NtQueryInformationJobObject()
{
return STATUS_NOT_SUPPORTED;
}
NTSTATUS handle_NtSetSystemInformation()
{
return STATUS_NOT_SUPPORTED;
}
NTSTATUS handle_NtRaiseHardError(const syscall_context& c, const NTSTATUS error_status,
const ULONG /*number_of_parameters*/,
const emulator_object<UNICODE_STRING> /*unicode_string_parameter_mask*/,
@@ -1706,7 +1700,26 @@ namespace
}
printf("Hard error: %X\n", static_cast<uint32_t>(error_status));
c.proc.exception_rip = c.emu.read_instruction_pointer();
c.emu.stop();
return STATUS_SUCCESS;
}
NTSTATUS handle_NtRaiseException(const syscall_context& c,
const emulator_object<EXCEPTION_RECORD> /*exception_record*/,
const emulator_object<CONTEXT> thread_context, BOOLEAN handle_exception)
{
if (handle_exception)
{
puts("Unhandled exceptions not supported yet!");
c.emu.stop();
return STATUS_NOT_SUPPORTED;
}
c.proc.exception_rip = thread_context.read().Rip;
c.emu.stop();
return STATUS_SUCCESS;
}
@@ -1900,6 +1913,9 @@ void syscall_dispatcher::add_handlers()
add_handler(NtIsUILanguageComitted);
add_handler(NtQueryInstallUILanguage);
add_handler(NtUpdateWnfStateData);
add_handler(NtRaiseException);
add_handler(NtQueryInformationJobObject);
add_handler(NtSetSystemInformation);
#undef add_handler

View File

@@ -294,19 +294,6 @@ namespace
});
}
uint64_t find_exported_function(const std::vector<exported_symbol>& exports, const std::string_view name)
{
for (auto& symbol : exports)
{
if (symbol.name == name)
{
return symbol.address;
}
}
return 0;
}
using exception_record_map = std::unordered_map<const EXCEPTION_RECORD*, emulator_object<EXCEPTION_RECORD>>;
emulator_object<EXCEPTION_RECORD> save_exception_record(emulator_allocator& allocator,
@@ -505,9 +492,9 @@ void windows_emulator::setup_process(const std::filesystem::path& application,
this->dispatcher_.setup(context.ntdll->exports, context.win32u->exports);
const auto ldr_initialize_thunk = find_exported_function(context.ntdll->exports, "LdrInitializeThunk");
const auto rtl_user_thread_start = find_exported_function(context.ntdll->exports, "RtlUserThreadStart");
context.ki_user_exception_dispatcher = find_exported_function(context.ntdll->exports, "KiUserExceptionDispatcher");
const auto ldr_initialize_thunk = context.ntdll->find_export("LdrInitializeThunk");
const auto rtl_user_thread_start = context.ntdll->find_export("RtlUserThreadStart");
context.ki_user_exception_dispatcher = context.ntdll->find_export("KiUserExceptionDispatcher");
CONTEXT ctx{};
ctx.ContextFlags = CONTEXT_ALL;
@@ -553,7 +540,14 @@ void windows_emulator::setup_hooks()
this->emu().hook_interrupt([&](const int interrupt)
{
printf("Interrupt: %i 0x%llX\n", interrupt, this->emu().read_instruction_pointer());
const auto rip = this->emu().read_instruction_pointer();
printf("Interrupt: %i 0x%llX\n", interrupt, rip);
if (this->fuzzing)
{
this->process().exception_rip = rip;
this->emu().stop();
}
});
this->emu().hook_memory_violation([&](const uint64_t address, const size_t size, const memory_operation operation,
@@ -574,6 +568,13 @@ void windows_emulator::setup_hooks()
name);
}
if (this->fuzzing)
{
this->process().exception_rip = ip;
this->emu().stop();
return memory_violation_continuation::stop;
}
dispatch_access_violation(this->emu(), this->process().ki_user_exception_dispatcher, address, operation);
return memory_violation_continuation::resume;
});

View File

@@ -66,6 +66,7 @@ public:
bool verbose{false};
bool verbose_calls{false};
bool buffer_stdout{false};
bool fuzzing{false};
private:
std::unique_ptr<x64_emulator> emu_{};