TExcelTAD

SMTP, POP3, IMAP and STARTTLS

Email was designed in the early 1980s for cooperating universities, and its protocols still show it. SMTP delivers mail between servers and from clients to servers; POP3 and IMAP let clients read it. All three began as cleartext and added encryption later, mostly through STARTTLS: start in plain text, then upgrade the same connection to TLS if both sides agree. "If both sides agree" is the weakness. This lesson runs a STARTTLS upgrade against a tiny lab mail server, shows how an on-path attacker can strip the upgrade, and covers the mechanisms that close the gap, along with the DNS records that protect the sender address. Mail protocols are introduced in Email Protocols.

Ports and modes

Protocol Cleartext / STARTTLS Implicit TLS Role
SMTP (relay between servers) 25 (none in practice) server to server, opportunistic TLS
SMTP submission 587 (STARTTLS) 465 client to its own server, with authentication
POP3 110 (STLS) 995 download mail
IMAP 143 (STARTTLS) 993 read mail on the server

RFC 8314 (2018) recommends implicit TLS (465, 993, 995) for clients: TLS from the first byte, nothing to strip.

A STARTTLS upgrade, for real

The session writes a minimal SMTP server in Python (it only knows EHLO, STARTTLS and QUIT, and uses the lab certificate for lab.test), starts it on 127.0.0.1:2525, and connects with openssl s_client -starttls smtp, which speaks the plaintext part, sends STARTTLS and then performs the TLS handshake. Run once with a server that offers STARTTLS and once with one that doesn't.

bash · try it yourself
cat > smtp_lab.py <<'PY'
import socket, ssl, sys
offer_tls = sys.argv[1] == "tls"
ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ctx.load_cert_chain("/opt/sec-samples/pki/lab.test.crt", "/opt/sec-samples/pki/lab.test.key")
srv = socket.socket(); srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", 2525)); srv.listen(1)
conn, _ = srv.accept(); f = conn.makefile("rwb")
def say(line): f.write(line.encode() + b"\r\n"); f.flush()
say("220 lab.test ESMTP lab-mail")
while True:
    line = f.readline().decode(errors="replace").strip()
    if not line: break
    cmd = line.split()[0].upper()
    if cmd in ("EHLO", "HELO"):
        say("250-lab.test"); say("250-SIZE 10240000"); say("250 STARTTLS" if offer_tls else "250 8BITMIME")
    elif cmd == "STARTTLS" and offer_tls:
        say("220 Ready to start TLS")
        conn = ctx.wrap_socket(conn, server_side=True); f = conn.makefile("rwb")
    elif cmd == "QUIT":
        say("221 Bye"); break
    else:
        say("502 not implemented")
conn.close()
PY
python3 smtp_lab.py tls &
for i in $(seq 50); do ss -Htln 'sport = :2525' | grep -q . && break; sleep 0.1; done
openssl s_client -starttls smtp -connect 127.0.0.1:2525 -servername lab.test -CAfile $SAMPLES/pki/ca.crt -brief </dev/null 2>&1
wait
echo "=== server without STARTTLS (or with the offer stripped):"
python3 smtp_lab.py plain &
for i in $(seq 50); do ss -Htln 'sport = :2525' | grep -q . && break; sleep 0.1; done
openssl s_client -starttls smtp -connect 127.0.0.1:2525 -servername lab.test -CAfile $SAMPLES/pki/ca.crt -brief </dev/null 2>&1 | head -1
kill %1 2>/dev/null; wait 2>/dev/null; echo done
CONNECTION ESTABLISHED
Protocol version: TLSv1.3
Ciphersuite: TLS_AES_256_GCM_SHA384
Peer certificate: C = XX, O = ExcelTAD Lab, OU = Web, CN = lab.test
Hash used: SHA256
Signature type: RSA-PSS
Verification: OK
Server Temp Key: X25519, 253 bits
250 STARTTLS
DONE
=== server without STARTTLS (or with the offer stripped):
Didn't find STARTTLS in server response, trying anyway...
done

The first run upgrades to TLS 1.3 and verifies the lab certificate against the lab CA (Verification: OK). The 250 STARTTLS line is the end of the server's EHLO reply, printed by s_client (it appears late because its standard output is buffered). In the second run the server's EHLO reply has no STARTTLS line, and s_client says so. s_client is a test tool and tries anyway; a mail server configured for opportunistic TLS would simply continue in cleartext.

STARTTLS stripping

Because the offer travels in cleartext, an attacker on the path can delete the 250-STARTTLS line from the server's reply (or answer the client's STARTTLS with an error). The model below compares client policies.

python · try it yourself
def server_ehlo():
    return ["250-lab.test", "250-SIZE 10240000", "250 STARTTLS"]

def mitm(lines, strip):
    if not strip:
        return lines
    kept = [l for l in lines if "STARTTLS" not in l]
    kept[-1] = "250 " + kept[-1][4:]                    # keep the reply well-formed
    return kept

def session(policy, strip):
    offer = any("STARTTLS" in l for l in mitm(server_ehlo(), strip))
    if offer:
        return "TLS"
    if policy == "require":
        return "abort: TLS required but not offered (alert)"
    return "CLEARTEXT: credentials and mail readable"

for policy in ["opportunistic", "require"]:
    for strip in [False, True]:
        print(f"{policy:<14} attacker strips={strip!s:<5} -> {session(policy, strip)}")
opportunistic  attacker strips=False -> TLS
opportunistic  attacker strips=True  -> CLEARTEXT: credentials and mail readable
require        attacker strips=False -> TLS
require        attacker strips=True  -> abort: TLS required but not offered (alert)

