Skip to content

Commit e32c241

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 cf8a955 commit e32c241

23 files changed

+164
-62
lines changed

bootstrap.example.toml

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

729729
# Indicates whether stack protectors should be used
730-
# via the unstable option `-Zstack-protector`.
730+
# via `-Cstack-protector`.
731731
#
732732
# Valid options are : `none`(default),`basic`,`strong`, or `all`.
733733
# `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
@@ -279,19 +279,32 @@ impl CodegenBackend for LlvmCodegenBackend {
279279
Generate stack canaries in all functions.
280280
281281
strong
282-
Generate stack canaries in a function if it either:
283-
- has a local variable of `[T; N]` type, regardless of `T` and `N`
284-
- takes the address of a local variable.
282+
Generate stack canaries for all functions, unless the compiler
283+
can prove these functions can't be the source of a stack
284+
buffer overflow (even in the presence of undefined behavior).
285285
286-
(Note that a local variable being borrowed is not equivalent to its
287-
address being taken: e.g. some borrows may be removed by optimization,
288-
while by-value argument passing may be implemented with reference to a
289-
local stack variable in the ABI.)
286+
This provides the same security guarantees as Clang's
287+
`-fstack-protector=strong`.
288+
289+
The exact rules are unstable and subject to change, but
290+
currently, it generates stack protectors for functions that,
291+
*post-optimization*, contain either arrays (of any size
292+
or type) or address-taken locals.
290293
291294
basic
292-
Generate stack canaries in functions with local variables of `[T; N]`
295+
Generate stack canaries in functions that are heuristically
296+
suspected to contain buffer overflows.
297+
298+
The heuristic is subject to change, but currently it
299+
includes functions with local variables of `[T; N]`
293300
type, where `T` is byte-sized and `N` >= 8.
294301
302+
This heuristic originated from C, where it detects
303+
functions that allocate a `char buf[N];` buffer on the
304+
stack, and are therefore likely to have a stack buffer overflow
305+
in the case of a length-calculation error. It is *not* a good
306+
heuristic for Rust code.
307+
295308
none
296309
Do not generate stack canaries.
297310
"#

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"));
@@ -872,7 +873,6 @@ fn test_unstable_options_tracking_hash() {
872873
tracked!(small_data_threshold, Some(16));
873874
tracked!(split_lto_unit, Some(true));
874875
tracked!(src_hash_algorithm, Some(SourceFileHashAlgorithm::Sha1));
875-
tracked!(stack_protector, StackProtector::All);
876876
tracked!(teach, true);
877877
tracked!(thinlto, Some(true));
878878
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
@@ -129,7 +129,7 @@ session_target_requires_unwind_tables = target requires unwind tables, they cann
129129
130130
session_target_small_data_threshold_not_supported = `-Z small-data-threshold` is not supported for target {$target_triple} and will be ignored
131131
132-
session_target_stack_protector_not_supported = `-Z stack-protector={$stack_protector}` is not supported for target {$target_triple} and will be ignored
132+
session_target_stack_protector_not_supported = `-C stack-protector={$stack_protector}` is not supported for target {$target_triple}
133133
134134
session_unexpected_builtin_cfg = unexpected `--cfg {$cfg}` flag
135135
.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
@@ -1899,9 +1899,12 @@ pub mod parse {
18991899
true
19001900
}
19011901

1902-
pub(crate) fn parse_stack_protector(slot: &mut StackProtector, v: Option<&str>) -> bool {
1902+
pub(crate) fn parse_stack_protector(
1903+
slot: &mut Option<StackProtector>,
1904+
v: Option<&str>,
1905+
) -> bool {
19031906
match v.and_then(|s| StackProtector::from_str(s).ok()) {
1904-
Some(ssp) => *slot = ssp,
1907+
Some(ssp) => *slot = Some(ssp),
19051908
_ => return false,
19061909
}
19071910
true
@@ -2193,6 +2196,9 @@ options! {
21932196
#[rustc_lint_opt_deny_field_access("use `Session::split_debuginfo` instead of this field")]
21942197
split_debuginfo: Option<SplitDebuginfo> = (None, parse_split_debuginfo, [TRACKED],
21952198
"how to handle split-debuginfo, a platform-specific option"),
2199+
#[rustc_lint_opt_deny_field_access("use `Session::stack_protector` instead of this field")]
2200+
stack_protector: Option<StackProtector> = (None, parse_stack_protector, [TRACKED],
2201+
"control stack smash protection strategy (`rustc --print stack-protector-strategies` for details)"),
21962202
strip: Strip = (Strip::None, parse_strip, [UNTRACKED],
21972203
"tell the linker which information to strip (`none` (default), `debuginfo` or `symbols`)"),
21982204
symbol_mangling_version: Option<SymbolManglingVersion> = (None,
@@ -2671,7 +2677,7 @@ written to standard error output)"),
26712677
src_hash_algorithm: Option<SourceFileHashAlgorithm> = (None, parse_src_file_hash, [TRACKED],
26722678
"hash algorithm of source files in debug info (`md5`, `sha1`, or `sha256`)"),
26732679
#[rustc_lint_opt_deny_field_access("use `Session::stack_protector` instead of this field")]
2674-
stack_protector: StackProtector = (StackProtector::None, parse_stack_protector, [TRACKED],
2680+
stack_protector: Option<StackProtector> = (None, parse_stack_protector, [TRACKED],
26752681
"control stack smash protection strategy (`rustc --print stack-protector-strategies` for details)"),
26762682
staticlib_allow_rdylib_deps: bool = (false, parse_bool, [TRACKED],
26772683
"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
@@ -728,11 +728,12 @@ impl Session {
728728
}
729729

730730
pub fn stack_protector(&self) -> StackProtector {
731-
if self.target.options.supports_stack_protector {
732-
self.opts.unstable_opts.stack_protector
733-
} else {
734-
StackProtector::None
735-
}
731+
// -C stack-protector overwrites -Z stack-protector, default to StackProtector::None
732+
self.opts
733+
.cg
734+
.stack_protector
735+
.or(self.opts.unstable_opts.stack_protector)
736+
.unwrap_or(StackProtector::None)
736737
}
737738

738739
pub fn must_emit_unwind_tables(&self) -> bool {
@@ -1283,10 +1284,10 @@ fn validate_commandline_args_with_session_available(sess: &Session) {
12831284
}
12841285
}
12851286

1286-
if sess.opts.unstable_opts.stack_protector != StackProtector::None {
1287+
if sess.stack_protector() != StackProtector::None {
12871288
if !sess.target.options.supports_stack_protector {
1288-
sess.dcx().emit_warn(errors::StackProtectorNotSupportedForTarget {
1289-
stack_protector: sess.opts.unstable_opts.stack_protector,
1289+
sess.dcx().emit_err(errors::StackProtectorNotSupportedForTarget {
1290+
stack_protector: sess.stack_protector(),
12901291
target_triple: &sess.opts.target_triple,
12911292
});
12921293
}

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

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

942942
if let Some(stack_protector) = &self.config.rust_stack_protector {
943-
rustflags.arg(&format!("-Zstack-protector={stack_protector}"));
943+
rustflags.arg(&format!("-Cstack-protector={stack_protector}"));
944944
}
945945

946946
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
1111

1212
#![crate_type = "lib"]

0 commit comments

Comments
 (0)