← Effective AI Code Development

Rust Series Part 3: Rust Is Not Immune — Real Security Risks in Rust Code

Rust prevents most memory bugs, but not all vulnerabilities. Unsafe code, C interop, logic flaws and supply-chain attacks explained, with the Linux kernel's first Rust CVE as a case study.

·11 min read·
#Rust#Security#Unsafe Rust#Supply Chain#Type Safety#AI Engineering#AI-SDLC

Rust provides strong memory-safety guarantees, but applications written in Rust can still contain serious security vulnerabilities.

The compiler helps prevent use-after-free errors, invalid memory access, and data races in safe Rust code, provided the unsafe implementations on which that code depends uphold their safety contracts.

However, vulnerabilities can still arise from:

  • Unsafe Rust: Incorrect pointer handling, aliasing, lifetimes, or synchronization.
  • FFI boundaries: Incorrect assumptions when Rust interacts with C/C++ or other external code.
  • Application logic: Authentication flaws, injection, timing leaks, resource exhaustion, and incorrect business rules.
  • Supply-chain threats: Malicious crates, vulnerable dependencies, build scripts, and procedural macros.

A useful real-world example is CVE-2025-68260, a concurrency-related memory corruption vulnerability in the Linux kernel's Rust Binder driver.

The important lesson is that Rust reduces certain vulnerability classes, but secure software still depends on correct implementation and disciplined engineering practices.

Introduction

In Part 2 of this series, we examined why Rust provides substantial memory-safety advantages over C and C++.

We also looked at Google's Android security research and the broader industry movement toward memory-safe programming languages.

But an important question remains.

If Rust prevents memory-safety errors, how can Rust code still contain security vulnerabilities?

The answer lies in understanding the boundaries of the language's guarantees.

Rust's compiler can verify many properties of a program, but it cannot determine whether an application's business rules are correct, whether an external C library honors its contracts, or whether a dependency is malicious.

It also cannot prove the safety of every operation permitted by unsafe.

Let's explore where these risks appear and how they affect real software systems.

1. Understanding Unsafe Rust

Rust has a feature called unsafe that allows developers to perform certain operations the compiler cannot fully verify for memory safety.

This is necessary for some forms of low-level programming.

Examples include:

  • Accessing hardware or memory-mapped devices.
  • Implementing allocators and low-level data structures.
  • Dereferencing raw pointers.
  • Calling unsafe functions.
  • Interacting with operating-system interfaces and foreign libraries.
  • Implementing unsafe traits such as Send and Sync.

However, unsafe does not completely disable Rust's type system or borrow checker.

Normal compiler checks continue to apply.

Instead, unsafe permits specific operations whose safety depends on invariants that the programmer must uphold.

A simple unsafe example

fn main() {
    let number = 42;

    let pointer = &number as *const i32;

    unsafe {
        println!("{}", *pointer);
    }
}

Output:

42

Here, we create a raw pointer and dereference it inside an unsafe block.

The example is valid because the pointer refers to a live, properly aligned integer.

However, Rust cannot generally prove that every raw pointer dereference is valid.

The programmer must ensure the pointer is suitable for the operation.

What can go wrong?

Incorrect unsafe code can introduce familiar memory-safety vulnerabilities.

Use-after-free

A pointer may refer to memory that has already been released.

Dangling pointers

A pointer may no longer refer to a valid object.

Data races

Unsynchronized concurrent access to shared memory can violate Rust's memory-safety requirements.

Invalid aliasing

Multiple references or pointers may be used in ways that violate Rust's aliasing rules.

The important point is that unsafe operations must satisfy their safety requirements even when the compiler cannot verify them.

Unsafe code can affect safe callers

A particularly important concern is that unsafe code can be hidden behind a safe public API.

For example, a library may expose a normal Rust function while internally using raw pointers.

If the internal implementation violates memory-safety invariants, callers can encounter undefined behavior even though they never write an unsafe block themselves.

