I have an application that needs to display foreign HTML data (e.g. HTML-encoded email texts, though not only) safely – i.e., remove XSS attempts and other nasty stuff. But still be able to display HTML as it should look like. Solutions considered so far aren’t ideal:
- Clean HTML with something like HTMLPurifier. Works fine, but once email size goes over 100K it becomes very slow – tens of seconds per email. I suspect any secure enough parser would be as slow in PHP – some emails are really bad HTML, I’ve seen some that generate 150K HTML for one page of text.
- Display HTML in an iframe – here the problem is that iframe needs then to be in another origin to be safe from XSS AFAIK, and this would require different domain for the same app. Setting up application with two domains is much more work and may be very hard in some setups (such as hosting that gives only one domain name).
Any other solutions that can achieve this result?
From my understanding, I don’t believe so.
The trouble is that you can only safely remove HTML tags if you understand its structure, and ‘understanding its structure’ is exactly what parsing is. Even if you find a different way to analyse the structure of HTML and don’t call it parsing, that’s what you’re doing, and it’s bound to be some form of slow (or unsafe).
What you could do is play around with a few preliminary filters (e.g.
strip_tags, which is generally a good prelim’ (if certainly nothing else)) to give the parser less work to do, but whether that’s viable depends on the size of your tag whitelist – a small whitelist will probably yield better benchmark results, since a large chunk of HTML would be filtered out bystrip_tagsbefore the parser got to it.Additionally, different parsers work in different ways, and the sort of HTML you deal with frequently may be best suited to one sort of parser over another – HTML Purifier itself even has different parsers at its disposal that you can switch between to see if that results in a better benchmark for you (though I suspect the differences are negligible).
Whether such juggling works for your usecases is something you’ll probably have to benchmark yourself, though.
Word of caution: If you decide to pursue it, know I wouldn’t go with the iframe approach. If you don’t filter HTML, you also allow forms, and it becomes (IMO) trivial in combination with scripts and CSS to set up extremely convincing phishing, e.g. using tricks such as “this e-mail is password protected, to proceed, please enter your password“.