# Improper markup sanitization in popular software
_[Featuring](#affected-software): GitHub, GitLab, Bitbucket, Redmine, Gogs, JetBrains, and others._
There are several common markup (mostly Markdown) sanitization issues outlined in this article, but I would be mostly speaking about the single, most common one.
_If you don't care about the technical stuff, just skip to the [screenshots](#github) and scroll down._
## Introduction
Most solutions that deal with social coding, issues and comments obviously allow some sort of formatting in those comments and in
other places (e.g., the README files in the repos).
Accepting untrusted content from user, processing the markup language, and producing sanitized safe HTML is a common usage scenario.
Allowing a subset of HTML markup is also a commonly used feature (this is even included in the Markdown spec).
### How it should be done
The only correct way to produce sanitized HTML on the output is to parse everything to a tree structure, make sure that that tree
is sanitized, then encode it to HTML. Sounds pretty simple, doesn't it?
A fast way to achieve that is to add a sanitizer at the very last step of the transformations, and define the ruleset for that
sanitizer — this way, no matter what else is broken in the transformation pipeline, it won't affect the safety of the produced
html. Refer to [this article](https://michelf.ca/blog/2010/markdown-and-xss/) for some explanations.
_In some cases, the sanitizer might not be needed, when the markup library builds a safe tree structure from scratch, ensuring that
no unsafe content is put into that tree. It's still better to apply a dedicated sanitization step afterwards, as I would trust
specialized sanitizers more than markup libraries that might miss some specific things._
So, what could go wrong?
### Ways to break things
1. **Not having sanitization at all.**
Check if your markup library sanitizes things (e.g. already utilizes a good sanitizer).
If it doesn't (some treat this as not their problems, and they are correct) — you need an external sanitizer.
2. **Applying any transformations after sanitization.**
Any transformations applied after the sanitization are not sanitized themselves, and could produce unsafe code.
3. **Sanitizing in the process of transformations.**
This usually gets broken very quickly, for the reasons stated above.
There are more places to make mistakes this way, also there could be various interplay between some transformations.
Also, some user-supplied content might even end up untransformed, and will be unsanitized because of that.
4. **Having an insecure ruleset passed to the sanitizer.**
E.g. allowing some elements/attributes that really shouldn't be allowed.
Most issues present in this post are related to that.
5. **Having the serialization broken.**
If you are using a sanitizer (_you should be_) — it's mainly their task.
The tree structure should be correctly encoded in a HTML form, e.g. forgetting to encode HTML attributes and putting `"`
there unescaped will break things very badly.
6. **Mistakes through transferring.**
This is tangentially related to applying transformations after sanitization.
E.g. if the HTML is stored/passed in a JSON form, it should be property encoded to that JSON form when doing so.
If it's not — the attacker could use JSON escape sequences that will get unescaped by the time the HTML will be inserted to
the web page.
### Ways to fix things
Make sure that:
1. You or your library are using a specialized sanitizer.
2. That sanitizer is known to be good enough.
3. Your ruleset for the sanitizer is fine. There should be a **whitelist** of allowed tags and a **whitelist** of their allowed attributes,
if you use those.
For some attributes, including `id` and `class` (see below), there should be a whitelist or additional validation.
Attributes like `href` also should never be allowed blindly — but the sanitizer should take care of that.
Btw, if you are using just the defaults — you should make sure what exactly are those «defaults»,
I have seen issues related to that (not mentioned here).
4. You don't apply any transformation after the sanitization, including transfer errors.
5. You use CSP which is not relaxed to a state where it does almost nothing.
6. You have carefully checked the OWASP [cheatsheet](https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet)
(and other similar ones that you might find on the internet). Better to add those examples to your tests, btw.
## Unsanitized `class` attribute
[tl;dr](#tldr).
The most common issue had two prerequisites:
1. Allowing a subset of HTML markup (that feature is included in Markdown spec),
2. Code syntax highlighting.
Markdown parsers implementing (1) have to support both Markdown and HTML, and they have to sanitize the code in some way to avoid malicious content (e.g. embedded JS). The most obvious place for the sanitizer is the last step, after the markup is processed — that makes the logic resistant to various errors in the markup processor, which is rather complex and could potentially produce unsafe or invalid HTML if some bug is present in that processor.
So, the common rule of thumb is — after (or in the process) of the markup being processed, convert everything to DOM, then run the sanitizer to allow only whitelisted set of HTML tags and attributes, then serialize that DOM to HTML.
So far so good, what could go wrong there? And what does code syntax highlighting has to do with that?
Let's say we want to add syntax code highlight to our shiny and secure model (as described above). How would we do that? There are existing JS libraries for syntax code highlighting on the clientside, let's take one of those and just use that. It should just work, shouldn't it? _(Minor remark: that doesn't literally mean just throwing in thirparty software blindly, just making an in-house solution that behaves similar to already existing ones gives the same result here)._
But wait, our library wants us to specify a `class` attribute on `code` or `pre` elements to hint the language which syntax do we want to highlight.
So, what a programmer that doesn't think much about security at that point _or at least doesn't question why the rules for the sanitizer were written in the way they were present_, would do there?
### tl;dr
**It looks like most of the affected projects (those with the common issue of `class` not being sanitized) carefully landed that loophole for the sake of code syntax highlighting, and allowed arbitrary `class` attributes on `code` and/or `pre` elements.**
So `class` attribute was added to the exceptions for specific tags and was not sanitized for those tags, but why exactly is this bad? In fact, if there were no css or js on the webpage at all, there wouldn't be any difference. But in real world, there is a bunch of css rules and js code on all those pages, and both of those in most cases heavily rely on `class` properties of DOM elements.
### Utilizing existing CSS rules
Websites usually have a large number of CSS rules that allow styling of elements using their `class`es, and those rules could be utilized and combined to achieve any desired look of the webpage, by overriding different rules with other classes. The ability to use nested elements with different `class` attributes gives the attacker even more flexibility.
### Reusing existing JavaScript event listeners
`class` attributes are also widely used to attach JavaScript event listeners, e.g. `$('#someclass').click(function() {…})` or `$(document).on('click', '.someclass', function() {…})` (yeah, many sites still use jQuery, so I'm using those as an example).
Those already existing event handlers could be used by the attacker to execute some potentially malicious actions on user behalf.
## Affected software
I have found and reported markup sanitization related issues in: \
[GitHub](#github), [GitLab](#gitlab),
[Bitbucket](#bitbucket),
[Gogs](#gogs), [Gitea](#gitea), [Redmine](#redmine),
[Vanilla Forums](#vanilla),
[YouTrack](#youtrack),
[Upsource](#upsource),
[JIRA](#jira).
Of those, [Bitbucket](#bitbucket), [Vanilla Forums](#vanilla), [YouTrack](#youtrack), and [Upsource](#upsource) issues are not related to unsanitized `class` atribute.
Note that the first two of those don't satisfy the [prerequisites](#introduction) — Bitbucket does not support HTML markup in Markdown at all, and
Vanilla doesn't have code syntax highlighting.
They managed to fail markup sanitization in other ways, though, and that's the reason for them to be included in this writeup.
See below for the detailed vulnerabilities information, PoC examples and screenshots.
### GitHub
Fixed in [v2.9.2](https://enterprise.github.com/releases/2.9.2/notes).
The disclosure is available
[here](https://bounty.github.com/researchers/ChALkeR.html#user-controlled--class--attribute-on-some-markdown-tags-20170321).
#### Forged content

The most simple PoC (as seen above) was achieved with this code:
```html
1
1
```
_And more padding with «1» below to adjust the next message / comment form placement._
This has several drawbacks — the image was clickable, on this exact screenshot the «1 participant» label wasn't affected, etc.
That all could have been avoided, but I was lazy there, and the above version was enough for the report.
#### Fullsize

PoC:
```html
```
#### JS event handlers
GitHub binds event handlers by class name at many places in their JS client-side code (e.g. `…(document).on("click",".js-add-gist-file",function()…`), so it was possible to bind the desired pre-existing `onclick` event handler to the user content. I did not produce a full-featured PoC for this as it was not important for fixing the issue, so I preferred to report it faster instead. I made a simple demo that just logged an error to the console on click, though.
### GitLab
Fixed in [v9.0.4/v8.17.5/v8.16.9](https://about.gitlab.com/2017/04/05/gitlab-9-dot-0-dot-4-security-release/).
Disclosed on [HackerOne](https://hackerone.com/reports/216453).

Pretty much the same issue as in GitHub, so I won't repeat myself.
PoC:
```html
Hello there! Something has gone wrong, we are working on it.
In the meantime, play a game with us at http://example.com/.
``` I also made a simple JS action example just to demonstrate the concept, but it's unimpressive (hiding one element and showing another one on click), so I won't include a screenshot here. ### Gogs  Fullsize message is pretty similar to the already mentioned ones. PoC: ```html
![]()
Hello there! Something has gone wrong, we are working on it.
In the meantime, play a game with us at example.com.
Hello there! Something has gone wrong, we are working on it.
In the meantime, play a game with us at example.com.
```

That is a demo of content (actually, a same page) being loaded inside the comment on click. I did not go further, that was not relevant to fixing the issue.
That was a simple `Click me!`.
### Gitea
A community-managed Gogs fork.
_Fixed in [this PR](https://github.com/go-gitea/gitea/pull/1461)._

PoC is mostly the same as in Gogs, but with a different logo.

That one executes a basic POST request (and fails) on click. I did not go further.
### Redmine
Fixed in [v3.3.3/v3.2.6](http://www.redmine.org/news/111).

PoC:
```html
Hello there! Something has gone wrong, we are working on it.
In the meantime, play a game with us by clicking the link below:
http://example.com/
{repeated several times}
```
Could you spot the difference with the screenshots for other projects? This one looks very suspicious.
Redmine (in default setup) has a relatively small number of css rules and a small client-side JS file (which doesn't bind onclick handlers solely by the `class` attribute). Thus, the issue for the default Redmine setup has lower severity than for all other mentioned projects. The above screenshot was made with the default setup, though.
The severity could be raised in presence of various Redmine plugins that include their own js/css to the page, and installing thirdparty plugins is pretty popular in Redmine ecosystem.
### Bitbucket
_Fixed at: 2017-06-20._
The issue here is different and is not related to `class` not being sanitized.
This is a full-featured XSS, with arbitrary JS code, achievable through issue comments (among other places).
PoC 1, covers everything on the page with a div with an `onmouseover` event handler executing arbitrary JS code:
```md
The HTML specification is maintained by the W3C.
*[HTML]: [Hyper Text Markup Language](http://example.com/bar/style='background:#fff;font-size:0;left:0;right:0;top:0;bottom:0;z-index:99990;position:fixed'#/onmouseover=alert('xss:'+document.cookie);")
```

PoC 2:
~~~md
```
#!lolcoad.0000123
lol
```
~~~

I was surprised by the fact that Bitbucket does not use Content Security Policy at all (they said that they are in the process of adding it).
Note: Atlassian security team managed to disclose the XSS vulnerability before fixing it by testing the PoC in a public repo issues
on their production server, soon after I reported the issue and provided the PoC privately, and it was public until I noticed that
after 19 hours. Explanation was the following: «testing your PoC to make sure it was reproducible».
_They acknowledged that it was accidential — the test repository itself was private, but its issue tracker
was public. I was able to find my PoC in that public issue tracker, though.
That repo permissions were fixed in an hour after I noticed that._
This issue has been passed to the development team after 50 days from the inital report.
An incomplete fix was deployed 57 days after the report — that covered only the first one of the originally reported PoCs
(the other one did not execute arbitrary JS code, though).
The complete fix was deployed after 78 days from the initial report.
Timeline:
* Discovered: 2017-04-03
* Reported: 2017-04-03
* Confirmed by Atlassian Security team: 2017-04-03
* PoC leaked to a public repo issues by Atlassian Security team: 2017-04-03
* Issue was assigned to the Bitbucket development team: 2017-05-23
* Incomplete fix deployed (covered only the first PoC): 2017-05-30
* Complete fix deployed: 2017-06-20
### Vanilla
_Fixed in Vanilla [2.5.0](https://github.com/vanilla/vanilla/tags) / htmlLawed [1.2.1.1](http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/htmLawed_README.htm#s4.3)._
An issue in Vanilla Forums allowed arbitrary user content in `style` attribute (not related to `class` not being sanitized), which could
be used to obtain any desired look of the page (forging other people content, etc).
User-specified `align` attribute value was inserted into actual `style` attribute, and that was done without proper
sanitization or escaping.
The upstream issue was in the HTML sanitizer that they use,
[htmLawed](http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/) (actually, it's [fork](https://github.com/vanilla/htmlawed)).


PoC:
```html

Hello there! Something has gone wrong, we are working on it.
In the meantime, play a game with us at example.com.