CVE-2023-40030 (Rust, published 2023-08-24T23:15Z)
Description: value: Cargo downloads a Rust project’s dependencies and compiles the project. Starting in Rust 1.60.0 and prior to 1.72, Cargo did not escape Cargo feature names when including them in the report generated by `cargo build --timings`. A malicious package included as a dependency may inject nearly arbitrary HTML here, potentially leading to cross-site scripting if the report is subsequently uploaded somewhere. The vulnerability affects users relying on dependencies from git, local paths, or alternative registries. Users who solely depend on crates.io are unaffected.

Rust 1.60.0 introduced `cargo build --timings`, which produces a report of how long the different steps of the build process took. It includes lists of Cargo features for each crate. Prior to Rust 1.72, Cargo feature names were allowed to contain almost any characters (with some exceptions as used by the feature syntax), but it would produce a future incompatibility warning about them since Rust 1.49. crates.io is far more stringent about what it considers a valid feature name and has not allowed such feature names. As the feature names were included unescaped in the timings report, they could be used to inject Javascript into the page, for example with a feature name like `features = ["<img src='' onerror=alert(0)"]`. If this report were subsequently uploaded to a domain that uses credentials, the injected Javascript could access resources from the website visitor.

This issue was fixed in Rust 1.72 by turning the future incompatibility warning into an error. Users should still exercise 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 has server-side checks preventing this attack, 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 remote code execution is allowed by design there as well.
Severity: nan (CVSS v3 base score: 6.1)
Weakness: CWE-79 \u2014 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
Repository: https://github.com/rust-lang/cargo
Files changed:
crates/resolver-tests/src/lib.rs
src/cargo/core/resolver/version_prefs.rs
src/cargo/core/summary.rs
src/cargo/sources/registry/index.rs
src/cargo/util/toml/mod.rs
tests/testsuite/features.rs
Commit message: Convert valid feature name warning to an error.


Vulnerable code:
        config,
        &Config::default().unwrap(),
        &Config::default().unwrap(),
        &Config::default().unwrap(),
    use crate::util::Config;
        let config = Config::default().unwrap();
            &config,
use crate::util::{CargoResult, Config};
        config: &Config,
        let feature_map = build_feature_map(config, pkg_id, features, &dependencies)?;
    config: &Config,
        validate_feature_name(config, pkg_id, feature)?;
