CVE-2022-36114: Uncontrolled Resource Consumption (CWE-400)
value: Cargo is a package manager for the rust programming language. It was discovered that Cargo did not limit the amount of data extracted from compressed archives. An attacker could upload to an alternate registry a specially crafted package that extracts way more data than its size (also known as a "zip bomb"), exhausting the disk space on the machine using Cargo to download the package. Note that by design Cargo allows code execution at build time, due to build scripts and procedural macros. The vulnerabilities in this advisory allow performing a subset of the possible damage in a harder to track down way. Your dependencies must still be trusted if you want to be protected from attacks, as it's possible to perform the same attacks with build scripts and procedural macros. The vulnerability is present in all versions of Cargo. Rust 1.64, to be released on September 22nd, will include a fix for it. Since the vulnerability is just a more limited way to accomplish what a malicious build scripts or procedural macros can do, we decided not to publish Rust point releases backporting the security fix. Patch files are available for Rust 1.63.0 are available in the wg-security-response repository for people building their own toolchain. We recommend users of alternate registries to excercise care in which package they download, by only including trusted dependencies in their projects. Please note that even with these vulnerabilities fixed, by design Cargo allows arbitrary code execution at build time thanks to build scripts and procedural macros: a malicious dependency will be able to cause damage regardless of these vulnerabilities. crates.io implemented server-side checks to reject these kinds of packages years ago, and there are no packages on crates.io exploiting these vulnerabilities. crates.io users still need to excercise care in choosing their dependencies though, as the same concerns about build scripts and procedural macros apply here.
CWE description: The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
CVSS v3 base score: 6.5
Published: 2022-09-14T18:15Z
Repository: https://github.com/rust-lang/cargo
Language: Rust
Files changed: src/cargo/sources/registry/mod.rs, src/cargo/util/io.rs, src/cargo/util/mod.rs
Commit date: 2022-09-14 10:54:48 +0200
Commit message: CVE-2022-36114: limit the maximum unpacked size of a crate to 512MB

This gives users of custom registries the same protections, using the
same size limit that crates.io uses.

`LimitErrorReader` code copied from crates.io.

Diff: diff --git a/src/cargo/sources/registry/mod.rs b/src/cargo/sources/registry/mod.rs
index a2863bf78..c9c414e50 100644
--- a/src/cargo/sources/registry/mod.rs
+++ b/src/cargo/sources/registry/mod.rs
@@ -180,11 +180,13 @@ use crate::core::{Package, PackageId, QueryKind, Source, SourceId, Summary};
 use crate::sources::PathSource;
 use crate::util::hex;
 use crate::util::interning::InternedString;
 use crate::util::into_url::IntoUrl;
 use crate::util::network::PollExt;
-use crate::util::{restricted_names, CargoResult, Config, Filesystem, OptVersionReq};
+use crate::util::{
+    restricted_names, CargoResult, Config, Filesystem, LimitErrorReader, OptVersionReq,
+};
 
 const PACKAGE_SOURCE_LOCK: &str = ".cargo-ok";
 pub const CRATES_IO_INDEX: &str = "https://github.com/rust-lang/crates.io-index";
 pub const CRATES_IO_HTTP_INDEX: &str = "sparse+https://index.crates.io/";
 pub const CRATES_IO_REGISTRY: &str = "crates-io";
@@ -192,10 +194,11 @@ pub const CRATES_IO_DOMAIN: &str = "crates.io";
 const CRATE_TEMPLATE: &str = "{crate}";
 const VERSION_TEMPLATE: &str = "{version}";
 const PREFIX_TEMPLATE: &str = "{prefix}";
 const LOWER_PREFIX_TEMPLATE: &str = "{lowerprefix}";
 const CHECKSUM_TEMPLATE: &str = "{sha256-checksum}";
+const MAX_UNPACK_SIZE: u64 = 512 * 1024 * 1024;
 
 /// A "source" for a local (see `local::LocalRegistry`) or remote (see
 /// `remote::RemoteRegistry`) registry.
 ///
 /// This contains common functionality that is shared between the two registry
