Skip to content

shipped · · 12 min

We closed a DNS-rebinding gap in our mail clients by pinning the socket to the address we checked

How a validate-then-connect SSRF guard let Ruby's Net::IMAP and Net::SMTP resolve a hostname twice, why a cloud threat detector flagged our own guard, and the one private method, tcp_socket, that pins the dial to the approved IP while TLS still verifies the hostname.

A multi-tenant SaaS app makes outbound connections on its users' behalf all day. Webhooks POST to a URL the customer typed. The mail integration opens IMAP and SMTP sessions to a host the customer typed. Every one of those is a server-side request forgery surface: if the typed host is 169.254.169.254, the request comes from inside your network, where the cloud metadata service answers.

We had a guard for this, and for HTTP it was right. For mail it was checking one address and connecting to another. This post covers how that happens, why the usual fix ("validate the host first") doesn't close it, and the three-line change that does, in both Ruby mail libraries, without losing TLS hostname verification.

What tipped us off: our own guard

The first signal wasn't a bug report. A cloud threat detector raised a metadata DNS rebinding finding on the application hosts, along with a DNS-over-HTTPS finding pointing at 1.1.1.1.

The hosts were clean. CloudTrail showed the instance role used only from the hosts' own addresses, and IMDSv2 was required. The lookups came from our SSRF guard. Some sign-ups had saved webhook URLs like these:

terminal
https://169.254.169.254/latest/meta-data/iam/security-credentials/
https://169.254.169.254.nip.io/
https://[::ffff:169.254.169.254]/
https://2130706433/                     # 127.0.0.1 as a decimal
https://httpbin.org/redirect-to?url=http://169.254.169.254/
https://01010101.a9fea9fe.rbndr.us/      # the interesting one

The guard resolved each name before refusing it. Resolving a name that answers 169.254.169.254 is exactly what the detector watches for. So the finding was real, but the actor was the code saying no.

The last name on that list is the reason for this post.

DNS rebinding in one picture

rbndr.us is a public test service. A name like 01010101.a9fea9fe.rbndr.us encodes two IPv4 addresses in hex (1.1.1.1 and 169.254.169.254). The server answers with one or the other, at random, with a TTL of zero, so nothing caches the answer.

One name, two answers01010101.a9fea9fe.rbndr.uslookup 1 → 1.1.1.1lookup 2 → 169.254…lookup 3 → 1.1.1.1public: passesmetadata: blockedpublic: passesTTL 0: every lookup asks again, and every answer is a coin toss

A rebinding name answers differently on every lookup. A check that resolves the name and a connect that resolves it again can see two different addresses.

