Strict HTML Validation and Filtering in PHP

前端 未结 4 800
刺人心
刺人心 2020-12-08 03:04

I\'m looking for best practices for performing strict (whitelist) validation/filtering of user-submitted HTML.

Main purpose is to filter out XSS and similar nasties

相关标签:
4条回答
  • 2020-12-08 03:41

    I've tested all exploits I know on HTML Purifier and it did very well. It filters not only HTML, but also CSS and URLs.

    Once you narrow elements and attributes to innocent ones, the pitfalls are in attribute content – javascript: pseudo-URLs (IE allows tab characters in protocol name - java	script: still works) and CSS properties that trigger JS.

    Parsing of URLs may be tricky, e.g. these are valid: http://spoof.com:xxx@evil.com or //evil.com. Internationalized domains (IDN) can be written in two ways – Unicode and punycode.

    Go with HTML Purifier – it has most of these worked out. If you just want to fix broken HTML, then use HTML Tidy (it's available as PHP extension).

    0 讨论(0)
  • 2020-12-08 03:48

    The W3C has a big open-source package for validating HTML available here:

    http://validator.w3.org/

    You can download the package for yourself and probably implement whatever they're doing. Unfortunately, it seems like a lot of DOM parsers seem to be willing to bend the rules to allot for HTML code "in the wild" as it were, so it's a good idea to let the masters tell you what's wrong and not leave it to a more practical tool--there are a lot of websites out there that aren't perfect, compliant HTML but that we still use every day.

    0 讨论(0)
  • 2020-12-08 03:52

    I used HTML Purifier with success and haven't had any xss or other unwanted input filter through. I also run the sanitize HTML through the Tidy extension to make sure it validates as well.

    0 讨论(0)
  • 2020-12-08 04:02

    User-submitted HTML isn't always valid, or indeed complete. Browsers will interpret a wide range of invalid HTML and you should make sure you can catch it.

    Also be aware of the valid-looking:

    <img src="http://www.mysite.com/logout" />
    

    and

    <a href="javascript:alert('xss hole');">click</a>
    
    0 讨论(0)
提交回复
热议问题