
Dimostra un use-after-free in Rust in un server web con codice vulnerabile e un trigger multithread per mostrare la corruzione della memoria e la possibile esecuzione di codice.
// uaf_server.rs - Vulnerable Rust HTTP server with use-after-free
use std::sync::{Arc, Mutex};
use std::thread;
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
struct SharedBuffer {
data: Vec<u8>,
}
impl SharedBuffer {
fn new() -> Self { SharedBuffer { data: vec![0; 1024] } }
}
fn handle_client(mut stream: TcpStream, buffer: Arc<Mutex<SharedBuffer>>) {
// Simulate reading request and writing response.
let mut buf = [0; 512];
stream.read(&mut buf).unwrap();
let b = buffer.lock().unwrap();
let ptr = b.data.as_ptr() as *mut u8; // raw pointer
// Drop the lock early? In unsafe block we might send the pointer to another thread.
// Here we simulate a bug: the SharedBuffer is dropped, but we later use the pointer.
drop(b);
// After lock is released, another thread could replace the Vec, freeing the old allocation.
// Unsafe write through the dangling pointer.
unsafe {
*ptr = 42; // use after free!
}
stream.write(b"HTTP/1.1 200 OK\r\n\r\nHello").unwrap();
}
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let buffer = Arc::new(Mutex::new(SharedBuffer::new()));
for stream in listener.incoming() {
let stream = stream.unwrap();
let buf_clone = Arc::clone(&buffer);
thread::spawn(move || {
handle_client(stream, buf_clone);
});
}
}
Un server web Rust utilizza codice unsafe per condividere un buffer tra thread. Una condizione di gara porta a un use‑after‑free, con potenziale corruzione della memoria o divulgazione di informazioni.
Vec sotto lock, il lock viene rilasciato e il vettore viene sostituito da un altro thread, liberando la memoria mentre il puntatore è ancora in uso.rustc uaf_server.rs
./uaf_server
python trigger_uaf.py