Skip to main content

Email, SSH and Other Protocols

TL;DR
  • Email is store-and-forward: your client submits to a server (SMTP, 587), servers relay to the recipient's MX host (SMTP, 25), and the recipient reads it later over IMAP (993). SMTP pushes, IMAP is a remote mailbox API.
  • Email has no sender authentication by default. SPF, DKIM and DMARC bolt it on through DNS records, and DMARC is the one that ties them to the visible From address.
  • SSH is one authenticated, encrypted TCP connection (port 22) that carries many channels: a shell, file transfer, and port forwards. Trust the server by its host key, trust yourself by your key.
  • FTP puts its data on a second connection whose port is negotiated inside the control stream, which is why NAT and firewalls need helpers. Use SFTP or FTPS instead.
  • Transport TLS on mail is hop by hop, not end to end. Each server in the path can read the message.

Mental model​

ANALOGYEveryday

Email is the postal system. You hand a letter to your local post office counter (SMTP submission). Sorting offices pass it along, looking up the recipient's town in a directory (SMTP relay, guided by the MX record). It ends up in a mailbox you can open from any device (IMAP). SSH is a sealed armoured courier with an ID check at both ends: the courier proves who they are to you, you prove who you are to them, and then you can send a few errands through the same trusted door.

Where it breaks: a post office will not let a stranger write your name on the return address, but SMTP will accept any claimed sender unless the receiving side checks. And mail passes through several sorting offices that each handle the contents in the clear, unlike a sealed courier.

ANALOGYFor engineers

SMTP is a queue-to-queue push: each server accepts a message, durably queues it, and retries delivery, much like a message broker handing off between hops with at-least-once semantics. IMAP is a remote API over a mailbox (list, fetch, flag, search) so many clients see one state, like a database you query rather than a file you download. SSH is a multiplexed RPC transport: one authenticated connection, many logical streams, like HTTP/2 carrying a shell, a file server and arbitrary TCP tunnels.

Where it breaks: a broker authenticates producers, while SMTP by itself does not. And an SSH channel is not a general network: it carries TCP streams, not UDP or raw IP packets.

How it works​

The path of one email​

Four roles, named in RFC 5598: the MUA (mail user agent, your client), the MSA (submission agent, accepts your outgoing mail after you log in), the MTA (transfer agent, relays between domains) and the MDA (delivery agent, files the message into a mailbox). The sending server finds the next hop by asking DNS for the recipient domain's MX records (DNS records owns that lookup).

MUAMSAMTAMDAMUAsender appsubmissionMX relaymailboxreader appDNS: MX lookup of recipient domainSMTP 587SMTP 25localIMAP 993
Submission on 587, server to server on 25 after an MX lookup, then IMAP on 993 to read it. TLS on each hop is separate, so no single encrypted pipe spans the whole path.

The last arrow points left on purpose: the reader's client pulls from the mailbox. Everything before it is pushed.

An SMTP conversation​

SMTP is a line-oriented text dialogue (RFC 5321). The server answers each command with a three-digit code: 2xx success, 3xx "go on", 4xx temporary failure (retry later), 5xx permanent failure. This transcript is illustrative (example domains, S: server, C: client):

S: 220 mx.example.org ESMTP ready
C: EHLO client.example.com
S: 250 mx.example.org greets client.example.com
C: MAIL FROM:alice@example.com
S: 250 OK
C: RCPT TO:bob@example.org
S: 250 OK
C: DATA
S: 354 End data with CRLF.CRLF
C: (headers, a blank line, the body, then a line holding only a dot)
S: 250 OK queued
C: QUIT
S: 221 closing connection

Two addresses appear and they are different things. MAIL FROM and RCPT TO are the envelope, used for routing and bounces. The From: and To: lines inside the DATA are headers (RFC 5322), which is what your mail client displays. Nothing in base SMTP forces them to match, and that gap is what spoofing lives in.

Ports and TLS: STARTTLS versus implicit TLS​

ProtocolPortRoleTLSDirection
SMTP relay25server to server (MTA to MTA)STARTTLS, opportunisticpush
SMTP submission587client to your provider (RFC 6409)STARTTLS, requiredpush
SMTPS465client to your providerimplicit TLS (RFC 8314)push
IMAP143 / 993client reads a server-side mailboxSTARTTLS / implicit TLSpull
POP3110 / 995client downloads, usually deletingSTARTTLS / implicit TLSpull

STARTTLS means the connection starts in plaintext, the client asks to upgrade, and a TLS handshake follows on the same socket. Implicit TLS means the handshake starts the instant the TCP connection opens. RFC 8314 recommends implicit TLS for mail submission and access because a plaintext start can be stripped by an attacker in the middle. TLS itself is explained once, in TLS; certificate checks are in certificates and PKI. The full port registry is in ports and protocols.

