Skip to content

Commit 9c411ab

Browse files
author
Ariel Ben-Yehuda
committed
Stabilize -Zstack-protector as -Cstack-protector
I propose stabilizing `-Cstack-protector` as `-Zstack-protector`. This PR adds a new `-Cstack-protector` flag, leaving the unstable `-Z` flag as is to ease the transition period. The `-Z` flag will be removed in the future. No RFC/MCP, this flag was added in 84197 and was not deemed large enough to require additional process. The tracking issue for this feature is 114903. The `-Cstack-protector=strong` mode uses the same underlying heuristics as Clang's `-fstack-protector-strong`. These heuristics weren't designed for Rust, and may be over-conservative in some cases - for example, if Rust stores a field's data in an alloca using an LLVM array type, LLVM regard the alloca as meaning that the function has a C array, and enable stack overflow canaries even if the function accesses the alloca in a safe way. Some people thought we should wait on stabilization until there are better heuristics, but I didn't hear about any concrete case where this unduly harms performance, and I think that when a need comes, we can improve the heuristics in LLVM after stabilization. The heuristics do seem to not be under-conservative, so this should not be a security risk. The `-Cstack-protector=basic` mode (`-fstack-protector`) uses heuristics that are specifically designed to catch old-C-style string manipulation. This is not a good fit to Rust, which does not perform much unsafe C-style string manipulation. As far as I can tell, nobody has been asking for it, and few people are using it even in today's C - modern distros (e.g. [Debian]) tend to use `-fstack-protector-strong`. Therefore, `-Cstack-protector=basic` has been **removed**. If anyone is interested in it, they are welcome to add it back as an unstable option. [Debian]: https://wiki.debian.org/Hardening#DEB_BUILD_HARDENING_STACKPROTECTOR_.28gcc.2Fg.2B-.2B-_-fstack-protector-strong.29 Most implementation was done in <rust-lang#84197>. The command-line attribute enables the relevant LLVM attribute on all functions in <https://github.com/rust-lang/rust/blob/68baa87ba6f03f8b6af2a368690161f1601e4040/compiler/rustc_codegen_llvm/src/attributes.rs#L267-L276>. Each target can indicate that it does not support stack canaries - currently, the GPU platforms `nvptx64-nvidia-cuda` and `amdgcn-amd-amdhsa`. On these platforms, use of `-Cstack-protector` causes an error. The feature has tests that make sure that the LLVM heuristic gives reasonable results for several functions, by checking for `__security_check_cookie` (on Windows) or `__stack_chk_fail` (on Linux). See <https://github.com/rust-lang/rust/tree/68baa87ba6f03f8b6af2a368690161f1601e4040/tests/assembly-llvm/stack-protector> No call-for-testing has been conducted, but the feature seems to be in use. No reported bugs seem to exist. - bbjornse was the original implementor at 84197 - mrcnski documented it at 111722 - wesleywiser added tests for Windows at 116037 - davidtwco worked on the feature at 121742 - nikic provided support from the LLVM side (on Zulip on <https://rust-lang.zulipchat.com/#narrow/channel/233931-t-compiler.2Fmajor-changes/topic/Proposal.20for.20Adapt.20Stack.20Protector.20for.20Ru.E2.80.A6.20compiler-team.23841> and elsewhere), thanks nikic! No FIXMEs related to this feature. This feature cannot cause undefined behavior. No changes to reference/spec, docs added to the codegen docs as part of the stabilization PR. No. None. No support needed for rustdoc, clippy, rust-analyzer, rustfmt or rustup. Cargo could expose this as an option in build profiles but I would expect the decision as to what version should be used would be made for the entire crate graph at build time rather than by individual package authors. `-C stack-protector` is propagated to C compilers using cc-rs via rust-lang/cc-rs issue 1550
1 parent 4586feb commit 9c411ab

23 files changed

Lines changed: 164 additions & 62 deletions

