{"id":234531,"date":"2026-11-09T22:24:15","date_gmt":"2026-11-09T22:24:15","guid":{"rendered":"https:\/\/www.europesays.com\/ai\/234531\/"},"modified":"2026-11-09T22:24:15","modified_gmt":"2026-11-09T22:24:15","slug":"forge-lab-uses-agentic-tools-to-identify-memory-safety-issues-in-rust","status":"publish","type":"post","link":"https:\/\/www.europesays.com\/ai\/234531\/","title":{"rendered":"FORGE Lab uses agentic tools to identify memory safety issues in Rust"},"content":{"rendered":"<p>\t\tIn this article<\/p>\n<p class=\"wp-block-paragraph\">Microsoft\u2019s FORGE Lab found several memory safety issues in Rust\u2019s standard library (std and core), including cases where code written entirely in safe Rust can trigger undefined behavior. The research used Hyenas, FORGE\u2019s frontier research version of codename MDASH, an AI-powered vulnerability-scanning system. The findings reveal three recurring patterns of misplaced trust in unsafe code: trusting code not to panic, trusting user-provided implementations to be correct, and trusting the underlying system.<\/p>\n<p class=\"wp-block-paragraph\">Rust\u2019s safety guarantees are precisely what make these findings interesting. Its rich type system and ownership model rule out whole classes of memory-safety issues, but much of the standard library relies on unsafe code underneath its safe APIs. When that code breaks its safety contract, even safe Rust can encounter behavior the language is designed to prevent.<\/p>\n<p class=\"wp-block-paragraph\">Rust\u2019s memory-safety guarantees are increasingly important as the language becomes part of software that billions of people rely on every day. Billions of people are estimated to interact with Rust-based software or operating systems daily, often without knowing it. Microsoft made Rust a <a href=\"https:\/\/rustfoundation.org\/media\/guest-post-rust-is-tier-1-language-at-microsoft\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">Tier-1 internal language<\/a> alongside C++, C#, and TypeScript, GitHub <a href=\"https:\/\/github.blog\/ai-and-ml\/generative-ai\/migrating-the-github-copilot-runtime-to-rust-using-copilot\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">rewrote the Copilot agent runtime in Rust<\/a>, and <a href=\"https:\/\/bun.com\/blog\/bun-in-rust\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">Bun<\/a>, <a href=\"https:\/\/blog.google\/security\/rust-in-android-move-fast-fix-things\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">Android<\/a>, the <a href=\"https:\/\/lwn.net\/Articles\/1050174\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">Linux kernel<\/a>, and <a href=\"https:\/\/blog.cloudflare.com\/20-percent-internet-upgrade\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">Cloudflare<\/a> are moving code to it as well. Much of this software relies on Rust\u2019s foundational libraries, core and std, and the safety guarantees of the APIs they provide. Bugs in those libraries can have consequences well beyond the code where they originate.<\/p>\n<p class=\"wp-block-paragraph\">Unsafe Rust has been a long-running interest for us. Our team includes the people behind <a href=\"https:\/\/dl.acm.org\/doi\/10.1145\/3477132.3483570\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">Rudra<\/a>, a static analyzer that looked for memory-safety bugs across the Rust ecosystem in 2021. We also write many of our own tools in Rust, so its safety is more than a research topic for us. This year, we took a closer look at the standard library to see what kinds of mistakes still show up in its unsafe code today.<\/p>\n<p class=\"wp-block-paragraph\">In this post, we share some of the bugs we reported to the Rust issue tracker. We use them to discuss what Rust does and doesn\u2019t guarantee, why writing correct unsafe Rust is so difficult, and why Rust\u2019s safety model still matters even though its memory safety isn\u2019t perfect.<a href=\"#_msocom_1\">[OW1]<\/a> <a href=\"#_msocom_2\">[YB2]<\/a> <\/p>\n<p>How we found and validated the bugs<\/p>\n<p class=\"wp-block-paragraph\">At <a href=\"https:\/\/www.microsoft.com\/en-us\/security\/blog\/2026\/10\/07\/3-lessons-from-frontier-ai-vulnerability-research\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">Microsoft FORGE Lab<\/a>, we study vulnerabilities in complex software, including the Rust standard library. Our team combines years of experience in vulnerability research with AI-assisted tools that help us investigate code and find bugs that are difficult to uncover through traditional analysis alone.<\/p>\n<p class=\"wp-block-paragraph\">Some of the bugs in this post were found with help from Hyenas, our research version of codename MDASH. Our researchers investigated the underlying code, reproduced the bugs, assessed their potential security impact, and worked with Rust maintainers to report and fix them.<\/p>\n<p class=\"wp-block-paragraph\">This post focuses on soundness bugs in the standard library\u2019s unsafe code. Bugs in the compiler itself, such as miscompilations and holes in the type system, are a different topic that we don\u2019t cover here.<\/p>\n<p class=\"wp-block-paragraph\">At publication, two of the issues reported by our team remain open. The article also references related issues reported by others and fixes that are still under review. The Rust maintainers triaged and responded to our reports quickly, and we believe maintainers and the contributors working on these issues are doing their best and making the right tradeoffs among the many bugs they handle.<\/p>\n<p class=\"wp-block-paragraph\">If you\u2019re interested in an open issue, please comment only when you have something genuinely new to contribute, such as new information or an affected real-world use case.<\/p>\n<p class=\"wp-block-paragraph\">At the lowest level, Rust uses <a href=\"https:\/\/doc.rust-lang.org\/book\/ch20-01-unsafe-rust.html\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">unsafe blocks<\/a> to work with raw pointers and interact directly with the operating system. Much of the standard library, including Vec and String, is built from small unsafe pieces wrapped in safe APIs. Inside an unsafe block, the programmer takes responsibility for the guarantees the compiler can\u2019t check, and that responsibility extends to the safe API built around it. That API must be <a href=\"https:\/\/doc.rust-lang.org\/nomicon\/safe-unsafe-meaning.html\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">sound<\/a>: no matter how safe code uses it, it must be impossible to trigger undefined behavior.<\/p>\n<p class=\"wp-block-paragraph\">Upholding that promise is harder than it looks. Consider a function that returns the byte at idx from any type that can be viewed as a byte slice, skipping the redundant bounds check after doing its own:<a id=\"_msocom_1\"\/><\/p>\n<p>pub fn get&gt;(s: &amp;S, idx: usize) -&gt; Option {<br \/>\n    if idx &lt; s.as_ref().len() {<br \/>\n        \/\/ SAFETY: we just checked that `idx` is in bounds.<br \/>\n        Some(unsafe { *s.as_ref().get_unchecked(idx) })<br \/>\n    } else {<br \/>\n        None<br \/>\n    }<br \/>\n}<\/p>\n<p class=\"wp-block-paragraph\">The hard part of unsafe Rust is knowing what you can trust. The function above looks correct, but it assumes that two calls to as_ref return the same slice. Because S is chosen by the caller, a safe AsRef implementation can return a long slice the first time and an empty one the second, and get reads out of bounds. Unsafe code must be careful with every call it makes, and the bugs we found fall into three patterns of misplaced trust: trusting code not to panic, trusting user-provided implementations to be correct, and trusting the underlying system.<\/p>\n<p>Pattern 1: Trusting code not to panic<\/p>\n<p class=\"wp-block-paragraph\">Unsafe code often breaks an invariant for a moment and restores it afterward; for example, it may allocate an uninitialized buffer and fill it directly, avoiding redundant writes to zero the memory first. That\u2019s fine as long as the function runs to the end. But many operations in Rust can panic, from out-of-bounds indexing to calls into user-provided code, and by default a panic unwinds: it leaves the function early while still running destructors. Unwinding inside that window becomes an invisible exit that exposes the broken invariant to code that trusts it. Bugs of this kind are called panic safety bugs.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.europesays.com\/ai\/wp-content\/uploads\/2026\/11\/image-17.webp\" alt=\"\" class=\"wp-image-150875 webp-format\" style=\"aspect-ratio:1.4649745851146194;width:680px;height:auto\"  data-orig-src=\"https:\/\/www.europesays.com\/ai\/wp-content\/uploads\/2026\/11\/image-17.webp\"\/>Figure 1 \u2014 Panic Safety.<\/p>\n<p>MapWindows::clone (issue #156501)<\/p>\n<p class=\"wp-block-paragraph\">We identified a <a href=\"https:\/\/github.com\/rust-lang\/rust\/issues\/156501\" type=\"link\" id=\"https:\/\/github.com\/rust-lang\/rust\/issues\/156501\" target=\"_blank\" rel=\"noopener noreferrer nofollow\">panic safety issue<\/a> in MapWindows::clone. The nightly API Iterator::map_windows yields overlapping windows of N items. It keeps the current window in a Buffer whose destructor drops the N items starting at start. In Rust 1.97.0, library\/core\/src\/iter\/adapters\/map_windows.rs defines it as:<\/p>\n<p>struct Buffer {<br \/>\n    \/\/ Invariant: `self.buffer[self.start..self.start + N]` is initialized,<br \/>\n    \/\/ with all other elements being uninitialized. This also<br \/>\n    \/\/ implies that `self.start &lt;= N`.<br \/>\n    buffer: [[MaybeUninit; N]; 2],<br \/>\n    start: usize,<br \/>\n}<\/p>\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/github.com\/rust-lang\/rust\/blob\/1.97.0\/library\/core\/src\/iter\/adapters\/map_windows.rs#L195-L203\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">Buffer::clone<\/a>, in the same file, built the new buffer first and filled it afterward:<\/p>\n<p>impl Clone for Buffer {<br \/>\n    fn clone(&amp;self) -&gt; Self {<br \/>\n        let mut buffer = Buffer {<br \/>\n            buffer: [[const { MaybeUninit::uninit() }; N], [const { MaybeUninit::uninit() }; N]],<br \/>\n            start: self.start,<br \/>\n        };<br \/>\n        buffer.as_uninit_array_mut().write(self.as_array_ref().clone());<br \/>\n        buffer<br \/>\n    }<br \/>\n}<\/p>\n<p class=\"wp-block-paragraph\">After buffer is constructed, it breaks its own invariant: its slots are uninitialized, but its destructor is already armed. The self.as_array_ref().clone() call runs the user&#8217;s T::clone before the slots are written. If that call panics, unwinding drops buffer and runs drop_in_place on N uninitialized values. Our proof of concept uses only safe code: an element type whose clone always panics, which causes a crash when the destructor accesses uninitialized memory. The <a href=\"https:\/\/github.com\/rust-lang\/rust\/commit\/4a647a5084fa9100cb506185fa9ee9ed454374ab\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">fix<\/a> holds the new buffer in ManuallyDrop until it is fully written, so unwinding leaks the half-built buffer instead of dropping it.<\/p>\n<p class=\"wp-block-paragraph\">The general lesson is to treat every call to code you don\u2019t control, such as clone, drop, comparisons, closures, and iterator methods, as a possible early exit. Either finish the work that may panic before breaking an invariant, or make the broken state safe to unwind through: hold it in ManuallyDrop, or use a guard whose destructor restores the invariant, like Vec\u2019s internal SetLenOnDrop. The Rustonomicon covers this under <a href=\"https:\/\/doc.rust-lang.org\/nomicon\/exception-safety.html\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">exception safety<\/a>.<\/p>\n<p>Allocators must not unwind<\/p>\n<p class=\"wp-block-paragraph\">The recently stabilized Allocator API shows how hard panic safety is to get right. With std, an allocation failure <a href=\"https:\/\/doc.rust-lang.org\/std\/alloc\/fn.handle_alloc_error.html\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">aborts the process<\/a> by default instead of unwinding, so much of the standard library&#8217;s unsafe code assumes allocation never unwinds. Custom allocators can break that assumption. While the API was being stabilized, we reported <a href=\"https:\/\/github.com\/rust-lang\/rust\/issues\/156490\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">one place in BTreeMap::insert<\/a> that becomes unsound when an allocator unwinds, and others reported more (<a href=\"https:\/\/github.com\/rust-lang\/rust\/issues\/159334\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">#159334<\/a>, <a href=\"https:\/\/github.com\/rust-lang\/rust\/issues\/159368\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">#159368<\/a>, <a href=\"https:\/\/github.com\/rust-lang\/rust\/issues\/159370\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">#159370<\/a>). Fixing them one by one would mean auditing everything that allocates, so the <a href=\"https:\/\/github.com\/rust-lang\/rust\/pull\/156882\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">stabilization<\/a>, shipping in Rust 1.100 on November 12, instead requires implementors never to unwind from the trait&#8217;s methods or from drop. The proposal notes that &#8220;unwinding out of many allocation-related methods was found to be a pervasive source of unsoundness.&#8221;<\/p>\n<p>Pattern 2: Trusting user-provided implementations to be correct<\/p>\n<p class=\"wp-block-paragraph\">Unsafe code often calls into code its caller provides: a comparator, a trait implementation, a closure. That code is safe, but safe doesn\u2019t mean correct, and it can return inconsistent or plainly wrong answers. The question is who is responsible when it does. In C++, it\u2019s the caller. std::sort requires its comparator to be a strict weak ordering, and breaking that rule is undefined behavior. With libstdc++, sorting equal elements with &lt;= reads past the end of the vector:<\/p>\n<p>std::vector v(100, 42);<br \/>\n\/\/ Bug: `&lt;=` is not a strict weak ordering, since cmp(a, a) is true.<br \/>\nstd::sort(v.begin(), v.end(), [](int a, int b) { return a &lt;= b; });<br \/>\n\/\/ AddressSanitizer: heap-buffer-overflow in std::__introsort_loop<\/p>\n<p class=\"wp-block-paragraph\">The same comparator passed to Rust&#8217;s <a href=\"https:\/\/doc.rust-lang.org\/std\/primitive.slice.html#method.sort_by\" rel=\"nofollow noopener\" target=\"_blank\">sort_by<\/a> is only a logic error. The sort may panic or leave the slice in an unspecified order, but it never causes undefined behavior. The responsibility sits with the unsafe code. The comparator is safe code supplied by the caller, so the unsafe code inside the sort must stay sound no matter what it returns. The same goes for every safe trait a user can implement: comparisons can be inconsistent, an ExactSizeIterator can report a length that doesn&#8217;t match the items it yields, and Borrow can return a different value on each call.<\/p>\n<p>str::replace with a custom Pattern (#156491)<\/p>\n<p class=\"wp-block-paragraph\">Another of our bug reports shows how easy this trust is to miss: <a href=\"https:\/\/github.com\/rust-lang\/rust\/issues\/156491\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">str::replace with a custom Pattern can create a non-UTF-8 String<\/a>. String search APIs accept any type that implements the nightly Pattern trait, and a pattern can describe itself through as_utf8_pattern. str::replace uses that description to take a fast path when replacing one ASCII byte with another. In Rust 1.96.0, the fast path in <a href=\"https:\/\/github.com\/rust-lang\/rust\/blob\/1.96.0\/library\/alloc\/src\/str.rs#L268-L278\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">library\/alloc\/src\/str.rs<\/a> looked like this:<\/p>\n<p>pub fn replace(&amp;self, from: P, to: &amp;str) -&gt; String {<br \/>\n    \/\/ Fast path for replacing a single ASCII character with another.<br \/>\n    if let Some(from_byte) = match from.as_utf8_pattern() {<br \/>\n        Some(Utf8Pattern::StringPattern([from_byte])) =&gt; Some(*from_byte),<br \/>\n        Some(Utf8Pattern::CharPattern(c)) =&gt; c.as_ascii().map(|ascii_char| ascii_char.to_u8()),<br \/>\n        _ =&gt; None,<br \/>\n    } {<br \/>\n        if let [to_byte] = to.as_bytes() {<br \/>\n            return unsafe { replace_ascii(self.as_bytes(), from_byte, *to_byte) };<br \/>\n        }<br \/>\n    }<\/p>\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/github.com\/rust-lang\/rust\/blob\/1.96.0\/library\/alloc\/src\/str.rs#L708-L712\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">replace_ascii<\/a>, in the same file, then rewrites the bytes:<\/p>\n<p>unsafe fn replace_ascii(utf8_bytes: &amp;[u8], from: u8, to: u8) -&gt; String {<br \/>\n    let result: Vec = utf8_bytes.iter().map(|b| if *b == from { to } else { *b }).collect();<br \/>\n    \/\/ SAFETY: We replaced ascii with ascii on valid utf8 strings.<br \/>\n    unsafe { String::from_utf8_unchecked(result) }<br \/>\n}<\/p>\n<p class=\"wp-block-paragraph\">The CharPattern branch checks that the character is ASCII, but the StringPattern branch assumes a one-byte string pattern must be ASCII. That holds for &amp;str patterns, but StringPattern stored &amp;[u8], and as_utf8_pattern is a safe method any Pattern can implement. In our proof of concept, a custom pattern reports the single byte 0x80, which only appears inside multibyte UTF-8 sequences:<\/p>\n<p>impl Pattern for NonAsciiBytePattern {<br \/>\n    \/\/ &#8230;<br \/>\n    fn as_utf8_pattern(&amp;self) -&gt; Option&gt; {<br \/>\n        static NEEDLE: [u8; 1] = [0x80];<br \/>\n        Some(Utf8Pattern::StringPattern(&amp;NEEDLE))<br \/>\n    }<br \/>\n}<\/p>\n<p>\/\/ &#8220;\\u{d000}&#8221; is [ed, 80, 80]; the result is [ed, 3f, 3f], which is not UTF-8.<br \/>\nlet corrupted = &#8220;\\u{d000}&#8221;.replace(NonAsciiBytePattern, &#8220;?&#8221;);<\/p>\n<p class=\"wp-block-paragraph\">str::replace rewrites the continuation bytes and returns a String that isn&#8217;t valid UTF-8, and later string operations that rely on UTF-8 reach undefined behavior. The <a href=\"https:\/\/github.com\/rust-lang\/rust\/pull\/156556\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">fix<\/a> changed StringPattern to hold &amp;str instead of &amp;[u8], so the type itself now guarantees UTF-8.<\/p>\n<p class=\"wp-block-paragraph\">When unsafe code depends on a property of a user-provided implementation, don\u2019t take it on faith. Call the implementation once and keep the result, validate what it returns, or encode the property in a type that safe code can\u2019t forge, as this fix did. If none of those work, make the trait unsafe so implementors explicitly promise to uphold it.<\/p>\n<p>More examples<\/p>\n<p class=\"wp-block-paragraph\">join shows how easy it is to fix this kind of bug only partway. In 2020, we reported that it trusted Borrow::borrow to return the same string on each call (<a href=\"https:\/\/rustsec.org\/advisories\/CVE-2020-36323.html\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">CVE-2020-36323<\/a>), and the fix handled strings that shrink between calls. In April 2026, the same function <a href=\"https:\/\/github.com\/rust-lang\/rust\/pull\/155708\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">needed another fix<\/a>: join borrows the first element twice, and if it grows on the second call, the remaining-length calculation underflows into a heap overflow. The earlier fix had never covered that path.<\/p>\n<p class=\"wp-block-paragraph\">Others reported similar problems in the Pattern API this year. A safe Pattern can hand back a valid searcher built for a different string, and consumers such as strip_prefix_of apply its ranges to the original string unchecked, reading out of bounds (<a href=\"https:\/\/github.com\/rust-lang\/rust\/issues\/158265\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">#158265<\/a>). The same problem turned up in split_once (<a href=\"https:\/\/github.com\/rust-lang\/rust\/issues\/165076\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">#165076<\/a>) after a report that the Searcher contract doesn&#8217;t spell out what str::split relies on (<a href=\"https:\/\/github.com\/rust-lang\/rust\/issues\/164904\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">#164904<\/a>). Both bugs are still open.<\/p>\n<p>Pattern 3: Trusting the underlying system<\/p>\n<p class=\"wp-block-paragraph\">The first two patterns stay inside Rust code. The third sits at the boundary with the operating system, where unsafe code trusts process-wide state such as signal stacks, memory mappings, and the environment, which other threads, C libraries, or the kernel can touch at any time. These bugs have been hard to find automatically, because a static analyzer would need to model all of that surrounding behavior. AI agents change the picture: they understand enough about the environment the code runs in to make this area practical to search. We started exploring it and found some interesting bugs.<\/p>\n<p>process::exit and the main thread\u2019s signal stack (#161018)<\/p>\n<p class=\"wp-block-paragraph\">When a thread overflows its stack, Rust prints a clear message and aborts instead of crashing with a bare segmentation fault:<\/p>\n<p>thread &#8216;main&#8217; (3307186) has overflowed its stack<br \/>\nfatal runtime error: stack overflow, aborting<\/p>\n<p class=\"wp-block-paragraph\">This relies on a few pieces of process-wide state. Each thread\u2019s stack ends in a guard page, an inaccessible region just past the stack\u2019s limit: pthread reserves one for every spawned thread, and on Linux the kernel\u2019s own stack guard plays that role for the main thread. Touching it raises SIGSEGV, and Rust registers a handler for that signal. The handler can\u2019t run on the stack that just overflowed, so Rust also gives each thread an alternate signal stack, a small separate mapping with a guard page of its own, which the kernel switches to when it delivers the signal. The handler checks that the faulting address is inside the guard page, prints the message, and aborts.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.europesays.com\/ai\/wp-content\/uploads\/2026\/11\/image-18.webp\" alt=\"\" class=\"wp-image-150876 webp-format\"  data-orig-src=\"https:\/\/www.europesays.com\/ai\/wp-content\/uploads\/2026\/11\/image-18.webp\"\/>Figure 2 \u2014 Stack Overflow.<\/p>\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/github.com\/rust-lang\/rust\/issues\/161018\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">We found<\/a> that calling process::exit from a child thread tears down the main thread\u2019s alternate stack while the main thread is still running. process::exit runs the runtime\u2019s cleanup before calling libc\u2019s exit, and in Rust 1.98.0 that cleanup ends in <a href=\"https:\/\/github.com\/rust-lang\/rust\/blob\/1.98.0\/library\/std\/src\/sys\/pal\/unix\/stack_overflow.rs#L196-L203\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">library\/std\/src\/sys\/pal\/unix\/stack_overflow.rs<\/a>:<\/p>\n<p>pub unsafe fn cleanup() {<br \/>\n    if cfg!(panic = &#8220;immediate-abort&#8221;) {<br \/>\n        return;<br \/>\n    }<br \/>\n    \/\/ FIXME: I probably cause more bugs than I&#8217;m worth!<br \/>\n    \/\/ see https:\/\/github.com\/rust-lang\/rust\/issues\/111272<br \/>\n    unsafe { drop_handler(MAIN_ALTSTACK.load(Ordering::Relaxed)) };<br \/>\n}<\/p>\n<p class=\"wp-block-paragraph\">The cleanup function passes MAIN_ALTSTACK, the main thread\u2019s alternate stack, to <a href=\"https:\/\/github.com\/rust-lang\/rust\/blob\/1.98.0\/library\/std\/src\/sys\/pal\/unix\/stack_overflow.rs#L297-L301\" type=\"link\" id=\"https:\/\/github.com\/rust-lang\/rust\/blob\/1.98.0\/library\/std\/src\/sys\/pal\/unix\/stack_overflow.rs#L297-L301\" target=\"_blank\" rel=\"noopener noreferrer nofollow\">drop_handler<\/a>:<\/p>\n<p>\/\/ SAFETY: we warned the caller this disables the alternate signal stack!<br \/>\nunsafe { sigaltstack(&amp;disabling_stack, ptr::null_mut()) };<br \/>\n\/\/ SAFETY: We know from `get_stackp` that the alternate stack we installed is part of<br \/>\n\/\/ a mapping that started one page earlier, so walk back a page and unmap from there.<br \/>\nunsafe { munmap(data.sub(page_size), sigstack_size + page_size) };<\/p>\n<p class=\"wp-block-paragraph\">The call to sigaltstack disables the alternate stack of the calling thread, but the subsequent call to munmap unmaps the main thread\u2019s. The code assumes it runs on the main thread, which isn\u2019t true when a child thread calls process::exit. The main thread keeps running until libc\u2019s exit finishes, with its signal stack registration still pointing at unmapped memory. If it overflows its stack in that window, the kernel can\u2019t deliver the signal, and our proof of concept dies with a plain segmentation fault instead of Rust\u2019s message. The bug dates back to <a href=\"https:\/\/github.com\/rust-lang\/rust\/pull\/28069\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">2015<\/a>, and the <a href=\"https:\/\/github.com\/rust-lang\/rust\/pull\/161037\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">fix<\/a> stops cleaning up the main thread\u2019s alternate stack altogether.<\/p>\n<p class=\"wp-block-paragraph\">We also checked whether this could become a security issue. In theory, it could lead to code execution: if a writable mapping landed at the old alternate stack\u2019s address, the kernel would deliver the main thread\u2019s next signal onto it, and another thread could overwrite the handler\u2019s frame, such as its return address, while it runs. In practice, the conditions are very tight. Everything has to happen in the brief window before libc\u2019s exit finishes, the new mapping must have exactly the right size to reuse that address, and overwriting the frame takes a second race inside a short handler. For issue #161018, our testing found no reliable exploitation path under the conditions examined, and we assessed practical exploitation as unlikely. This assessment does not automatically apply to the other issues discussed. The <a href=\"https:\/\/github.com\/rust-lang\/rust\/issues\/161018\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">issue<\/a> has more details in its security impact analysis.<\/p>\n<p>CommandExt::exec and the global environment (#156951)<\/p>\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/github.com\/rust-lang\/rust\/issues\/156951\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">Our other report<\/a> involves the process environment. On Unix, CommandExt::exec replaces the current process with a new program. When the command has its own environment variables, exec points the process-global environ at a new array, calls execvp, and restores environ if execvp fails. In Rust 1.99.0, Command::exec takes the environment lock in <a href=\"https:\/\/github.com\/rust-lang\/rust\/blob\/1.99.0\/library\/std\/src\/sys\/process\/unix\/unix.rs#L242-L244\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">library\/std\/src\/sys\/process\/unix\/unix.rs<\/a>:<\/p>\n<p>let _lock = sys::env::env_read_lock();<\/p>\n<p>let Err(e) = self.do_exec(theirs, envp.as_ref());<\/p>\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/github.com\/rust-lang\/rust\/blob\/1.99.0\/library\/std\/src\/sys\/process\/unix\/unix.rs#L409-L414\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">Command::do_exec<\/a>, in the same file, then swaps the environment:<\/p>\n<p>    _reset = Some(Reset(*sys::env::environ()));<br \/>\n    *sys::env::environ() = envp.as_ptr();<br \/>\n}<\/p>\n<p>libc::execvp(self.get_program_cstr().as_ptr(), self.get_argv().as_ptr());<br \/>\nErr(io::Error::last_os_error())<\/p>\n<p class=\"wp-block-paragraph\">Command::exec takes only the read side of the environment lock, yet do_exec writes the process-global environ. Before the write, do_exec saves the old value so it can be restored if execvp fails. Writing environ under a read lock lets other threads in. A thread calling env::var takes the same read lock and can see variables meant only for the new program, and two failed exec calls racing each other can leave environ pointing at a freed array that a later env::vars_os() reads. Both proofs of concept use only safe Rust. A <a href=\"https:\/\/github.com\/rust-lang\/rust\/pull\/55939\" target=\"_blank\" rel=\"noopener noreferrer nofollow\">2018 fix<\/a> held an exclusive lock here, but when the environment lock became a <a href=\"https:\/\/github.com\/rust-lang\/rust\/pull\/81850\" target=\"_blank\" rel=\"noopener noreferrer nofollow\">read-write lock<\/a> in 2021, exec kept the read side. A fix that avoids touching environ by calling execve directly is <a href=\"https:\/\/github.com\/rust-lang\/rust\/pull\/157144\" target=\"_blank\" rel=\"noopener noreferrer nofollow\">in review<\/a>.<\/p>\n<p class=\"wp-block-paragraph\">The environment has caused trouble before. After a <a href=\"https:\/\/github.com\/rust-lang\/rust\/issues\/27970\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">discussion that began in 2015<\/a>, the 2024 edition <a href=\"https:\/\/doc.rust-lang.org\/edition-guide\/rust-2024\/newly-unsafe-functions.html\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">marked env::set_var as unsafe<\/a>, because C functions on most Unix platforms read the environment without going through Rust&#8217;s lock.<\/p>\n<p>process::exit and thread-local destructors (#164243)<\/p>\n<p class=\"wp-block-paragraph\">Getting this boundary right is hard, and more problems are still open. While exploring this area, we independently ran into a double free in safe code that process::exit can cause through thread-local destructors. It was reported by someone else (<a href=\"https:\/\/github.com\/rust-lang\/rust\/issues\/164243\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">#164243<\/a>), but it\u2019s worth mentioning here. libc\u2019s exit first runs the calling thread\u2019s thread-local destructors, as C++ requires, and Rust registers its destructors the same way. If a destructor calls process::exit while a thread local is being replaced, libc drops that thread local a second time. A <a href=\"https:\/\/github.com\/rust-lang\/rust\/pull\/165125\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">proposed fix<\/a> switches process::exit to POSIX _exit, which ends the process without running these handlers.<\/p>\n<p>Why Rust still matters and advancing vulnerability discovery with AI<\/p>\n<p class=\"wp-block-paragraph\">Every unsafe block rests on assumptions about the code around it. The bugs in this post came from three kinds of misplaced trust:<\/p>\n<p>that code won&#8217;t panic at the wrong moment,<\/p>\n<p>that a caller-provided implementation behaves correctly, and<\/p>\n<p>that the process-wide state Rust shares with the operating system and the C library stays the way the code expects.<\/p>\n<p>Familiar patterns are still difficult (Patterns 1 and 2)<\/p>\n<p class=\"wp-block-paragraph\">The first two patterns are well studied. <a href=\"https:\/\/dl.acm.org\/doi\/10.1145\/3477132.3483570\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">Rudra<\/a> looked for both in 2021, and the standard library was already fixing panic safety bugs in 2015 (<a href=\"https:\/\/rustsec.org\/advisories\/CVE-2015-20001.html\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">CVE-2015-20001<\/a>). They remain challenging to avoid because any call inside unsafe code might unwind or run code the caller supplied.<\/p>\n<p class=\"wp-block-paragraph\">What we saw this year was mixed. On the positive side, the nightly process is working. Many reports were caught while the affected APIs were still unstable, and several were fixed by changing the design before stabilization. StringPattern now <a href=\"https:\/\/github.com\/rust-lang\/rust\/pull\/156556\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">holds &amp;str instead of &amp;[u8]<\/a>, and Allocator was <a href=\"https:\/\/github.com\/rust-lang\/rust\/pull\/156882\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">stabilized<\/a> with a rule that implementors must not unwind. At the same time, bugs in these patterns still reach stable releases, and their fixes aren&#8217;t always complete. join was fixed in 2020 and <a href=\"https:\/\/github.com\/rust-lang\/rust\/pull\/155708\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">needed another fix<\/a> in 2026 for a path the first fix had missed.<\/p>\n<p>System boundary bugs are now within reach (Pattern 3)<\/p>\n<p class=\"wp-block-paragraph\">The third pattern is different. Its bugs live where Rust meets the layers below it: the kernel, through system calls such as sigaltstack and munmap, and the C library, through process-wide state such as environ and the cleanup that libc&#8217;s exit runs. Getting them right takes knowledge that lives outside Rust&#8217;s type system, which has made these bugs difficult to find with traditional static analysis. That may also be why they last so long. The process::exit signal stack bug was in the standard library for nearly 11 years, and exec has written environ under a read lock since 2021. Unlike our reports in the first two patterns, both affect stable Rust.<\/p>\n<p class=\"wp-block-paragraph\">Language models already know a great deal about how these interfaces behave, so agentic scanners can check unsafe code against the system it runs on, not just the language. We think this boundary is one of the most promising places for agentic security research, in Rust and beyond.<\/p>\n<p>Rust&#8217;s high bar is hard to meet but worth keeping<\/p>\n<p class=\"wp-block-paragraph\">Rust holds its safe APIs to a stricter standard than C and C++. Safe code must never be able to cause undefined behavior, no matter how it uses an API. In C++, a comparator that breaks std::sort&#8217;s ordering requirement causes undefined behavior, while Rust&#8217;s sort must stay memory-safe with any Ord implementation. POSIX doesn&#8217;t guarantee that setenv is safe to call while another thread reads the environment. That makes memory safety bugs in Rust hard to compare one-to-one with bugs in other languages.<\/p>\n<p class=\"wp-block-paragraph\">For the same reason, a soundness bug in the standard library isn&#8217;t automatically a vulnerability in the programs that use it. Each bug in this post needs an unusual setup to trigger, such as a panic at exactly the wrong moment, a deliberately misbehaving implementation, or calling process::exit from a child thread. It becomes a serious vulnerability only if a real program reaches the API in that way.<\/p>\n<p class=\"wp-block-paragraph\">Rust&#8217;s safety standard is strict and difficult to meet, but it&#8217;s also useful. It gives an unambiguous answer to what counts as a soundness bug, so problems can be fixed and prevented once in the library, instead of in every program that uses it. Rust&#8217;s safety model strikes the right balance between control, safety, and performance for systems programming, which is why so many projects choose it.<\/p>\n<p class=\"wp-block-paragraph\">At Microsoft FORGE Lab, we&#8217;re exploring how technology such as codename MDASH can help researchers find bugs like the ones in this post at greater scale. Rust&#8217;s standard library is one of several foundational open source projects where we&#8217;re applying this approach.<\/p>\n<p class=\"wp-block-paragraph\">This research also extends beyond the lab. It helps inform the development of codename MDASH, which brings agentic vulnerability discovery into Microsoft Defender. These findings can also serve as inputs to Microsoft Perception, our new multi-agent security system, where specialized agents work together across broader security workflows. For example, the Web App Pen Test Agent can use codename MDASH findings to help prioritize testing, validate exploitability against live applications, and produce actionable vulnerabilities that downstream agents can use to prioritize and support remediation. This connects AI-powered code analysis with real-world security validation and response, helping security teams move from identifying potential vulnerabilities to understanding and addressing actual risk.<\/p>\n<p class=\"wp-block-paragraph\">Our goal isn\u2019t to simply find more bugs, it&#8217;s to identify meaningful issues, turn those findings into actionable research, and improve the safety of foundational software that developers and organizations depend on.<\/p>\n","protected":false},"excerpt":{"rendered":"In this article Microsoft\u2019s FORGE Lab found several memory safety issues in Rust\u2019s standard library (std and core),&hellip;\n","protected":false},"author":2,"featured_media":234532,"comment_status":"","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6],"tags":[179,7493,9878,10718],"class_list":["post-234531","post","type-post","status-publish","format-standard","has-post-thumbnail","category-agentic-ai","tag-agentic-ai","tag-agentic-artificial-intelligence","tag-frontier-ai-models","tag-vulnerability"],"_links":{"self":[{"href":"https:\/\/www.europesays.com\/ai\/wp-json\/wp\/v2\/posts\/234531","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.europesays.com\/ai\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.europesays.com\/ai\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.europesays.com\/ai\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.europesays.com\/ai\/wp-json\/wp\/v2\/comments?post=234531"}],"version-history":[{"count":0,"href":"https:\/\/www.europesays.com\/ai\/wp-json\/wp\/v2\/posts\/234531\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.europesays.com\/ai\/wp-json\/wp\/v2\/media\/234532"}],"wp:attachment":[{"href":"https:\/\/www.europesays.com\/ai\/wp-json\/wp\/v2\/media?parent=234531"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.europesays.com\/ai\/wp-json\/wp\/v2\/categories?post=234531"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.europesays.com\/ai\/wp-json\/wp\/v2\/tags?post=234531"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}