fn validate_feature_name(config: &Config, pkg_id: PackageId, name: &str) -> CargoResult<()> {
    const FUTURE: &str = "This was previously accepted but is being phased out; \
        it will become a hard error in a future release.\n\
        For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, \
        and please leave a comment if this will be a problem for your project.";
            config.shell().warn(&format!(
                (most letters or `_` or `0` to `9`)\n\
                {}",
                ch, name, pkg_id, FUTURE
            ))?;
            config.shell().warn(&format!(
                (numbers, `+`, `-`, `_`, `.`, or most letters)\n\
                {}",
                ch, name, pkg_id, FUTURE
            ))?;
        let config = self.config;
            .filter_map(
                move |maybe| match maybe.parse(config, raw_data, source_id) {
                    Ok(summary) => Some(summary),
                    Err(e) => {
                        info!("failed to parse `{}` registry package: {}", name, e);
                        None
                    }
                },
            )
                    let summary = match IndexSummary::parse(config, line, source_id) {
    fn parse(
        &mut self,
        config: &Config,
        raw_data: &[u8],
        source_id: SourceId,
    ) -> CargoResult<&IndexSummary> {
        let summary = IndexSummary::parse(config, &raw_data[start..end], source_id)?;
    fn parse(config: &Config, line: &[u8], source_id: SourceId) -> CargoResult<IndexSummary> {
        let mut summary = Summary::new(config, pkgid, deps, &features, links, rust_version)?;
            config,
fn invalid_feature_names_warning() {
    // Warnings for more restricted feature syntax.
                # Some valid, but unusual names, shouldn't warn.
                "c++17" = []
                "128bit" = []
                "_foo" = []
                "feat-name" = []
                "feat_name" = []
                "foo.bar" = []

                # Invalid names.
                "-foo" = []
                ".foo" = []
                "foo:bar" = []
                "foo?" = []
                "?foo" = []
                "ⒶⒷⒸ" = []
                "a¼" = []
    // Unfortunately the warnings are duplicated due to the Summary being
    // loaded twice (once in the Workspace, and once in PackageRegistry) and
    // Cargo does not have a de-duplication system. This should probably be
    // OK, since I'm not expecting this to affect anyone.
        .with_stderr("\
[WARNING] invalid character `+` in feature `+foo` in package foo v0.1.0 ([ROOT]/foo), the first character must be a Unicode XID start character or digit (most letters or `_` or `0` to `9`)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[WARNING] invalid character `-` in feature `-foo` in package foo v0.1.0 ([ROOT]/foo), the first character must be a Unicode XID start character or digit (most letters or `_` or `0` to `9`)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[WARNING] invalid character `.` in feature `.foo` in package foo v0.1.0 ([ROOT]/foo), the first character must be a Unicode XID start character or digit (most letters or `_` or `0` to `9`)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[WARNING] invalid character `?` in feature `?foo` in package foo v0.1.0 ([ROOT]/foo), the first character must be a Unicode XID start character or digit (most letters or `_` or `0` to `9`)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[WARNING] invalid character `¼` in feature `a¼` in package foo v0.1.0 ([ROOT]/foo), characters must be Unicode XID characters, `+`, or `.` (numbers, `+`, `-`, `_`, `.`, or most letters)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[WARNING] invalid character `:` in feature `foo:bar` in package foo v0.1.0 ([ROOT]/foo), characters must be Unicode XID characters, `+`, or `.` (numbers, `+`, `-`, `_`, `.`, or most letters)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[WARNING] invalid character `?` in feature `foo?` in package foo v0.1.0 ([ROOT]/foo), characters must be Unicode XID characters, `+`, or `.` (numbers, `+`, `-`, `_`, `.`, or most letters)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[WARNING] invalid character `Ⓐ` in feature `ⒶⒷⒸ` in package foo v0.1.0 ([ROOT]/foo), the first character must be a Unicode XID start character or digit (most letters or `_` or `0` to `9`)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[WARNING] invalid character `Ⓑ` in feature `ⒶⒷⒸ` in package foo v0.1.0 ([ROOT]/foo), characters must be Unicode XID characters, `+`, or `.` (numbers, `+`, `-`, `_`, `.`, or most letters)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[WARNING] invalid character `Ⓒ` in feature `ⒶⒷⒸ` in package foo v0.1.0 ([ROOT]/foo), characters must be Unicode XID characters, `+`, or `.` (numbers, `+`, `-`, `_`, `.`, or most letters)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[CHECKING] foo v0.1.0 [..]
[FINISHED] [..]
")
fn invalid_feature_names_error() {

Fixed code:
use crate::util::CargoResult;
        let feature_map = build_feature_map(pkg_id, features, &dependencies)?;
        validate_feature_name(pkg_id, feature)?;
fn validate_feature_name(pkg_id: PackageId, name: &str) -> CargoResult<()> {
            bail!(
                (most letters or `_` or `0` to `9`)",
                ch,
                name,
                pkg_id
            );
            bail!(
                (numbers, `+`, `-`, `_`, `.`, or most letters)",
                ch,
                name,
                pkg_id
            );

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sources::CRATES_IO_INDEX;
    use crate::util::into_url::IntoUrl;

    use crate::core::SourceId;

    #[test]
    fn valid_feature_names() {
        let loc = CRATES_IO_INDEX.into_url().unwrap();
        let source_id = SourceId::for_registry(&loc).unwrap();
        let pkg_id = PackageId::new("foo", "1.0.0", source_id).unwrap();

        assert!(validate_feature_name(pkg_id, "c++17").is_ok());
        assert!(validate_feature_name(pkg_id, "128bit").is_ok());
        assert!(validate_feature_name(pkg_id, "_foo").is_ok());
        assert!(validate_feature_name(pkg_id, "feat-name").is_ok());
        assert!(validate_feature_name(pkg_id, "feat_name").is_ok());
        assert!(validate_feature_name(pkg_id, "foo.bar").is_ok());

        assert!(validate_feature_name(pkg_id, "+foo").is_err());
        assert!(validate_feature_name(pkg_id, "-foo").is_err());
        assert!(validate_feature_name(pkg_id, ".foo").is_err());
        assert!(validate_feature_name(pkg_id, "foo:bar").is_err());
        assert!(validate_feature_name(pkg_id, "foo?").is_err());
        assert!(validate_feature_name(pkg_id, "?foo").is_err());
        assert!(validate_feature_name(pkg_id, "ⒶⒷⒸ").is_err());
        assert!(validate_feature_name(pkg_id, "a¼").is_err());
    }
}
            .filter_map(move |maybe| match maybe.parse(raw_data, source_id) {
                Ok(summary) => Some(summary),
                Err(e) => {
                    info!("failed to parse `{}` registry package: {}", name, e);
                    None
                }
            })
                    let summary = match IndexSummary::parse(line, source_id) {
    fn parse(&mut self, raw_data: &[u8], source_id: SourceId) -> CargoResult<&IndexSummary> {
        let summary = IndexSummary::parse(&raw_data[start..end], source_id)?;
    fn parse(line: &[u8], source_id: SourceId) -> CargoResult<IndexSummary> {
        let mut summary = Summary::new(pkgid, deps, &features, links, rust_version)?;
fn invalid_feature_names_error() {
    // Errors for more restricted feature syntax.
                # Invalid start character.
        .with_status(101)
        .with_stderr(
            "\
error: failed to parse manifest at `[ROOT]/foo/Cargo.toml`

Caused by:
  invalid character `+` in feature `+foo` in package foo v0.1.0 ([ROOT]/foo), \
  the first character must be a Unicode XID start character or digit \
  (most letters or `_` or `0` to `9`)
",
        )
        .run();

    p.change_file(
        "Cargo.toml",
        r#"
            [package]
            name = "foo"
            version = "0.1.0"

            [features]
            # Invalid continue character.
            "a&b" = []
        "#,
    );

    p.cargo("check")
        .with_status(101)
        .with_stderr(
            "\
error: failed to parse manifest at `[ROOT]/foo/Cargo.toml`

Caused by:
  invalid character `&` in feature `a&b` in package foo v0.1.0 ([ROOT]/foo), \
  characters must be Unicode XID characters, `+`, or `.` \
  (numbers, `+`, `-`, `_`, `.`, or most letters)
",
        )
fn invalid_feature_name_slash_error() {