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:
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.
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:
- Resolve once and check every answer, not just the first. A name with one public and one private A record must fail.
- Pin: open the TCP connection to the IP that passed, not to the name.
- Keep the name for TLS: SNI and certificate verification still use the hostname, so pinning doesn't break HTTPS.
- 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:
# 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.
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 setshostname(SNI) and runspost_connection_checkagainst@tls_hostname || @address, which is the name you passed tonew.Net::IMAP#tcp_socket(host, port)dials.start_tls_sessionsets SNI and verifies against@host, which is again the name.
So the override only swaps the argument at the moment of dialling:
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.
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:
| Range | Why |
|---|---|
0.0.0.0/8 | "this network"; reaches localhost on many stacks |
127.0.0.0/8, ::1 | loopback |
10/8, 172.16/12, 192.168/16, fc00::/7 | private |
169.254/16, fe80::/10 | link-local, where cloud metadata lives |
100.64/10 | carrier-grade NAT |
::/96, 64:ff9b::/96, 2002::/16 | IPv6 forms that embed an arbitrary IPv4 |
| IPv4-mapped IPv6 | unwrapped 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 passesread_timeout: nil) - every SMTP connection goes through
PinnedSmtp, or a module prepended to the delivery class that overrides the sametcp_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.
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.
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:
- 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,localhostandredirect-to. - Read your delivery log for those targets. The question is whether any response came back, not whether a request was made.
- 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
| Decision | The constraint that set it |
|---|---|
Pin in tcp_socket | the one seam both mail libraries dial through, and it leaves the TLS hostname alone |
| Check every resolved address | a name can return one public and one private record; checking the first is a coin toss too |
| Never follow redirects | a 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 allowed | DNS outages shouldn't block setup; the send-time pin still covers it |
| Generic error text | a precise error turns the form into an internal DNS oracle |
One class per protocol, no direct Net::*.new | the 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.