bluemonday: 一款快速的 Golang HTML 清洁器 (受 OWASP Java HTML 清洁器的启发), 用于清理用户生成的 XSS 内容
bluemonday: 一款快速的 Golang HTML 清洁器 (受 OWASP Java HTML 清洁器的启发), 用于清理用户生成的 XSS 内容
and p.AllowAttrs("href").OnElements("a") p.AllowElements("p") html := p.Sanitize( `Google`, ) // Output: // Google fmt.Println(html) } ``` We ship two default policies: 1. `bluemonday.StrictPolicy()` which can be thought of as equivalent to stripping all HTML elements and their attributes as it has nothing on its allowlist. An example usage scenario would be blog post titles where HTML tags are not expected at all and if they are then the elements *and* the content of the elements should be stripped. This is a *very* strict policy. 2. `bluemonday.UGCPolicy()` which allows a broad selection of HTML elements and attributes that are safe for user generated content. Note that this policy does *not* allow iframes, object, embed, styles, script, etc. An example usage scenario would be blog post bodies where a variety of formatting is expected along with the potential for TABLEs and IMGs. ## Policy Building The essence of building a policy is to determine which HTML elements and attributes are considered safe for your scenario. OWASP provide an [XSS prevention cheat sheet](https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet) to help explain the risks, but essentially: 1. Avoid anything other than the standard HTML elements 1. Avoid `script`, `style`, `iframe`, `object`, `embed`, `base` elements that allow code to be executed by the client or third party content to be included that can execute code 1. Avoid anything other than plain HTML attributes with values matched to a regexp Basically, you should be able to describe what HTML is fine for your scenario. If you do not have confidence that you can describe your policy please consider using one of the shipped policies such as `bluemonday.UGCPolicy()`. To create a new policy: ```go p := bluemonday.NewPolicy() ``` To add elements to a policy either add just the elements: ```go p.AllowElements("b", "strong") ``` Or using a regex: _Note: if an element is added by name as shown above, any matching regex will be ignored_ It is also recommended to ensure multiple patterns don't overlap as order of execution is not guaranteed and can result in some rules being missed. ```go p.AllowElementsMatching(regex.MustCompile(`^my-element-`)) ``` Or add elements as a virtue of adding an attribute: ```go // Note the recommended pattern, see the recommendation on using .Matching() below p.AllowAttrs("nowrap").OnElements("td", "th") ``` Again, this also supports a regex pattern match alternative: ```go p.AllowAttrs("nowrap").OnElementsMatching(regex.MustCompile(`^my-element-`)) ``` Attributes can either be added to all elements: ```go p.AllowAttrs("dir").Matching(regexp.MustCompile("(?i)rtl|ltr")).Globally() ``` Or attributes can be added to specific elements: ```go // Not the recommended pattern, see the recommendation on using .Matching() below p.AllowAttrs("value").OnElements("li") ``` It is **always** recommended that an attribute be made to match a pattern. XSS in HTML attributes is very easy otherwise: ```go // \p{L} matches unicode letters, \p{N} matches unicode numbers p.AllowAttrs("title").Matching(regexp.MustCompile(`[\p{L}\p{N}\s\-_',:\[\]!\./\\\(\)&]*`)).Globally() ``` You can stop at any time and call .Sanitize(): ```go // string htmlIn passed in from a HTTP POST htmlOut := p.Sanitize(htmlIn) ``` And you can take any existing policy and extend it: ```go p := bluemonday.UGCPolicy() p.AllowElements("fieldset", "select", "option") ``` ### Inline CSS Although it's possible to handle inline CSS using `AllowAttrs` with a `Matching` rule, writing a single monolithic regular expression to safely process all inline CSS which you wish to allow is not a trivial task. Instead of attempting to do so, you can allow the `style` attribute on whichever element(s) you desire and use style policies to control and sanitize inline styles. It is strongly recommended that you use `Matching` (with a suitable regular expression) `MatchingEnum`, or `MatchingHandler` to ensure each style matches your needs, but default handlers are supplied for most widely used styles. Similar to attributes, you can allow specific CSS properties to be set inline: ```go p.AllowAttrs("style").OnElements("span", "p") // Allow the 'color' property with valid RGB(A) hex values only (on any element allowed a 'style' attribute) p.AllowStyles("color").Matching(regexp.MustCompile("(?i)^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$")).Globally() ``` Additionally, you can allow a CSS property to be set only to an allowed value: ```go p.AllowAttrs("style").OnElements("span", "p") // Allow the 'text-decoration' property to be set to 'underline', 'line-through' or 'none' // on 'span' elements only p.AllowStyles("text-decoration").MatchingEnum("underline", "line-through", "none").OnElements("span") ``` Or you can specify elements based on a regex pattern match: ```go p.AllowAttrs("style").OnElementsMatching(regex.MustCompile(`^my-element-`)) // Allow the 'text-decoration' property to be set to 'underline', 'line-through' or 'none' // on 'span' elements only p.AllowStyles("text-decoration").MatchingEnum("underline", "line-through", "none").OnElementsMatching(regex.MustCompile(`^my-element-`)) ``` If you need more specific checking, you can create a handler that takes in a string and returns a bool to validate the values for a given property. The string parameter has been converted to lowercase and unicode code points have been converted. ```go myHandler := func(value string) bool{ // Validate your input here return true } p.AllowAttrs("style").OnElements("span", "p") // Allow the 'color' property with values validated by the handler (on any element allowed a 'style' attribute) p.AllowStyles("color").MatchingHandler(myHandler).Globally() ``` ### Links Links are difficult beasts to sanitise safely and also one of the biggest attack vectors for malicious content. It is possible to do this: ```go p.AllowAttrs("href").Matching(regexp.MustCompile(`(?i)mailto|https?`)).OnElements("a") ``` But that will not protect you as the regular expression is insufficient in this case to have prevented a malformed value doing something unexpected. We provide some additional global options for safely working with links. `RequireParseableURLs` will ensure that URLs are parseable by Go's `net/url` package: ```go p.RequireParseableURLs(true) ``` If you have enabled parseable URLs then the following option will `AllowRelativeURLs`. By default this is disabled (bluemonday is an allowlist tool... you need to explicitly tell us to permit things) and when disabled it will prevent all local and scheme relative URLs (i.e. `href="localpage.html"`, `href="../home.html"` and even `href="//www.google.com"` are relative): ```go p.AllowRelativeURLs(true) ``` If you have enabled parseable URLs then you can allow the schemes (commonly called protocol when thinking of `http` and `https`) that are permitted. Bear in mind that allowing relative URLs in the above option
暂无开放 Issues,或尚未同步最近议题。