IMAP versus POP3. IMAP (RFC 9051, IMAP4rev2) keeps messages and folders on the server, so a phone and a laptop agree on what is read. POP3 (RFC 1939) downloads messages and usually removes them from the server, so state lives on one device.

SSH: one connection, three layers​

SSH 2 is specified as three stacked protocols (RFC 4251 architecture, 4253 transport, 4252 authentication, 4254 connection).

Connection layer - RFC 4254User authentication - RFC 4252Transport layer - RFC 4253TCP, port 22321shell, exec, sftp, -L, -R, -Dpublickey, passwordkex, host key, cipher, MACmany channels on one connectionwho are you: key or passwordwho is the server: host key, then keys
Built bottom up: TCP, then the transport layer secures the pipe and proves the server, then the client authenticates, then channels are opened inside the secured connection.
  1. Transport. Both sides send a version banner, agree on algorithms, run a key exchange, and the server proves itself with its host key. Everything after this is encrypted and integrity-checked.
  2. Host key check. Your client compares the host key against ~/.ssh/known_hosts. First contact asks you to trust it (trust on first use, TOFU); a later mismatch is a loud warning, because it means either a reinstalled server or an interceptor.
  3. Authentication. Usually public key: you prove you hold the private key matching a public key listed in the server's authorized_keys, without sending the key. Passwords are the fallback.
  4. Channels. Now the client opens channels inside the one connection: an interactive shell, a one-off command, the SFTP subsystem, or port forwards.

The three forwarding modes are owned by VPNs and SSH tunnels (flags, GatewayPorts, SOCKS): -L listens on your side, -R listens on the server, -D makes a local SOCKS proxy.

FTP: two connections​

FTP (RFC 959) uses a control connection on TCP 21 for commands and a separate data connection for each listing or transfer. In active mode the server connects back to the client from port 20; in passive mode the client opens both. The port is negotiated inside the control stream, so a NAT or firewall that reads only headers does not know to let it through. The mechanics and the helper that parses the control channel are in ports and protocols; the NAT side is in NAT and the policy side in firewalls and segmentation.

Deep dive​

SPF, DKIM and DMARC at one paragraph each​

These all live in DNS (record syntax is in DNS records) and each answers a different question.

  • SPF (RFC 7208): "is this IP allowed to send for this domain?" The receiver looks up the TXT record v=spf1 ... of the envelope sender domain (the MAIL FROM, falling back to the HELO name) and checks the connecting IP against it. It never looks at the visible From: header.
  • DKIM (RFC 6376): "was this message signed by a key that domain published?" The sender adds a DKIM-Signature header naming a domain (d=) and a selector (s=); the receiver fetches the public key from a TXT record at selector._domainkey.domain and verifies the signature over chosen headers and the body. It survives forwarding if the content is untouched, where SPF does not.
  • DMARC (RFC 9989, which obsoletes RFC 7489): "does a passing check match the domain the human sees?" A message passes DMARC only if SPF or DKIM passes and is aligned: the domain SPF or DKIM authenticated must match the domain in the From: header. The policy (p=none, quarantine, reject) says what receivers should do on failure, and rua= asks for aggregate reports.

Alignment is the whole point. Without it, an attacker can pass SPF for their own domain in the envelope while forging From: you@yourbank.example in the header.

Deliverability: reverse DNS and reputation​

Large receivers also check that the connecting IP has a PTR (reverse DNS) record that resolves back to a plausible name, and they track the IP's and domain's sending reputation. A new server with perfect SPF and DKIM can still land in spam. That is why most teams send through a provider with warmed-up IPs rather than from their own box.

Store-and-forward and retries​

If the next hop answers with a 4xx code or is unreachable, the sending MTA keeps the message in a queue and retries on a schedule, giving up and sending a bounce after a configured time (RFC 5321 section 4.5.4 recommends retrying for at least 4 to 5 days). A 5xx is final immediately. The lowest-numbered MX is tried first and the others are fallbacks.

SSH details seniors get asked​

  • Agent forwarding (-A) exposes your agent socket on the remote host. Anyone with root there can use your keys while you are connected. Prefer ProxyJump (-J bastion target), which tunnels through the bastion without exposing your agent.
  • SSH certificates. Instead of distributing every user's public key to every server, a certificate authority signs user keys (ssh-keygen -s) and servers trust the CA. Short validity replaces key revocation chores. See authentication in practice for the general identity patterns.
  • SFTP is not FTP over SSH. It is a different protocol, run as an SSH subsystem on port 22. FTPS is real FTP wrapped in TLS (RFC 4217), and it still needs the second connection.
  • Why FTP is replaced. Plain FTP sends username, password and files in cleartext. SFTP keeps all traffic in one encrypted connection, which also removes the firewall problem.

