rust/tests/ui/abi/stack-protector.rs

100 lines
3.3 KiB
Rust
Raw Normal View History

add rustc option for using LLVM stack smash protection LLVM has built-in heuristics for adding stack canaries to functions. These heuristics can be selected with LLVM function attributes. This patch adds a rustc option `-Z stack-protector={none,basic,strong,all}` which controls the use of these attributes. This gives rustc the same stack smash protection support as clang offers through options `-fno-stack-protector`, `-fstack-protector`, `-fstack-protector-strong`, and `-fstack-protector-all`. The protection this can offer is demonstrated in test/ui/abi/stack-protector.rs. This fills a gap in the current list of rustc exploit mitigations (https://doc.rust-lang.org/rustc/exploit-mitigations.html), originally discussed in #15179. Stack smash protection adds runtime overhead and is therefore still off by default, but now users have the option to trade performance for security as they see fit. An example use case is adding Rust code in an existing C/C++ code base compiled with stack smash protection. Without the ability to add stack smash protection to the Rust code, the code base artifacts could be exploitable in ways not possible if the code base remained pure C/C++. Stack smash protection support is present in LLVM for almost all the current tier 1/tier 2 targets: see test/assembly/stack-protector/stack-protector-target-support.rs. The one exception is nvptx64-nvidia-cuda. This patch follows clang's example, and adds a warning message printed if stack smash protection is used with this target (see test/ui/stack-protector/warn-stack-protector-unsupported.rs). Support for tier 3 targets has not been checked. Since the heuristics are applied at the LLVM level, the heuristics are expected to add stack smash protection to a fraction of functions comparable to C/C++. Some experiments demonstrating how Rust code is affected by the different heuristics can be found in test/assembly/stack-protector/stack-protector-heuristics-effect.rs. There is potential for better heuristics using Rust-specific safety information. For example it might be reasonable to skip stack smash protection in functions which transitively only use safe Rust code, or which uses only a subset of functions the user declares safe (such as anything under `std.*`). Such alternative heuristics could be added at a later point. LLVM also offers a "safestack" sanitizer as an alternative way to guard against stack smashing (see #26612). This could possibly also be included as a stack-protection heuristic. An alternative is to add it as a sanitizer (#39699). This is what clang does: safestack is exposed with option `-fsanitize=safe-stack`. The options are only supported by the LLVM backend, but as with other codegen options it is visible in the main codegen option help menu. The heuristic names "basic", "strong", and "all" are hopefully sufficiently generic to be usable in other backends as well. Reviewed-by: Nikita Popov <nikic@php.net> Extra commits during review: - [address-review] make the stack-protector option unstable - [address-review] reduce detail level of stack-protector option help text - [address-review] correct grammar in comment - [address-review] use compiler flag to avoid merging functions in test - [address-review] specify min LLVM version in fortanix stack-protector test Only for Fortanix test, since this target specifically requests the `--x86-experimental-lvi-inline-asm-hardening` flag. - [address-review] specify required LLVM components in stack-protector tests - move stack protector option enum closer to other similar option enums - rustc_interface/tests: sort debug option list in tracking hash test - add an explicit `none` stack-protector option Revert "set LLVM requirements for all stack protector support test revisions" This reverts commit a49b74f92a4e7d701d6f6cf63d207a8aff2e0f68.
2021-04-06 14:37:49 -05:00
// run-pass
// only-x86_64-unknown-linux-gnu
// revisions: ssp no-ssp
// [ssp] compile-flags: -Z stack-protector=all
// compile-flags: -C opt-level=2
// compile-flags: -g
use std::env;
use std::process::{Command, ExitStatus};
fn main() {
if env::args().len() == 1 {
// The test is initially run without arguments. Start the process again,
// this time *with* an argument; in this configuration, the test program
// will deliberately smash the stack.
let cur_argv0 = env::current_exe().unwrap();
let mut child = Command::new(&cur_argv0);
child.arg("stacksmash");
if cfg!(ssp) {
assert_stack_smash_prevented(&mut child);
} else {
assert_stack_smashed(&mut child);
}
} else {
vulnerable_function();
// If we return here the test is broken: it should either have called
// malicious_code() which terminates the process, or be caught by the
// stack check which also terminates the process.
panic!("TEST BUG: stack smash unsuccessful");
}
}
// Avoid inlining to make sure the return address is pushed to stack.
#[inline(never)]
fn vulnerable_function() {
let mut x = 5usize;
let stackaddr = &mut x as *mut usize;
let bad_code_ptr = malicious_code as usize;
// Overwrite the on-stack return address with the address of `malicious_code()`,
// thereby jumping to that function when returning from `vulnerable_function()`.
unsafe { fill(stackaddr, bad_code_ptr, 20); }
}
// Use an uninlined function with its own stack frame to make sure that we don't
// clobber e.g. the counter or address local variable.
#[inline(never)]
unsafe fn fill(addr: *mut usize, val: usize, count: usize) {
let mut addr = addr;
for _ in 0..count {
*addr = val;
addr = addr.add(1);
}
}
// We jump to malicious_code() having wreaked havoc with the previous stack
// frame and not setting up a new one. This function is therefore constrained,
// e.g. both println!() and std::process::exit() segfaults if called. We
// therefore keep the amount of work to a minimum by calling POSIX functions
// directly.
// The function is un-inlined just to make it possible to set a breakpoint here.
#[inline(never)]
fn malicious_code() {
let msg = [112u8, 119u8, 110u8, 101u8, 100u8, 33u8, 0u8]; // "pwned!\0" ascii
unsafe {
write(1, &msg as *const u8, msg.len());
_exit(0);
}
}
extern "C" {
fn write(fd: i32, buf: *const u8, count: usize) -> isize;
fn _exit(status: i32) -> !;
}
fn assert_stack_smash_prevented(cmd: &mut Command) {
let (status, stdout, stderr) = run(cmd);
assert!(!status.success());
assert!(stdout.is_empty());
assert!(stderr.contains("stack smashing detected"));
}
fn assert_stack_smashed(cmd: &mut Command) {
let (status, stdout, stderr) = run(cmd);
assert!(status.success());
assert!(stdout.contains("pwned!"));
assert!(stderr.is_empty());
}
fn run(cmd: &mut Command) -> (ExitStatus, String, String) {
let output = cmd.output().unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
println!("status: {}", output.status);
println!("stdout: {}", stdout);
println!("stderr: {}", stderr);
(output.status, stdout.to_string(), stderr.to_string())
}