CVE-2024-23644 (Rust, published 2024-01-24T20:15Z)
Description: value: Trillium is a composable toolkit for building internet applications with async rust. In `trillium-http` prior to 0.3.12 and `trillium-client` prior to 0.5.4, insufficient validation of outbound header values may lead to request splitting or response splitting attacks in scenarios where attackers have sufficient control over headers. This only affects use cases where attackers have control of request headers, and can insert "\r\n" sequences. Specifically, if untrusted and unvalidated input is inserted into header names or values.

Outbound `trillium_http::HeaderValue` and `trillium_http::HeaderName` can be constructed infallibly and were not checked for illegal bytes when sending requests from the client or responses from the server. Thus, if an attacker has sufficient control over header values (or names) in a request or response that they could inject `\r\n` sequences, they could get the client and server out of sync, and then pivot to gain control over other parts of requests or responses. (i.e. exfiltrating data from other requests, SSRF, etc.)

In `trillium-http` versions 0.3.12 and later, if a header name is invalid in server response headers, the specific header and any associated values are omitted from network transmission. Additionally, if a header value is invalid in server response headers, the individual header value is omitted from network transmission. Other headers values with the same header name will still be sent. In `trillium-client` versions 0.5.4 and later, if any header name or header value is invalid in the client request headers, awaiting the client Conn returns an `Error::MalformedHeader` prior to any network access. As a workaround, Trillium services and client applications should sanitize or validate untrusted input that is included in header values and header names. Carriage return, newline, and null characters are not allowed.
Severity: nan (CVSS v3 base score: 8.1)
Weakness: CWE-436 \u2014 Interpretation Conflict
Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state.
Repository: https://github.com/trillium-rs/trillium
Files changed:
client/src/conn.rs
client/tests/unsafe_headers.rs
http/src/conn.rs
http/src/headers/header_name.rs
http/src/headers/header_value.rs
http/src/headers/unknown_header_name.rs
http/tests/unsafe_headers.rs
Commit message: fix(security): handling of unsafe characters in outbound header names and values