This is called an unsound abstraction.

Therefore, reviewing unsafe code is not simply about counting how many unsafe blocks exist.

We need to understand the safety contracts and whether they remain valid for every permitted use of the public API.

2. FFI Boundaries: When Rust Interacts with C and C++

Many real-world systems contain code written in multiple programming languages.

Rust may interact with:

  • Existing C libraries.
  • Operating-system APIs.
  • Hardware drivers.
  • Native libraries used by applications.
  • Legacy C++ components.

This interaction is commonly implemented through a Foreign Function Interface, or FFI.

Why is FFI a security concern?

Rust's compiler understands Rust's ownership and borrowing rules.

It does not automatically understand the memory-management contracts of external C or C++ implementations.

Consider a C function that returns a pointer.

Rust needs to know:

  • Who owns the allocated memory?
  • How long will the pointer remain valid?
  • Who is responsible for freeing it?
  • Can another thread modify the underlying object?
  • Can the function return a null pointer?
  • Is the memory properly aligned?
  • Can callbacks occur concurrently?

If these assumptions are incorrect, a safe-looking Rust wrapper can expose invalid memory.

Example of an FFI boundary

use std::ffi::c_char;

unsafe extern "C" {
    fn external_get_message() -> *const c_char;
}

This declaration describes a function implemented outside Rust.

The declaration alone does not establish whether the returned pointer is valid, how long it remains valid, or whether it points to a null-terminated string.

A wrapper must validate and uphold the external function's documented contract before converting the pointer into a safe Rust representation.

This is why FFI boundaries deserve careful review.

They connect Rust's compiler-enforced safety model to external implementations whose behavior may not follow the same rules.

3. Case Study: CVE-2025-68260 in the Linux Kernel

Rust support entered the mainline Linux kernel in version 6.1.

One significant area of development has been Rust-based implementations of low-level kernel components, including Android Binder.

In December 2025, CVE-2025-68260 was published for a race condition in the Rust Binder driver.

The vulnerability illustrates how memory-safety problems can still arise when unsafe-code invariants are incorrect.

What happened?

The affected code manipulated an intrusive linked list used to manage Binder death notifications.

An intrusive linked list stores linkage information inside the objects themselves.

This can be efficient for low-level systems, but it requires careful management of pointer validity and concurrent access.

The vulnerable implementation relied on assumptions about exclusive access to list state.

Under certain concurrent operations, those assumptions did not hold.

As a result, linked-list pointers could become corrupted, potentially leading to memory corruption and kernel crashes.

Why didn't Rust prevent it?

The relevant operations depended on unsafe-code invariants that the compiler could not fully verify.

The compiler could enforce Rust's ordinary language rules, but it could not establish that the concurrency assumptions underlying those unsafe operations were always valid.

This is an important distinction.

The vulnerability does not demonstrate that safe Rust's memory-safety guarantees are ineffective.

It demonstrates that incorrect unsafe implementations can invalidate those guarantees.

What was the impact?

The vulnerability was associated with kernel crashes and memory corruption.

The Linux kernel's security assessment assigned it a high severity rating and recognized potential confidentiality, integrity, and availability impacts.

That does not establish that arbitrary code execution was demonstrated in the public reporting.

We should distinguish between observed behavior, assessed impact, and proven exploitation.

What can developers learn?

There are several practical lessons:

  1. Unsafe-code reviews must consider concurrency and object lifetime together.
  2. Intrusive data structures require carefully documented ownership and synchronization invariants.
  3. Safe APIs must not expose assumptions that their internal implementation cannot guarantee.
  4. Testing must include concurrency scenarios, not only ordinary functional behavior.
  5. Rust's safety advantages remain valuable, but unsafe boundaries require additional engineering discipline.

This case is particularly relevant to systems software, device drivers, embedded programming, and FFI-heavy applications.

4. Logic Vulnerabilities in Safe Rust