Opportunistic TLS between mail servers is the default on the Internet, because a sending server can't know in advance whether a receiver supports TLS. Two standards let a receiving domain say "you must use TLS with a valid certificate":

  • MTA-STS (RFC 8461): a policy file served over HTTPS at mta-sts.<domain>, announced by a _mta-sts TXT record. Senders cache it and refuse to deliver without valid TLS.
  • DANE for SMTP (RFC 7672): TLSA records in a DNSSEC-signed zone pin the server's certificate or key.
  • TLS-RPT (RFC 8460): senders report TLS failures to an address the domain publishes, so stripping attempts become visible.

Who may send for a domain: SPF, DKIM, DMARC

Encryption protects the path; it doesn't stop someone from claiming to be ceo@lab.test. Three DNS-published mechanisms address that:

  • SPF (RFC 7208): a TXT record listing the servers allowed to send mail for the domain.
  • DKIM (RFC 6376): the sending server signs headers and body; the public key is in DNS.
  • DMARC (RFC 9989, May 2026, a Standards Track revision that obsoletes RFC 7489): tells receivers what to do when SPF/DKIM fail for the visible From domain (p=none|quarantine|reject) and where to send reports.

The lab zone publishes an SPF record. The session reads it and the MX record from the lab DNS server, and a short Python check evaluates the policy for two sending addresses:

bash · try it yourself
dnsmasq --conf-file=$SAMPLES/dns/lab.test.conf --pid-file="$PWD/dns.pid"
for i in $(seq 50); do dig @127.0.0.1 -p 5353 +short lab.test >/dev/null 2>&1 && break; sleep 0.1; done
echo "MX:  $(dig @127.0.0.1 -p 5353 +short lab.test MX)"
SPF=$(dig @127.0.0.1 -p 5353 +short lab.test TXT | tr -d '"')
echo "SPF: $SPF"
python3 - "$SPF" <<'PY'
import ipaddress, sys
spf = sys.argv[1].split()
allowed = [ipaddress.ip_network(t[4:]) for t in spf if t.startswith("ip4:")]
default = {"-all": "fail", "~all": "softfail", "?all": "neutral", "+all": "pass"}[spf[-1]]
for sender in ["10.10.0.25", "203.0.113.66"]:
    ok = any(ipaddress.ip_address(sender) in n for n in allowed)
    print(f"mail from {sender:<13} SPF result: {'pass' if ok else default}")
PY
kill "$(cat dns.pid)"
MX:  10 mail.lab.test.
SPF: v=spf1 ip4:10.10.0.25 -all
mail from 10.10.0.25    SPF result: pass
mail from 203.0.113.66  SPF result: fail

How problems are detected

  • Cleartext authentication: AUTH PLAIN/AUTH LOGIN or USER/PASS on 25, 110, 143 in IDS alerts or Zeek's smtp.log/pop3/imap analysers; clients configured for 110/143 without STLS/STARTTLS.
  • Stripping: TLS-RPT reports, and receiving logs that show sessions from servers known to support TLS arriving in cleartext.
  • Spoofing: DMARC aggregate reports (who sends mail claiming your domain), SPF/DKIM failures in received headers.
  • Exposure: scans of your own mail hosts for open relays (accepting mail for any destination from anyone) and for ports that offer authentication before TLS.

How it is fixed

  1. Clients: implicit TLS on 465/993/995, or STARTTLS with "require" and certificate validation; disable cleartext authentication on the server (auth only after TLS).
  2. Server to server: publish MTA-STS (or DANE with DNSSEC) and TLS-RPT; monitor reports.
  3. Sender authentication: SPF ending in -all, DKIM signing, DMARC moving from p=none to p=reject once reports are clean.
  4. No open relay; authenticated submission only on 587/465.

Pitfalls

  • STARTTLS with a client that accepts any certificate: the encryption is real, the authentication isn't, and a man-in-the-middle presents its own certificate.
  • SPF records with +all or ?all, which permit everyone.
  • Forgetting the STARTTLS command-injection class of bugs: commands sent in cleartext right after STARTTLS and buffered by the server were executed as if they came over TLS (first fixed in Postfix in 2011, CVE-2011-0411, and found again in other servers and clients since; a reason to prefer implicit TLS).

Practice

1. Why can't SMTP between arbitrary Internet servers simply require TLS by default?

A sending server doesn't know whether the receiver supports TLS or has a valid certificate, and refusing to deliver would break mail to many domains. MTA-STS and DANE let each receiving domain opt in to "require".

2. A mail arrives from 203.0.113.66 claiming to be from lab.test. What does the receiver conclude with the lab's SPF record?

SPF fail (-all): the address isn't listed. With a DMARC policy of p=reject and no valid DKIM signature from lab.test, the receiver should reject it.

3. Change the model so the attacker answers STARTTLS with 454 TLS not available instead of stripping the offer. Does "require" still protect?

Yes: the client asked for TLS and didn't get it, so a "require" policy aborts; an opportunistic client continues in cleartext. Either way, the policy decides, not the attacker's method.

Test yourself

What is STARTTLS?

  1. A separate TLS port
  2. A command that upgrades an existing plaintext connection to TLS
  3. An email signature
  4. A DNS record type

Why is opportunistic STARTTLS vulnerable to stripping?

  1. TLS 1.3 is weak
  2. The offer is sent in cleartext, so an on-path attacker can remove it and the client continues without TLS
  3. Mail servers have no certificates
  4. SPF disables TLS

Which mechanism lets a receiving domain tell senders that TLS with a valid certificate is mandatory?

  1. SPF
  2. MTA-STS
  3. DKIM
  4. PTR

Which ports does RFC 8314 recommend for mail clients?

  1. 25 and 110
  2. Implicit TLS: 465, 993, 995
  3. 587 only
  4. 143 and 110