@@ -613,10 +616,11 @@ impl<'cfg> RegistrySource<'cfg> {
             if meta.len() > 0 {
                 return Ok(unpack_dir.to_path_buf());
             }
         }
         let gz = GzDecoder::new(tarball);
+        let gz = LimitErrorReader::new(gz, MAX_UNPACK_SIZE);
         let mut tar = Archive::new(gz);
         let prefix = unpack_dir.file_name().unwrap();
         let parent = unpack_dir.parent().unwrap();
         for entry in tar.entries()? {
             let mut entry = entry.with_context(|| "failed to iterate over archive")?;
diff --git a/src/cargo/util/io.rs b/src/cargo/util/io.rs
new file mode 100644
index 000000000..f62672db0
--- /dev/null
+++ b/src/cargo/util/io.rs
@@ -0,0 +1,27 @@
+use std::io::{self, Read, Take};
+
+#[derive(Debug)]
+pub struct LimitErrorReader<R> {
+    inner: Take<R>,
+}
+
+impl<R: Read> LimitErrorReader<R> {
+    pub fn new(r: R, limit: u64) -> LimitErrorReader<R> {
+        LimitErrorReader {
+            inner: r.take(limit),
+        }
+    }
+}
+
+impl<R: Read> Read for LimitErrorReader<R> {
+    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+        match self.inner.read(buf) {
+            Ok(0) if self.inner.limit() == 0 => Err(io::Error::new(
+                io::ErrorKind::Other,
+                "maximum limit reached when reading",
+            )),
+            e => e,
+        }
+    }
+}
+
diff --git a/src/cargo/util/mod.rs b/src/cargo/util/mod.rs
index 28f685c20..47bbf37aa 100644
--- a/src/cargo/util/mod.rs
+++ b/src/cargo/util/mod.rs
@@ -12,10 +12,11 @@ pub use self::flock::{FileLock, Filesystem};
 pub use self::graph::Graph;
 pub use self::hasher::StableHasher;
 pub use self::hex::{hash_u64, short_hash, to_hex};
 pub use self::into_url::IntoUrl;
 pub use self::into_url_with_base::IntoUrlWithBase;
+pub(crate) use self::io::LimitErrorReader;
 pub use self::lev_distance::{closest, closest_msg, lev_distance};
 pub use self::lockserver::{LockServer, LockServerClient, LockServerStarted};
 pub use self::progress::{Progress, ProgressStyle};
 pub use self::queue::Queue;
 pub use self::restricted_names::validate_package_name;
@@ -42,10 +43,11 @@ mod hasher;
 pub mod hex;
 pub mod important_paths;
 pub mod interning;
 pub mod into_url;
 mod into_url_with_base;
+mod io;
 pub mod job;
 pub mod lev_distance;
 mod lockserver;
 pub mod machine_message;
 pub mod network;

Vulnerable code: use crate::util::{restricted_names, CargoResult, Config, Filesystem, OptVersionReq};
Fixed code: use crate::util::{
    restricted_names, CargoResult, Config, Filesystem, LimitErrorReader, OptVersionReq,
};
const MAX_UNPACK_SIZE: u64 = 512 * 1024 * 1024;
        let gz = LimitErrorReader::new(gz, MAX_UNPACK_SIZE);
use std::io::{self, Read, Take};

#[derive(Debug)]
pub struct LimitErrorReader<R> {
    inner: Take<R>,
}

impl<R: Read> LimitErrorReader<R> {
    pub fn new(r: R, limit: u64) -> LimitErrorReader<R> {
        LimitErrorReader {
            inner: r.take(limit),
        }
    }
}

impl<R: Read> Read for LimitErrorReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self.inner.read(buf) {
            Ok(0) if self.inner.limit() == 0 => Err(io::Error::new(
                io::ErrorKind::Other,
                "maximum limit reached when reading",
            )),
            e => e,
        }
    }
}

pub(crate) use self::io::LimitErrorReader;
mod io;