20 行代码速通 Safe Rust Double Free (整活向)

受到 cve-rs 项目启发,利用 Type system 的固有 Unsoundness 实现一个经典的 Double Free。

#代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#[inline(never)]
pub const fn lifetime_translator<'a, 'b, T: ?Sized>(_: &'a &'b (), x: &'b mut T) -> &'a mut T {
x
}

pub fn expand<'a, 'b, T: ?Sized>(x: &'a mut T) -> &'b mut T {
let f: for<'x> fn(_, &'x mut T) -> &'b mut T = lifetime_translator;
f(STATIC_UNIT, x)
}

pub const STATIC_UNIT: &&() = &&();

pub fn main() {
let dead = expand(&mut vec![1, 2, 3, 4, 5, 6, 7, 8]);
dead.push(1);
}

#运行

1
2
3
4
frezcirno@homelab:~/unsound-rust$ rustc unsound.rs 
frezcirno@homelab:~/unsound-rust$ ./unsound
free(): double free detected in tcache 2
已中止