It also explains the second finding. When the name answered 1.1.1.1, the guard approved it (it's a public address) and the webhook POST went to 1.1.1.1:443. To a detector, that is a host talking HTTPS to a well-known DoH resolver. Harmless, but now both findings had one cause.

The guard that was right: webhooks

Webhook delivery already did the four things that matter:

  1. Resolve once and check every answer, not just the first. A name with one public and one private A record must fail.
  2. Pin: open the TCP connection to the IP that passed, not to the name.
  3. Keep the name for TLS: SNI and certificate verification still use the hostname, so pinning doesn't break HTTPS.
  4. Never follow redirects. A redirect is a second URL nobody checked.

Against the probes above, it refused 164 of 175 deliveries outright. The other 11 went to the public redirectors, which answered 403/404 to a POST. The guard never followed the Location header, so the redirect to 169.254.169.254 was never fetched.

The guard that was wrong: IMAP and SMTP

The mail side had the same guard, used differently:

terminal
# before: the approved address is computed, then thrown away
Email::HostGuard.public_addr!(account.imap_host)   # resolves, checks, returns an IP
imap = Net::IMAP.new(account.imap_host, port: 993, ssl: true)  # resolves AGAIN

public_addr! returned the approved IP, and every caller ignored the return value. They passed the hostname to Net::IMAP or Net::SMTP, which resolved it a second time when it dialled. A comment above one of the call sites called this an "accepted residual risk". With a rebinding name that's not residual. It's a coin toss you can repeat until it lands on metadata.

Validate, then connect: two lookupsappDNSnetworkguard: resolve host1.1.1.1: public, approved (IP discarded)Net::IMAP.new(host): resolve again169.254.169.254connect to metadata

The check and the connect each do their own lookup. Nothing ties the second answer to the first.

The fix everyone reaches for first is to pass the IP instead of the name: Net::IMAP.new("1.1.1.1", ...). That breaks TLS. SNI is sent for the IP, the server's certificate names the hostname, and verification fails. Or worse, someone turns verification off to make it work. You need the socket to go to the IP and the TLS layer to keep the name.

The seam: tcp_socket

Both libraries open their TCP connection through one private method, and both keep the hostname in an instance variable that the TLS code reads later.

  • Net::SMTP#tcp_socket(address, port) dials. The TLS wrapper sets hostname (SNI) and runs post_connection_check against @tls_hostname || @address, which is the name you passed to new.
  • Net::IMAP#tcp_socket(host, port) dials. start_tls_session sets SNI and verifies against @host, which is again the name.

So the override only swaps the argument at the moment of dialling:

terminal
class PinnedSmtp < Net::SMTP
  private

  def tcp_socket(address, port) = super(HostGuard.public_addr!(address), port)
end

class BoundedImap < Net::IMAP
  def initialize(host, read_timeout:, **options)
    @read_timeout = read_timeout
    super(host, **options)
  end

  private

  def tcp_socket(host, port)
    super(HostGuard.public_addr!(host), port).tap { |s| s.timeout = @read_timeout }
  end
end

There is one lookup now, and it happens at connect time. Its answer is the address the kernel dials, and the hostname goes untouched to the TLS layer.

One lookup, two layersPinnedSmtp.new(host)tcp_socket:public_addr!(host) → IPTCP connect → IPTLS on that socket: SNI = host,certificate verified against host@address / @host keepthe name for TLSblocked answer → BlockedHost raised before any packet leaves

The name goes to TLS, the approved address goes to TCP, and the only lookup is the one that was checked.

What the guard checks

Pinning only helps if the check is strict. public_addr! refuses when any resolved address falls in:

RangeWhy
0.0.0.0/8"this network"; reaches localhost on many stacks
127.0.0.0/8, ::1loopback
10/8, 172.16/12, 192.168/16, fc00::/7private
169.254/16, fe80::/10link-local, where cloud metadata lives
100.64/10carrier-grade NAT
::/96, 64:ff9b::/96, 2002::/16IPv6 forms that embed an arbitrary IPv4
IPv4-mapped IPv6unwrapped with native before the range check

Literal IPs skip DNS and go straight to the range check. Decimal and hex forms (2130706433, 0x7f000001) are parsed by the resolver, so they are covered because the check runs on the resolved address, not on the text.

Make it impossible to forget

A guard that callers must remember to call will be forgotten. This one was. The IMAP IDLE listener built its own Net::IMAP.new, so the fix was structural:

  • every IMAP connection goes through BoundedImap (the IDLE listener passes read_timeout: nil)
  • every SMTP connection goes through PinnedSmtp, or a module prepended to the delivery class that overrides the same tcp_socket

One way in means one place to get it right.

The regression test fakes a rebinding resolver: it answers a public address the first time and the metadata address after that. Then it asserts what the socket actually dialled.

terminal
it "dials the address the guard approved, not a second lookup" do
  answers = %w[203.0.113.10 169.254.169.254]
  allow(Addrinfo).to receive(:getaddrinfo).with("mail.rebind.test", any_args) do
    [ Addrinfo.tcp(answers.shift || "169.254.169.254", 0) ]
  end
  expect(Socket).to receive(:tcp).with("203.0.113.10", 993, any_args).and_return(fake_socket)

  Email::BoundedImap.new("mail.rebind.test", port: 993, ssl: false, read_timeout: 5)
end

With the override removed, Socket.tcp receives the hostname and the expectation fails. We checked that by reverting the fix and watching it go red. A guard test that passes both ways isn't testing anything.

Refuse it at save time too

Pinning makes the connection safe. It doesn't stop the app from storing https://169.254.169.254/ and refusing it on every event forever. Webhook targets are now resolved when they're saved. A target that resolves into any blocked range doesn't save.

Two details matter:

  • An unresolvable target still saves. DNS is flaky, and a customer setting up a new endpoint shouldn't be blocked by a missing record. The send-time pin still protects it.
  • The error doesn't say why. "Must be a public address we're allowed to reach" covers both private and blocked. If the message said "resolves to 10.0.3.7", the form would become a DNS oracle for your internal network.
Two layers, two jobssave time: resolve, refuse privatekeeps junk out of the tablesend time: resolve, check, pinthe only layer that is a defenceDNS can change after save, so the save check is hygiene, not security.The send-time pin holds even when a saved name later rebinds.

The save-time check is about noise and intent. The connect-time pin is the security boundary.

Triage checklist for the next detector finding

When a metadata-rebinding or DoH finding lands on an app host, check your own stored targets before assuming a compromise:

  1. Search every column that holds a user-supplied host (webhook URLs, mail hosts, logo URLs, knowledge-source URLs) for 169.254, nip.io, sslip.io, rbndr, localhost and redirect-to.
  2. Read your delivery log for those targets. The question is whether any response came back, not whether a request was made.
  3. Ask the cloud audit log where the instance credentials were used from. If every call comes from the host's own address, nothing left the box.

The decisions, and what set each one

DecisionThe constraint that set it
Pin in tcp_socketthe one seam both mail libraries dial through, and it leaves the TLS hostname alone
Check every resolved addressa name can return one public and one private record; checking the first is a coin toss too
Never follow redirectsa redirect is a new, unchecked URL; the 11 redirector probes died here
Unwrap IPv4-mapped IPv6 before the range check::ffff:169.254.169.254 isn't in any IPv6 private range
Save-time refusal, unresolvable allowedDNS outages shouldn't block setup; the send-time pin still covers it
Generic error texta precise error turns the form into an internal DNS oracle
One class per protocol, no direct Net::*.newthe bug was a caller that forgot; make forgetting impossible

Validating a hostname and then handing the hostname to a library is the same mistake as checking a file's permissions and then opening it by path. If the second step looks the name up again, the check proved nothing. Pass the result of the check, not the input to it.

Working through something like this? I help teams ship AI and cloud systems that hold up, and cost what they should.