9 ms·
DOMPurify bypass: XSS via HTML namespace confusion
- megous 6y agoConverting back to string is asking for trouble.
- jarym 6y agoEnjoyable read - very succinctly explained.
- ievans 6y agoInteresting. Any kind of sanitizer like this seems doomed to fail repeatedly--I like the discussion at http://langsec.org/ http://langsec.org/ I wrote a Semgrep rule (I'm one of the maintainers) to look for calls to the .sanitize() method and suggest the final recommendation in the post, which is to use either RETURN_DOM or RETURN_DOM_FRAGMENT. To use it: pip install semgrep && semgrep --config=https://semgrep.dev/s/ievans:dom-purify2 Or you can just preview it on some test code: https://semgrep.dev/s/ievans:dom-purify2 https://semgrep.dev/s/ievans:dom-purify2
- Gehinnn 6y agoWith this amount of exceptions in the specification, it is no wonder that people find unexpected combinations of different features to exploit stuff. I know why I don't like automatically closing elements. Xhtml for the win!
- dataflow 6y ago+1 for XHTML. I never understood why people think it's a good idea to avoid closing elements. It's like a dangling brace to me... it nags me and it just doesn't look right. How is it seen as acceptable practice?
- vbezhenar 6y agoIt's not a good idea to close all elements in HTML because browser does not care about your closing elements, they'll be closed automatically regardless of whether you closed them or not. And your closed elements will be opened automatically. <p>List: <ul><li>item1</li></ul> of items</p> becomes <p>List: </p><ul><li>item1</li></ul> of items<p></p> and that's probably not what you wanted. So you have to understand auto-closing behaviour either way. And if you understand it, you can just spare yourself from closing them. Now with XHTML, that's a different thing. But I think that ship sailed many years ago and HTML is a preferred way to go nowadays.
- dataflow 6y agoWow, today I learned! I didn't realize that transformation would take place. I wonder how many people writing HTML are aware of these... your comment basically made me realize I in fact simply don't know HTML. Thanks!
- runarberg 6y agoYour linter should warn you about these. E.g. if you use prettier the first `<p>` will be automatically closed on auto-format before the `<ul>`, and the second (closing) `</p>` will cause a parsing error.
- sergeykish 6y agoSometimes we want <ul> inside <p> [1]. It works in DOM, it works in XHTML. And before "you should not want to do it" argument GML (SGML predecessor) had paragraph without indentation so text can continue after list [2]. > The pc tag identifies a paragraph continuation -- that is, one or more sentences related by their subject matter to a paragraph which has been interrupted by an address, example, figure, list, or long quotation. > Usage: The paragraph continuation can occur after the sequence consisting of a paragraph unit followed by an address, example, figure, list, or long quotation. :p.The subject of a paragraph might be continued through :sl :li.an address, a list, :li.an example or figure, or :li.a long quotation, :esl :pc.and continue to be discussed in flowing text. The discussion could continue indefinitely through To long to quote entirely [3], unfortunately IBM destroyed online version [1] https://www.google.com/search?q=list+inside+paragraph+site%3Astackoverflow.com https://www.google.com/search?q=list+inside+paragraph+site%3... [2] SH20-9160-0 DCF Generalized Markup Language GML Users Guide, First Edition (July 1978) [3] http://sergeykish.com/gml-element-pc http://sergeykish.com/gml-element-pc
- kijin 6y ago> So DOMPurify has nothing to do here, and returns a serialized HTML: <form><math><mtext><form><mglyph><style></math><img src onerror=alert(1)></style></mglyph></form></mtext></math></form> This seems to be the wrong part. If "</math><img src onerror=alert(1)>" was interpreted as part of a #text node, it should have been serialized into "</math><img src onerror=alert(1)>" so that it becomes harmless in any subsequent round-trip.
- thaumasiotes 6y agoI think you need to do something more than that, or round trips will give you text that looks like &amp;amp;lt;img src onerror=alert(1)&amp;amp;gt;
- kijin 6y agoOf course, special characters that are already escaped, i.e. already valid in a text node, don't need to be escaped again. Even PHP provided a function to do that 20 years ago. It should be relatively straightforward in any modern language with regexp support.
- thaumasiotes 6y ago> Of course, special characters that are already escaped, i.e. already valid in a text node, don't need to be escaped again. But this isn't true at all. You could have text that's supposed to look like "<span>" -- just look at the discussion we're having right now. And that text needs to be rendered as "&lt;span&gt;", but it also needs not to be rendered as "&amp;lt;span&amp;gt;". You have to keep track of what you've done to it.
- kijin 6y agoAny decent WYSIWYG editor (which I assume your data is coming from if you're trying to sanitize arbitrary HTML) will render "<span>" as "&lt;span&gt;" in the first place. The sanitizer doesn't need to do anything to it, as the markup is already valid.
- pabs3 6y agoI note that MediaWiki's VisualEditor uses DOMPurify in some capacity.
- bawolff 6y agoLast i checked, it was only used for stuff provided to the user themselves (so a bypass in dompurify would allow you to xss yourself but not others.). However that was a long time ago, so im not sure what the current state is.
- MatmaRex 6y agoYeah, that's true. We also always use the RETURN_DOM_FRAGMENT / RETURN_DOM options, which avoids the issue according to the article (I don't think we serialize/reparse the output anywhere ourselves). And also, we forbid the 'style' tag, which seems to be required by the exploits (although that is just a lucky coincidence). https://github.com/wikimedia/VisualEditor/blob/master/src/ve.sanitize.js#L16 https://github.com/wikimedia/VisualEditor/blob/master/src/ve...
- thaumasiotes 6y agoQuoting: --------- Thus, going back to the snippet: <form id="outer"><div></form><form id="inner"><input> In the beginning, the form element pointer is set to the one with id="outer". Then, a div is being started, and the </form> end tag set the form element pointer to null. Because it’s null, the next form with id="inner" can be created; and because we’re currently within div, we effectively have a form nested in form. --------- I was under the impression that a closing tag automatically also closed any tags that were currently open, but contained within the tag being closed. Is it not a bug that, when the </form> tag is encountered, the open <div> tag isn't closed at that point?
- jrwr 6y agoUnder HTML and the DOM (no Javascript) You can do any ordering of the tags, that's pretty normal a <strong><div>hello</strong></div> is perfectly valid HTML
- minitech 6y agoThat’s not valid HTML. It’s “working” HTML, because error recovery is defined pretty well, but quite invalid.
- thaumasiotes 6y agoNo, you're specifically not allowed to do that.
- egberts1 6y agoYou misspelled “specificationally”. :-D
- yyyk 6y agoThese XSS sanitization bugs don't seem to ever stop. The simplest and safest solution for sites would be to implement Content-Security-Policy with a good script-src (with limited sources and without the 'unsafe-inline' escape hatch). Unfortunately, even HN itself uses a script-src with unsafe-inline, and it allows everything on cloudfare's CDN...
- Seb-C 6y agoI had a situation lately where the CSP was not enough because of Safari, so I had to fallback to dom-purify. It is not always possible to just rely on it unfortunately.
- yoloClin 6y agoI think the best solution is CSP _and_ injection mitigations - even without XSS there is still DOM injection which can be equally damaging reputationally. iirc, IE11 (under Windows 7, specifically) does not support CSP. I don't think CSP mitigates all XSS vectors either (`<a href="javascript:alert(1)">` for example). Sure IE11 is deprecated but that doesn't mean you don't need to account for it when building an enterprise application. I'm curious if you can provide any details on what / how Safari was exploitable with CSP - https://caniuse.com/?search=content-security-policy https://caniuse.com/?search=content-security-policy indicates that it should be pretty uniform across popular browsers. If you'd prefer a private channel @yoloClin on twitter.
- yyyk 6y agoA CSP without unsafe-inline will block your example as well. I agree that one should still sanitize input, at least for fields which allow HTML* , but it's obvious XSS filtering/sanitization can introduce XSS as much as not. This article is merely one example, there were enough to make Chrome give up and turn off their XSS filter. So main defence should be CSP and sanitization is just a nice-to-have. * Because sanitized input is often saner than the nonsense users can insert when they are allowed to put in tags. Basically use sanitization as an HTML Tidy with extra filtering. Also for very old browsers.
- rambojazz 6y ago> DOMPurify’s job is to take an untrusted HTML snippet, supposedly coming from an end-user, and remove all elements and attributes that can lead to Cross-Site Scripting The error here is to use a blacklist instead of a whitelist.
- amluto 6y agoIf you read the article, you will find that DOMPurify uses a whitelist, that DOMPurify’s model thinks the offending snippet is safe, that nothing in particular is wrong with the model per se, and that the bug is something else entirely.
- bawolff 6y agoI disagree, dompurify takes a blacklist approach of trying to remove evil instead of only allowing through application-specific sane things (that it uses whitelists is a separate thing)
- bugmen0t 6y agoYou need defaults, and that default is an allow-list of sane HTML. If you want, you can initialize DOMPurify with your own allow-list, that might just be the bold, italics, underline, strikethrough. The fact that their list is not namespace-specific is a bigger issue imo.
- tmd83 6y agoHow to people do proper XSS protection and more importantly validate against it? It's effectively a manual process of calling appropriate escaping (html, css, js) at every dynamic output site. Ensuring you are doing it 100% in thousands if not millions of calls is daunting. I have seen security tools crawling your app and using payload to test for vulnerability which sounds nice in theory but in a really complex application where you need to understand the business rules to even crawl the whole application (not get caught up on validation/error) how do people ensure that?
- nom 6y agoNot sure about validation, but Content-Security-Policy is the best tool we have at our disposal right now to prevent XSS - define what content the browser is allowed to load and execute. I have a feeling it will remain a very manual and diligent process. Be always on top of new techniques and solutions, have a good understanding how everything works in detail and reduce your attack surface by keeping things simple.
- yoloClin 6y agoI agree with CSP, but as I've commented on another thread I recommend CSP _with_ other mitigation factors due to DOM/HTML injection, and browser support.
- continuational 6y agoYou simply never use string concatenation to produce HTML, CSS, JS, SQL, etc. Instead, use e.g. an HTML library that automatically escapes strings. Then you don't even have to think about it.
- bawolff 6y agoYou use libraries with safe apis that make it easy to do the right thing and hard to do the wrong thing. Often this means you generate some sort of data structure which gets serialized into html by a library as a last step (e.g. React, but there are lots of other examples). If you're always using safe apis, its really easy to verify that you dont do the wrong thing (e.g. via static analysis, or even grep. Browsers are even now suporting trusted types to dynamically verify this at runtime)
- sergeykish 6y agoSecond sample from the article does not work — non regular quotes, unmatched alert quote, fixed: <math><mtext><table><mglyph><style><math><table id="</table>"><img src onerror=alert(1)> Works on Firefox, fail to reproduce bypass on Chrome http://sergeykish.com/dompurify-bypass http://sergeykish.com/dompurify-bypass I've asked author, looks like Chrome parses src and srcdoc differently, works with innerHTML.
- triyambakam 6y agoThese are meant to be run through the DOMPurify library which serializes back to a different DOM tree than the input, so the input is not expected to work straight away
- sergeykish 6y agoYes, that's what it does. Check Firefox. First (unescaped) sample was my sanity check, yes, it alerts from <iframe>. It work in Chrome on div.innerHTML = sanitized but not on iframe.srcdoc = sanitized iframe.src = `data:text/html;charset=UTF-8,${sanitized}` I am rewriting document so it is possible to check different methods.
- Sniffnoy 6y agoHm, wouldn't the proper way to defend against such mutation attacks be to run parse-then-serialize in a loop until the output stabilizes? And throw some sort of error if it takes too many iterations. Only after stabilization would you go making any sort of modifications. Although, I guess, now that I think about it, the fact that you are making modifications means I guess there could still be attacks that rely on mutations that potentially happen after those modifications...
- securitymb 6y agoThis would work and this something that Angular DomSanitizer does [1]. But I personally am not a big fan of this solution as it has large performance penalty if the sanitized string is huge. [1] https://github.com/angular/angular/blob/2038568f3e631cb15e9149945692e98ad2c8729d/packages/core/src/sanitization/html_sanitizer.ts#L253 https://github.com/angular/angular/blob/2038568f3e631cb15e91...
- egberts1 6y agoAll this tracking of string types (encoded or decoded) makes me wonder if we should have separate string type AND strong-typing language for handling of HTML strings.
- yencabulator 6y agoOut of curiosity, I fed the attacks to the Go bluemonday library https://github.com/microcosm-cc/bluemonday https://github.com/microcosm-cc/bluemonday It seemed to have no issues whatsoever (click Run): https://play.golang.org/p/oBYXo9MDusr https://play.golang.org/p/oBYXo9MDusr https://play.golang.org/p/KzD1Ug-KKiB https://play.golang.org/p/KzD1Ug-KKiB