A program can be entirely memory-safe and still contain serious security vulnerabilities.

Memory safety is not equivalent to application security.

Let's look at several examples.

A. Timing attacks

Consider comparing two secret values:

fn verify_token(provided: &str, expected: &str) -> bool {
    provided == expected
}

This code is valid safe Rust.

However, ordinary string equality is not guaranteed to run in constant time.

Depending on the implementation and execution environment, comparison timing may reveal information about secret values.

For security-sensitive comparisons, developers should use vetted constant-time primitives.

The subtle crate provides functionality designed for this purpose.

Even then, constant-time comparison is only one part of a secure authentication design.

Token entropy, expiration, storage, transport security, and rate limiting also matter.

B. Denial of service

Consider a service that accepts a user-provided size:

fn allocate_buffer(size: usize) -> Vec<u8> {
    vec![0; size]
}

This is safe Rust.

However, if an attacker controls size, the application may attempt to allocate an excessive amount of memory.

The result could be resource exhaustion or process termination.

Memory safety does not automatically prevent denial-of-service attacks.

A safer design applies explicit resource limits and handles allocation failures where possible.

C. Integer overflow

Consider:

fn calculate_total(price: u32, quantity: u32) -> u32 {
    price * quantity
}

The multiplication may overflow.

In default debug builds, checked arithmetic detects overflow and panics.

In typical release builds with overflow checks disabled, unsigned arithmetic wraps.

Neither behavior guarantees that the result satisfies the application's business requirements.

For critical calculations, use checked arithmetic:

fn calculate_total(
    price: u32,
    quantity: u32,
) -> Option<u32> {
    price.checked_mul(quantity)
}

The caller can now handle overflow explicitly.

D. Web application vulnerabilities

Rust web applications can still suffer from:

  • SQL injection.
  • Cross-site scripting.
  • Server-side request forgery.
  • Broken authentication.
  • Missing authorization checks.
  • CORS misconfiguration.
  • Insecure session management.
  • Sensitive information disclosure.

For example, dynamically concatenating untrusted input into SQL statements can introduce injection vulnerabilities regardless of whether the application is written in Rust.

Using parameterized queries, input validation, authorization checks, and secure application architecture remains necessary.

E. Business-logic vulnerabilities

Imagine a financial application that allows a withdrawal without checking whether sufficient funds are available.

The implementation might compile successfully and be completely memory-safe.

However, the business rule is incorrect.

The compiler cannot determine whether a withdrawal should be allowed.

That responsibility belongs to the application's design, implementation, and testing processes.

5. Supply-Chain Attacks in the Rust Ecosystem

Rust applications commonly depend on third-party packages called crates.

Cargo makes dependency management convenient, but every dependency introduces an additional trust relationship.

Malicious crates

Attackers may publish packages that imitate popular crates or include malicious functionality.

Typosquatting is one example.

A developer intending to install a legitimate package may accidentally select a similarly named malicious crate.

Build-time execution

Rust dependencies can include build scripts and procedural macros.

A build.rs script can execute code during compilation.

Procedural macros also execute code as part of the build process.

This means a malicious dependency may affect a developer workstation or CI environment before the resulting application is executed.

Vulnerable dependencies

A legitimate crate may contain a security vulnerability discovered after it was added to a project.

Even a well-maintained dependency can become vulnerable.

Abandoned dependencies

Some crates stop receiving maintenance or security updates.

This creates additional risks, especially when a project depends on the crate for security-sensitive functionality.

What should developers do?

At a minimum:

  • Review dependencies before adoption.
  • Monitor RustSec security advisories.
  • Use dependency policies and lockfiles.
  • Restrict privileges available to build processes.
  • Avoid exposing long-lived secrets to untrusted builds.
  • Generate and maintain software bills of materials.
  • Establish a process for dependency updates and vulnerability remediation.

Supply-chain security is an engineering process, not something automatically guaranteed by a programming language.