Vulnerable code:
        for (header, values) in self.request_headers.iter() {
            for value in values.iter() {
                write!(buf, "{header}: {value}\r\n")?;
    fn write_headers(&mut self, output_buffer: &mut Vec<u8>) -> std::io::Result<()> {
        for (header, values) in &self.response_headers {
            for value in values {
                write!(output_buffer, "{header}: ")?;
                output_buffer.extend_from_slice(value.as_ref());
                write!(output_buffer, "\r\n")?;
use smartcow::SmartCow;
use smartstring::alias::String as SmartString;
use crate::Error;
use HeaderNameInner::{KnownHeader, UnknownHeader};
            UnknownHeader(UnknownHeaderName(smartcow)) => {
                UnknownHeader(UnknownHeaderName(smartcow.into_owned()))
            }
            Err(()) => UnknownHeader(UnknownHeaderName(SmartCow::Owned(s.into()))),
            Err(_e) => UnknownHeader(UnknownHeaderName(SmartCow::Borrowed(s))),
        if s.is_ascii() {
            Ok(Self(match s.parse::<KnownHeaderName>() {
                Ok(known) => KnownHeader(known),
                Err(()) => UnknownHeader(UnknownHeaderName(SmartCow::Owned(SmartString::from(s)))),
            }))

            HeaderValueInner::Utf8(s) => serializer.serialize_str(s),
            HeaderValueInner::Bytes(bytes) => serializer.serialize_bytes(bytes),
            HeaderValueInner::Utf8(s) => Debug::fmt(s, f),
            HeaderValueInner::Bytes(b) => Debug::fmt(&String::from_utf8_lossy(b), f),
            HeaderValueInner::Utf8(utf8) => Some(utf8),
            HeaderValueInner::Bytes(_) => None,
            HeaderValueInner::Utf8(s) => f.write_str(s),
            HeaderValueInner::Bytes(b) => f.write_str(&String::from_utf8_lossy(b)),
            Ok(s) => Self(HeaderValueInner::Utf8(SmartCow::Owned(s.into()))),
            Err(e) => Self(HeaderValueInner::Bytes(e.into_bytes().into())),
        Self(HeaderValueInner::Utf8(SmartCow::from(c)))
            Ok(s) => Self(HeaderValueInner::Utf8(SmartCow::Borrowed(s))),
            Err(_) => Self(HeaderValueInner::Bytes(b.into())),
        Self(HeaderValueInner::Utf8(SmartCow::Owned(s.into())))
        Self(HeaderValueInner::Utf8(SmartCow::Borrowed(s)))
            HeaderValueInner::Utf8(utf8) => utf8.as_bytes(),
            HeaderValueInner::Bytes(b) => b,
use hashbrown::Equivalent;
use smartcow::SmartCow;

use super::{HeaderName, HeaderNameInner::UnknownHeader};

pub(super) struct UnknownHeaderName<'a>(pub(super) SmartCow<'a>);

Fixed code:
        for (name, values) in &self.request_headers {
            if !name.is_valid() {
                return Err(Error::MalformedHeader(name.to_string().into()));
            }

            for value in values {
                if !value.is_valid() {
                    return Err(Error::MalformedHeader(
                        format!("value for {name}: {value:?}").into(),
                    ));
                }
                write!(buf, "{name}: ")?;
                buf.extend_from_slice(value.as_ref());
                write!(buf, "\r\n")?;
use test_harness::test;
use trillium_client::{Client, KnownHeaderName};
use trillium_testing::{connector, harness};

#[test(harness)]
async fn bad_characters_in_header_value() {
    assert!(Client::new(connector(()))
        .get("http://example.com")
        .with_header(
            KnownHeaderName::Referer,
            "x\r\nConnection: keep-alive\r\n\r\nGET / HTTP/1.1\r\nHost: example.com\r\n\r\n"
        )
        .await
        .is_err());
}

#[test(harness)]
async fn bad_characters_in_header_name() {
    assert!(Client::new(connector(()))
        .get("http://example.com")
        .with_header("dnt: 1\r\nConnection", "keep-alive")
        .await
        .is_err());
}
    fn write_headers(&mut self, output_buffer: &mut Vec<u8>) -> Result<()> {
        for (name, values) in &self.response_headers {
            if name.is_valid() {
                for value in values {
                    if value.is_valid() {
                        write!(output_buffer, "{name}: ")?;
                        output_buffer.extend_from_slice(value.as_ref());
                        write!(output_buffer, "\r\n")?;
                    } else {
                        log::error!("skipping invalid header value {value:?} for header {name}");
                    }
                }
            } else {
                log::error!("skipping invalid header with name {name:?}");
use crate::Error;
use HeaderNameInner::{KnownHeader, UnknownHeader};
            UnknownHeader(uhn) => UnknownHeader(uhn.into_owned()),

    /// Determine if this header name contains only the appropriate characters
    pub fn is_valid(&self) -> bool {
        match &self.0 {
            KnownHeader(_) => true,
            UnknownHeader(uh) => uh.is_valid(),
        }
    }
            Err(()) => UnknownHeader(UnknownHeaderName::from(s)),
            Err(_e) => UnknownHeader(UnknownHeaderName::from(s)),
        if let Ok(known) = s.parse::<KnownHeaderName>() {
            return Ok(known.into());
        }
        let uhn = UnknownHeaderName::from(s.to_string());
        if uhn.is_valid() {
            Ok(uhn.into())
use HeaderValueInner::{Bytes, Utf8};
impl HeaderValue {
    /// determine if this header contains no unsafe characters (\r, \n, \0)
    pub fn is_valid(&self) -> bool {
        memchr::memchr3(b'\r', b'\n', 0, self.as_ref()).is_none()
    }
}

            Utf8(s) => serializer.serialize_str(s),
            Bytes(bytes) => serializer.serialize_bytes(bytes),
            Utf8(s) => Debug::fmt(s, f),
            Bytes(b) => Debug::fmt(&String::from_utf8_lossy(b), f),
            Utf8(utf8) => Some(utf8),
            Bytes(_) => None,
            Utf8(s) => f.write_str(s),
            Bytes(b) => f.write_str(&String::from_utf8_lossy(b)),
            Ok(s) => Self(Utf8(SmartCow::Owned(s.into()))),
            Err(e) => Self(Bytes(e.into_bytes().into())),
        Self(Utf8(SmartCow::from(c)))
            Ok(s) => Self(Utf8(SmartCow::Borrowed(s))),
            Err(_) => Self(Bytes(b.into())),
        Self(Utf8(SmartCow::Owned(s.into())))
        Self(Utf8(SmartCow::Borrowed(s)))
            Utf8(utf8) => utf8.as_bytes(),
            Bytes(b) => b,
use super::{HeaderName, HeaderNameInner::UnknownHeader};
use hashbrown::Equivalent;
use smartcow::SmartCow;
pub(super) struct UnknownHeaderName<'a>(SmartCow<'a>);
impl UnknownHeaderName<'_> {
    pub(crate) fn is_valid(&self) -> bool {
        self.0
            .chars()
            .all(|c| matches!(c, 'a'..='z'|'A'..='Z'|'0'..='9'|'-'|'_'))
    }

    pub(crate) fn into_owned(self) -> UnknownHeaderName<'static> {
        UnknownHeaderName(self.0.into_owned())
    }
}

impl From<String> for UnknownHeaderName<'static> {
    fn from(value: String) -> Self {
        Self(value.into())
    }
}

impl<'a> From<&'a str> for UnknownHeaderName<'a> {
    fn from(value: &'a str) -> Self {
        Self(value.into())
    }
}

use indoc::{formatdoc, indoc};
use pretty_assertions::assert_eq;
use stopper::Stopper;
use test_harness::test;
use trillium_http::{Conn, KnownHeaderName, SERVER};
use trillium_testing::{harness, TestResult, TestTransport};

const TEST_DATE: &str = "Tue, 21 Nov 2023 21:27:21 GMT";

async fn handler(mut conn: Conn<TestTransport>) -> Conn<TestTransport> {
    conn.set_status(200);
    conn.set_response_body("response: 0123456789");
    conn.response_headers_mut()
        .insert(KnownHeaderName::Date, TEST_DATE);
    conn.response_headers_mut().insert(
        KnownHeaderName::Connection,
        "close\r\nGET / HTTP/1.1\r\nHost: example.com\r\n\r\n",
    );
    conn.response_headers_mut().insert("Bad\r\nHeader", "true");
    conn
}

#[test(harness)]
async fn bad_headers() -> TestResult {
    let (client, server) = TestTransport::new();

    trillium_testing::spawn(async move {
        Conn::map(server, Stopper::new(), handler).await.unwrap();
    });

    client.write_all(indoc! {"
        GET / HTTP/1.1\r
        Host: example.com\r
        \r
    "});

    let expected_response = formatdoc! {"
        HTTP/1.1 200 OK\r
        Server: {SERVER}\r
        Date: {TEST_DATE}\r
        Content-Length: 20\r
        \r
        response: 0123456789\
    "};

    assert_eq!(client.read_available_string().await, expected_response);

    Ok(())
}