bootstrap.example.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -755,7 +755,7 @@
755755
#rust.frame-pointers = false
756756

757757
# Indicates whether stack protectors should be used
758-
# via the unstable option `-Zstack-protector`.
758+
# via `-Cstack-protector`.
759759
#
760760
# Valid options are : `none`(default),`basic`,`strong`, or `all`.
761761
# `strong` and `basic` options may be buggy and are not recommended, see rust-lang/rust#114903.

compiler/rustc_codegen_llvm/src/lib.rs

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -300,19 +300,32 @@ impl CodegenBackend for LlvmCodegenBackend {
300300
Generate stack canaries in all functions.
301301
302302
strong
303-
Generate stack canaries in a function if it either:
304-
- has a local variable of `[T; N]` type, regardless of `T` and `N`
305-
- takes the address of a local variable.
303+
Generate stack canaries for all functions, unless the compiler
304+
can prove these functions can't be the source of a stack
305+
buffer overflow (even in the presence of undefined behavior).
306306
307-
(Note that a local variable being borrowed is not equivalent to its
308-
address being taken: e.g. some borrows may be removed by optimization,
309-
while by-value argument passing may be implemented with reference to a
310-
local stack variable in the ABI.)
307+
This provides the same security guarantees as Clang's
308+
`-fstack-protector=strong`.
309+
310+
The exact rules are unstable and subject to change, but
311+
currently, it generates stack protectors for functions that,
312+
*post-optimization*, contain either arrays (of any size
313+
or type) or address-taken locals.
311314
312315
basic
313-
Generate stack canaries in functions with local variables of `[T; N]`
316+
Generate stack canaries in functions that are heuristically
317+
suspected to contain buffer overflows.
318+
319+
The heuristic is subject to change, but currently it
320+
includes functions with local variables of `[T; N]`
314321
type, where `T` is byte-sized and `N` >= 8.
315322
323+
This heuristic originated from C, where it detects
324+
functions that allocate a `char buf[N];` buffer on the
325+
stack, and are therefore likely to have a stack buffer overflow
326+
in the case of a length-calculation error. It is *not* a good
327+
heuristic for Rust code.
328+
316329
none
317330
Do not generate stack canaries.
318331
"#

compiler/rustc_interface/src/tests.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -641,6 +641,7 @@ fn test_codegen_options_tracking_hash() {
641641
tracked!(relro_level, Some(RelroLevel::Full));
642642
tracked!(soft_float, true);
643643
tracked!(split_debuginfo, Some(SplitDebuginfo::Packed));
644+
tracked!(stack_protector, StackProtector::All);
644645
tracked!(symbol_mangling_version, Some(SymbolManglingVersion::V0));
645646
tracked!(target_cpu, Some(String::from("abc")));
646647
tracked!(target_feature, String::from("all the features, all of them"));
@@ -871,7 +872,6 @@ fn test_unstable_options_tracking_hash() {
871872
tracked!(small_data_threshold, Some(16));
872873
tracked!(split_lto_unit, Some(true));
873874
tracked!(src_hash_algorithm, Some(SourceFileHashAlgorithm::Sha1));
874-
tracked!(stack_protector, StackProtector::All);
875875
tracked!(teach, true);
876876
tracked!(thinlto, Some(true));
877877
tracked!(tiny_const_eval_limit, true);

compiler/rustc_session/messages.ftl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ session_target_requires_unwind_tables = target requires unwind tables, they cann
130130
131131
session_target_small_data_threshold_not_supported = `-Z small-data-threshold` is not supported for target {$target_triple} and will be ignored
132132
133-
session_target_stack_protector_not_supported = `-Z stack-protector={$stack_protector}` is not supported for target {$target_triple} and will be ignored
133+
session_target_stack_protector_not_supported = `-C stack-protector={$stack_protector}` is not supported for target {$target_triple}
134134
135135
session_unexpected_builtin_cfg = unexpected `--cfg {$cfg}` flag
136136
.controlled_by = config `{$cfg_name}` is only supposed to be controlled by `{$controlled_by}`

compiler/rustc_session/src/options.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1917,9 +1917,12 @@ pub mod parse {
19171917
true
19181918
}
19191919

1920-
pub(crate) fn parse_stack_protector(slot: &mut StackProtector, v: Option<&str>) -> bool {
1920+
pub(crate) fn parse_stack_protector(
1921+
slot: &mut Option<StackProtector>,
1922+
v: Option<&str>,
1923+
) -> bool {
19211924
match v.and_then(|s| StackProtector::from_str(s).ok()) {
1922-
Some(ssp) => *slot = ssp,
1925+
Some(ssp) => *slot = Some(ssp),
19231926
_ => return false,
19241927
}
19251928
true
@@ -2211,6 +2214,9 @@ options! {
22112214
#[rustc_lint_opt_deny_field_access("use `Session::split_debuginfo` instead of this field")]
22122215
split_debuginfo: Option<SplitDebuginfo> = (None, parse_split_debuginfo, [TRACKED],
22132216
"how to handle split-debuginfo, a platform-specific option"),
2217+
#[rustc_lint_opt_deny_field_access("use `Session::stack_protector` instead of this field")]
2218+
stack_protector: Option<StackProtector> = (None, parse_stack_protector, [TRACKED],
2219+
"control stack smash protection strategy (`rustc --print stack-protector-strategies` for details)"),
22142220
strip: Strip = (Strip::None, parse_strip, [UNTRACKED],
22152221
"tell the linker which information to strip (`none` (default), `debuginfo` or `symbols`)"),
22162222
symbol_mangling_version: Option<SymbolManglingVersion> = (None,
@@ -2687,7 +2693,7 @@ written to standard error output)"),
26872693
src_hash_algorithm: Option<SourceFileHashAlgorithm> = (None, parse_src_file_hash, [TRACKED],
26882694
"hash algorithm of source files in debug info (`md5`, `sha1`, or `sha256`)"),
26892695
#[rustc_lint_opt_deny_field_access("use `Session::stack_protector` instead of this field")]
2690-
stack_protector: StackProtector = (StackProtector::None, parse_stack_protector, [TRACKED],
2696+
stack_protector: Option<StackProtector> = (None, parse_stack_protector, [TRACKED],
26912697
"control stack smash protection strategy (`rustc --print stack-protector-strategies` for details)"),
26922698
staticlib_allow_rdylib_deps: bool = (false, parse_bool, [TRACKED],
26932699
"allow staticlibs to have rust dylib dependencies"),

compiler/rustc_session/src/session.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -714,11 +714,12 @@ impl Session {
714714
}
715715

716716
pub fn stack_protector(&self) -> StackProtector {
717-
if self.target.options.supports_stack_protector {
718-
self.opts.unstable_opts.stack_protector
719-
} else {
720-
StackProtector::None
721-
}
717+
// -C stack-protector overwrites -Z stack-protector, default to StackProtector::None
718+
self.opts
719+
.cg
720+
.stack_protector
721+
.or(self.opts.unstable_opts.stack_protector)
722+
.unwrap_or(StackProtector::None)
722723
}
723724

724725
pub fn must_emit_unwind_tables(&self) -> bool {
@@ -1240,10 +1241,10 @@ fn validate_commandline_args_with_session_available(sess: &Session) {
12401241
}
12411242
}
12421243

1243-
if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1244+
if sess.stack_protector() != StackProtector::None {
12441245
if !sess.target.options.supports_stack_protector {
1245-
sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1246-
stack_protector: sess.opts.unstable_opts.stack_protector,
1246+
sess.dcx().emit_err(errors::StackProtectorNotSupportedForTarget {
1247+
stack_protector: sess.stack_protector(),
12471248
target_triple: &sess.opts.target_triple,
12481249
});
12491250
}

src/bootstrap/src/core/builder/cargo.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -952,7 +952,7 @@ impl Builder<'_> {
952952
cargo.env(profile_var("STRIP"), self.config.rust_strip.to_string());
953953

954954
if let Some(stack_protector) = &self.config.rust_stack_protector {
955-
rustflags.arg(&format!("-Zstack-protector={stack_protector}"));
955+
rustflags.arg(&format!("-Cstack-protector={stack_protector}"));
956956
}
957957

958958
let debuginfo_level = match mode {

src/doc/rustc/src/codegen-options/index.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -695,6 +695,34 @@ Note that all three options are supported on Linux and Apple platforms,
695695
Attempting to use an unsupported option requires using the nightly channel
696696
with the `-Z unstable-options` flag.
697697

698+
## stack-protector
699+
700+
The option `-C stack-protector` (currently also supported in the
701+
old style `-Z stack-protector`) controls the generation of
702+
stack-protector canaries.
703+
704+
This flag controls stack smashing protection strategy.
705+
706+
Supported values for this option are:
707+
- `none` (default): Disable stack canary generation
708+
- `basic`: Generate stack canaries in functions that are suspected
709+
to have a high chance of containing stack buffer overflows (deprecated).
710+
- `strong`: Generate stack canaries in all functions, unless the compiler
711+
can prove these functions can't be the source of a stack
712+
buffer overflow (even in the presence of undefined behavior).
713+
714+
This provides the same security guarantees as Clang's
715+
`-fstack-protector=strong`.
716+
717+
The exact rules are unstable and subject to change, but
718+
currently, it generates stack protectors for functions that,
719+
*post-optimization*, contain either arrays (of any size
720+
or type) or address-taken locals.
721+
- `all`: Generate stack canaries in all functions
722+
723+
Stack protectors are not supported on many GPU targets, use of stack
724+
protectors on these targets is an error.
725+
698726
## strip
699727

700728
The option `-C strip=val` controls stripping of debuginfo and similar auxiliary

src/doc/rustc/src/exploit-mitigations.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ equivalent.
6262
| Stack clashing protection | Yes | Yes | 1.20.0 (2017-08-31) |
6363
| Read-only relocations and immediate binding | Yes | Yes | 1.21.0 (2017-10-12) |
6464
| Heap corruption protection | Yes | Yes | 1.32.0 (2019-01-17) (via operating system default or specified allocator) |
65-
| Stack smashing protection | Yes | No, `-Z stack-protector` | Nightly |
65+
| Stack smashing protection | Yes | No, `-C stack-protector` | ??? |
6666
| Forward-edge control flow protection | Yes | No, `-Z sanitizer=cfi` | Nightly |
6767
| Backward-edge control flow protection (e.g., shadow and safe stack) | Yes | No, `-Z sanitizer=shadow-call-stack,safestack` | Nightly |
6868

tests/assembly-llvm/stack-protector/stack-protector-heuristics-effect-windows-32bit.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
//@ only-windows
44
//@ only-msvc
55
//@ ignore-64bit 64-bit table based SEH has slightly different behaviors than classic SEH
6-
//@ [all] compile-flags: -Z stack-protector=all
7-
//@ [strong] compile-flags: -Z stack-protector=strong
8-
//@ [basic] compile-flags: -Z stack-protector=basic
9-
//@ [none] compile-flags: -Z stack-protector=none
6+
//@ [all] compile-flags: -C stack-protector=all
7+
//@ [strong] compile-flags: -C stack-protector=strong
8+
//@ [basic] compile-flags: -C stack-protector=basic
9+
//@ [none] compile-flags: -C stack-protector=none
1010
//@ compile-flags: -C opt-level=2 -Z merge-functions=disabled -Cpanic=abort -Cdebuginfo=1
1111

1212
#![crate_type = "lib"]

0 commit comments

Comments
 (0)