Textbook vs real world​

The textbook saysProduction doesWhy
SMTP delivers straight from sender to recipient serverMail passes through submission servers, cloud relays, spam filters and often a security gateway before the mailboxReputation, filtering and compliance live in the middle; direct-to-MX from a random IP is usually rejected
Email is encrypted in transitTLS is negotiated per hop and often opportunistic; MTA-STS (RFC 8461) can make it mandatory for a domainEach relay still reads the message; only end-to-end schemes protect the content
SSH is a remote shellSSH carries Git pushes, file copies, database tunnels and bastion jumpsOne authenticated, already-allowed port multiplexes everything
FTP is how you move filesFTP is essentially gone from the public web; SFTP and HTTPS uploads replaced itCleartext credentials plus the two-connection design that fights NAT

In production​

  • Bulk sender rules. Google announced requirements for senders of more than 5,000 messages a day to Gmail addresses, including authenticating with SPF and DKIM and publishing a DMARC policy, effective February 2024 (Google announcement). Yahoo published matching requirements (Yahoo sender best practices). Read the vendor pages for the current thresholds, which can change.
  • Browsers dropped FTP. Chrome removed its FTP support in 2021, tracked on Chrome Platform Status.
  • Replacing SSH exposure. AWS offers Systems Manager Session Manager and EC2 Instance Connect so instances can be reached without a long-lived key or an open inbound port 22.
  • Git over SSH. Hosting services accept Git pushes and pulls over SSH on port 22 using your public key; the protocol is the same one described above.

History and evolution​

HISTORY
  • 1971 FTP is first specified as RFC 114 on the early ARPANET, a file mover with no thought for encryption or NAT.
  • 1982 SMTP is defined in RFC 821: plain text, no authentication, built for a small trusted network. It is now RFC 5321.
  • 1984 POP appears (RFC 918) for fetching mail to one machine; IMAP's first design follows in 1986 to keep mail on the server for many clients.
  • 1985 FTP is reissued as RFC 959, still the base spec today.
  • 1995 Tatu Ylonen writes SSH at Helsinki University of Technology after a password-sniffing attack on the campus network, to replace telnet and rsh (overview).
  • 2006 SSH-2 is standardised in RFCs 4251 to 4254.
  • 2018 RFC 8314 recommends implicit TLS for mail, and MTA-STS (RFC 8461) lets a domain demand TLS between servers, because opportunistic STARTTLS can be downgraded.
  • Now Big receivers require SPF, DKIM and DMARC from bulk senders; SSH uses certificates, ed25519 keys and cloud session brokers.
  • Next Passkeys and zero-trust access proxies take over interactive login, while mail authentication keeps tightening.

Hands-on​

Outputs below were captured on 2026-10-14 (OpenSSH 10.5p1, OpenSSL 3.6.5, macOS). Yours will differ, because providers change records and servers change algorithms.

dig MX gmail.com +short
5 gmail-smtp-in.l.google.com.
10 alt1.gmail-smtp-in.l.google.com.
20 alt2.gmail-smtp-in.l.google.com.
30 alt3.gmail-smtp-in.l.google.com.
40 alt4.gmail-smtp-in.l.google.com.

Lowest number is tried first. Now the authentication records:

dig TXT gmail.com +short | grep spf
dig TXT _dmarc.gmail.com +short
"v=spf1 redirect=_spf.google.com"
"v=DMARC1; p=none; sp=quarantine; rua=mailto:mailauth-reports@google.com"

SPF here delegates to another name with redirect=. The DMARC policy for the bare domain is p=none (monitor), with sp=quarantine for subdomains. Reading them is a dig skill.

Talk SMTP over TLS with openssl s_client (curl and openssl explains the tool). Type EHLO example.org, then QUIT:

openssl s_client -starttls smtp -connect smtp.gmail.com:587 -crlf -quiet
depth=0 CN=smtp.gmail.com
verify return:1
250-smtp.gmail.com at your service, [your IP]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
250-ENHANCEDSTATUSCODES
250-PIPELINING
250 SMTPUTF8
221 2.0.0 closing connection ... - gsmtp

That is the EHLO reply after the TLS upgrade, abbreviated. The AUTH line lists what login methods are offered only now that the channel is encrypted. For a plain TCP look use nc (see ss, nc, lsof, ip); many home networks block outbound port 25.