6. Safe Rust vs. Unsafe Rust: Understanding the Risks

AspectSafe RustUnsafe Rust and FFI
Memory safetyGuaranteed when underlying unsafe implementations are soundDepends on manually maintained safety invariants
Data racesPrevented under Rust's soundness assumptionsPossible if unsafe synchronization or trait contracts are incorrect
Logic vulnerabilitiesPossiblePossible
Resource exhaustionPossiblePossible
Injection vulnerabilitiesPossiblePossible
Dangling pointer dereferencePrevented through sound safe abstractionsPossible through invalid raw-pointer operations
Supply-chain threatsPossiblePossible
Main review focusApplication logic, input handling, dependenciesAll applicable risks plus memory invariants and external contracts

This comparison highlights an important point.

Unsafe Rust is not automatically vulnerable, and safe Rust is not automatically secure.

The security outcome depends on what properties the compiler can enforce and what responsibilities remain with developers.

7. What This Means for Software Engineering Teams

When adopting Rust, teams should distinguish between three layers of security.

Language-level safety

Rust helps enforce types, ownership, borrowing, memory safety, and data-race freedom.

Application-level security

Developers must implement correct authentication, authorization, validation, cryptography, resource management, and business rules.

Software supply-chain and operational security

Teams must manage dependencies, CI/CD security, artifact integrity, deployment configuration, observability, and vulnerability response.

All three layers are necessary.

Using Rust improves the first layer substantially for systems software, but it does not replace the other two.

Conclusion

Rust reduces the risk of many memory-safety vulnerabilities, especially those commonly encountered in C and C++ systems.

However, it is not immune to security vulnerabilities.

Unsafe implementations, FFI boundaries, concurrency assumptions, application logic, and dependencies can still introduce serious problems.

CVE-2025-68260 is a useful reminder that memory-safety guarantees depend on the correctness of the unsafe code supporting safe abstractions.

For developers, the lesson is not to avoid Rust or unsafe code entirely.

It is to understand where the compiler's guarantees end and where engineering responsibility begins.

In the next article, we'll turn these risks into a practical security checklist for Rust projects, covering dependency analysis, static checks, fuzzing, unsafe-code testing, and CI/CD integration.

Key Takeaways

  • Safe Rust provides strong memory-safety guarantees when its underlying unsafe implementations are sound.
  • Unsafe Rust does not disable the entire borrow checker; it permits specific operations requiring manual safety guarantees.
  • Incorrect unsafe abstractions can expose vulnerabilities through otherwise safe APIs.
  • FFI boundaries require explicit ownership, lifetime, and synchronization contracts.
  • CVE-2025-68260 demonstrates the consequences of incorrect concurrency invariants in unsafe Rust.
  • Logic errors, denial of service, injection, and timing vulnerabilities remain possible.
  • Dependency and build-time supply-chain risks require independent security controls.

References

  1. Rustonomicon — Meet Safe and Unsafe
  2. Rust Reference — Unsafety
  3. Linux Kernel — CVE-2025-68260 Advisory
  4. Rust Foundation — Unsafe Rust in the Wild
  5. RustSec Advisory Database
  6. Snyk — Rust Vulnerable Applications

Public profile lookup

Ask AI About the Author

Open this query in ChatGPT, Claude, or Perplexity.

Comments

Comments are open to confirmed email subscribers. Use the email you subscribed with. To edit a comment, delete it and post a new one.

0/2000
Verify:

    Subscribe to get the new blogs.

    Field notes from someone who ships before they write about it. Sovereign AI, AI-SDLC, DevOps, and what 59 production deployments teach you. No spam. Unsubscribe anytime.

    More in this series

    1. Part 1
      Rust Series Part 1: Getting Started with Rust — Immutability and Type Safety
    2. Part 2
      Rust Series Part 2: Is Rust Really Safer? What the Data Says

    Related field notes