ssh -v -o BatchMode=yes example@github.com
debug1: Connecting to github.com [140.82.112.4] port 22.
debug1: Remote protocol version 2.0, remote software version 3bc2e72
debug1: kex: algorithm: sntrup761x25519-sha512
debug1: kex: host key algorithm: ssh-ed25519
debug1: Server host key: ssh-ed25519 SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU
debug1: Authentications that can continue: publickey
example@github.com: Permission denied (publickey).

You can see the layers in order: banner, key exchange, host key, then authentication, which fails because the fake user has no key there. Compare the fingerprint to the one the service publishes before trusting it.

ssh-keygen -t ed25519 # make a key pair
ssh-keyscan example.com # fetch a server's host keys
ssh -L 8080:localhost:80 host # local forward, see the VPN page

Gotchas​

GOTCHAS4
The From address proves who sent it
SSH is secure, so port forwarding is harmless
FTP through a firewall only needs port 21
Email is encrypted

Interview questions​

INTERVIEWHow does an email get from sender to recipient?junior
Show answer

The sender's client submits the message to its provider's server over SMTP, usually on port 587. That server looks up the MX records for the recipient's domain in DNS and connects to the lowest-numbered reachable one over SMTP on port 25. The recipient's server files the message in a mailbox, and the recipient reads it with IMAP or a web interface.

Follow-ups:

  • What is an MX record? A DNS record that names the mail server for a domain, with a preference number where lower is tried first.
  • What if the next server is down? The sender queues the message and retries, and bounces it after a long timeout.
INTERVIEWWhat is the difference between SPF, DKIM and DMARC?mid
Show answer

SPF says which IP addresses may send for the envelope sender's domain. DKIM is a cryptographic signature over the message that the sending domain's published key can verify. DMARC checks that a passing SPF or DKIM result is for the same domain as the visible From header, and publishes a policy and reporting address for failures.

Follow-ups:

  • Why does DMARC need alignment? Without it an attacker passes SPF or DKIM for their own domain while forging the From header you see.
  • Which survives forwarding? DKIM, if the content is not modified. SPF breaks because the forwarder's IP is not in the original domain's record.
INTERVIEWSMTP versus IMAP versus POP3, and how is each secured?mid
Show answer

SMTP pushes mail: submission from a client on 587, relay between servers on 25. IMAP and POP3 are for reading: IMAP keeps mail on the server for many devices, POP3 downloads it and usually deletes the server copy. Each can start plaintext and upgrade with STARTTLS or use implicit TLS from the first byte (465, 993, 995), which RFC 8314 recommends.

Follow-ups:

  • Why prefer implicit TLS? There is no plaintext window for an attacker to strip the upgrade.
  • Is the message end to end encrypted? No. TLS is per hop.
INTERVIEWHow does SSH authenticate, and what is port forwarding good for?mid
Show answer

The transport layer first establishes encryption and the client checks the server's host key against known_hosts. Then the client authenticates, normally by proving it holds a private key whose public half the server has listed. Port forwarding reaches one internal TCP service, such as a database, through the SSH connection without a VPN.

Follow-ups:

  • What is the bastion pattern? One hardened host is the only SSH entry to a private network, and you jump through it with ProxyJump.
  • What is the risk? Forwards and agent forwarding extend access beyond what the firewall thinks it allowed.
INTERVIEWWhy does active FTP break behind NAT, and what fixes it?mid
Show answer

In active mode the client announces an address and port in the control stream and the server connects back to it. A NAT sees an unsolicited inbound connection and the announced private address is wrong anyway. Passive mode has the client open both connections, which mostly works, and SFTP removes the problem by using one connection on port 22.

Follow-ups:

  • What does a firewall helper do? It reads the control channel, rewrites the address and opens the negotiated port.
  • Is FTPS better? It encrypts FTP but keeps the two-connection design, so the same firewall issues apply.

Fun facts​

FACTSTrivia worth knowing
  • SMTP's three-digit reply codes follow the same scheme FTP used, and HTTP status codes echo that style.
  • An SSH host key fingerprint such as SHA256:... is a hash of the public host key, so services can publish it for you to compare on first connect.
  • Email's envelope sender and header From are separate fields, which is why a bounce can go to a different address than the one you see on a message.

Cheat sheet​

NUMBERSOther protocols, one line each
  • SSH 22/TCP - encrypted shell, files, tunnels
  • FTP 21/TCP - control channel, data on a second connection
  • NTP 123/UDP - clock sync
  • SNMP 161/UDP - device monitoring and management
  • syslog 514/UDP - log shipping
  • LDAP 389 / 636 - directory lookups, plain or TLS

All numbers are registry defaults; see ports and protocols.